blob: 3d2d0930d87f3bb1abe622f7de9f885a2883616f [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
Douglas Gregor8ca72082011-10-18 21:20:17 +00001377/// \brief Retrieve a printing policy suitable for code completion.
1378static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1379 PrintingPolicy Policy = S.getPrintingPolicy();
1380 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
1386/// \brief Retrieve the string representation of the given type as a string
1387/// that has the appropriate lifetime for code completion.
1388///
1389/// This routine provides a fast path where we provide constant strings for
1390/// common type names.
1391static const char *GetCompletionTypeString(QualType T,
1392 ASTContext &Context,
1393 const PrintingPolicy &Policy,
1394 CodeCompletionAllocator &Allocator) {
1395 if (!T.getLocalQualifiers()) {
1396 // Built-in type names are constant strings.
1397 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1398 return BT->getName(Policy);
1399
1400 // Anonymous tag types are constant strings.
1401 if (const TagType *TagT = dyn_cast<TagType>(T))
1402 if (TagDecl *Tag = TagT->getDecl())
1403 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1404 switch (Tag->getTagKind()) {
1405 case TTK_Struct: return "struct <anonymous>";
1406 case TTK_Class: return "class <anonymous>";
1407 case TTK_Union: return "union <anonymous>";
1408 case TTK_Enum: return "enum <anonymous>";
1409 }
1410 }
1411 }
1412
1413 // Slow path: format the type as a string.
1414 std::string Result;
1415 T.getAsStringInternal(Result, Policy);
1416 return Allocator.CopyString(Result);
1417}
1418
Douglas Gregor01dfea02010-01-10 23:08:15 +00001419/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001420static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001421 Scope *S,
1422 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001423 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001424 CodeCompletionAllocator &Allocator = Results.getAllocator();
1425 CodeCompletionBuilder Builder(Allocator);
1426 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001427
John McCall0a2c5e22010-08-25 06:19:51 +00001428 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001429 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001430 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001431 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001432 if (Results.includeCodePatterns()) {
1433 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001434 Builder.AddTypedTextChunk("namespace");
1435 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1436 Builder.AddPlaceholderChunk("identifier");
1437 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1438 Builder.AddPlaceholderChunk("declarations");
1439 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1440 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1441 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001442 }
1443
Douglas Gregor01dfea02010-01-10 23:08:15 +00001444 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001445 Builder.AddTypedTextChunk("namespace");
1446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1447 Builder.AddPlaceholderChunk("name");
1448 Builder.AddChunk(CodeCompletionString::CK_Equal);
1449 Builder.AddPlaceholderChunk("namespace");
1450 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451
1452 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001453 Builder.AddTypedTextChunk("using");
1454 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1455 Builder.AddTextChunk("namespace");
1456 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1457 Builder.AddPlaceholderChunk("identifier");
1458 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001459
1460 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001461 Builder.AddTypedTextChunk("asm");
1462 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1463 Builder.AddPlaceholderChunk("string-literal");
1464 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1465 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001466
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001467 if (Results.includeCodePatterns()) {
1468 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("template");
1470 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1471 Builder.AddPlaceholderChunk("declaration");
1472 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001473 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001474 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001475
1476 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001477 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001478
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001479 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001480 // Fall through
1481
John McCallf312b1e2010-08-26 23:41:50 +00001482 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001483 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("using");
1486 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1487 Builder.AddPlaceholderChunk("qualifier");
1488 Builder.AddTextChunk("::");
1489 Builder.AddPlaceholderChunk("name");
1490 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001491
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001492 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001493 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001494 Builder.AddTypedTextChunk("using");
1495 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1496 Builder.AddTextChunk("typename");
1497 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1498 Builder.AddPlaceholderChunk("qualifier");
1499 Builder.AddTextChunk("::");
1500 Builder.AddPlaceholderChunk("name");
1501 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001502 }
1503
John McCallf312b1e2010-08-26 23:41:50 +00001504 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001505 AddTypedefResult(Results);
1506
Douglas Gregor01dfea02010-01-10 23:08:15 +00001507 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001508 Builder.AddTypedTextChunk("public");
1509 Builder.AddChunk(CodeCompletionString::CK_Colon);
1510 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001511
1512 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001513 Builder.AddTypedTextChunk("protected");
1514 Builder.AddChunk(CodeCompletionString::CK_Colon);
1515 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001516
1517 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("private");
1519 Builder.AddChunk(CodeCompletionString::CK_Colon);
1520 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001521 }
1522 }
1523 // Fall through
1524
John McCallf312b1e2010-08-26 23:41:50 +00001525 case Sema::PCC_Template:
1526 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001527 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001528 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001529 Builder.AddTypedTextChunk("template");
1530 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1531 Builder.AddPlaceholderChunk("parameters");
1532 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1533 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001534 }
1535
Douglas Gregorbca403c2010-01-13 23:51:12 +00001536 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1537 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001538 break;
1539
John McCallf312b1e2010-08-26 23:41:50 +00001540 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001541 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1542 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1543 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001544 break;
1545
John McCallf312b1e2010-08-26 23:41:50 +00001546 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001547 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1548 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1549 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001550 break;
1551
John McCallf312b1e2010-08-26 23:41:50 +00001552 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001553 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001554 break;
1555
John McCallf312b1e2010-08-26 23:41:50 +00001556 case Sema::PCC_RecoveryInFunction:
1557 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001558 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001559
Douglas Gregorec3310a2011-04-12 02:47:21 +00001560 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1561 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001562 Builder.AddTypedTextChunk("try");
1563 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1564 Builder.AddPlaceholderChunk("statements");
1565 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1566 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1567 Builder.AddTextChunk("catch");
1568 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1569 Builder.AddPlaceholderChunk("declaration");
1570 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1571 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1572 Builder.AddPlaceholderChunk("statements");
1573 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1574 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1575 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001576 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001577 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001578 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("if");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001594
Douglas Gregord8e8a582010-05-25 21:41:55 +00001595 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("switch");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001598 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001599 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001600 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001601 Builder.AddPlaceholderChunk("expression");
1602 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1603 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1604 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1605 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 }
1608
Douglas Gregor01dfea02010-01-10 23:08:15 +00001609 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001610 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001611 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001612 Builder.AddTypedTextChunk("case");
1613 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1614 Builder.AddPlaceholderChunk("expression");
1615 Builder.AddChunk(CodeCompletionString::CK_Colon);
1616 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001617
1618 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001619 Builder.AddTypedTextChunk("default");
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
1621 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001622 }
1623
Douglas Gregord8e8a582010-05-25 21:41:55 +00001624 if (Results.includeCodePatterns()) {
1625 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001626 Builder.AddTypedTextChunk("while");
1627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001628 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001630 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001631 Builder.AddPlaceholderChunk("expression");
1632 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1633 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1634 Builder.AddPlaceholderChunk("statements");
1635 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1636 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1637 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001638
1639 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001640 Builder.AddTypedTextChunk("do");
1641 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1642 Builder.AddPlaceholderChunk("statements");
1643 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1644 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1645 Builder.AddTextChunk("while");
1646 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1647 Builder.AddPlaceholderChunk("expression");
1648 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1649 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001650
Douglas Gregord8e8a582010-05-25 21:41:55 +00001651 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddTypedTextChunk("for");
1653 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001654 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001656 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001657 Builder.AddPlaceholderChunk("init-expression");
1658 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1659 Builder.AddPlaceholderChunk("condition");
1660 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1661 Builder.AddPlaceholderChunk("inc-expression");
1662 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1663 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1664 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1665 Builder.AddPlaceholderChunk("statements");
1666 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1667 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1668 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001669 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670
1671 if (S->getContinueParent()) {
1672 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001673 Builder.AddTypedTextChunk("continue");
1674 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001675 }
1676
1677 if (S->getBreakParent()) {
1678 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001679 Builder.AddTypedTextChunk("break");
1680 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001681 }
1682
1683 // "return expression ;" or "return ;", depending on whether we
1684 // know the function is void or not.
1685 bool isVoid = false;
1686 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1687 isVoid = Function->getResultType()->isVoidType();
1688 else if (ObjCMethodDecl *Method
1689 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1690 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001691 else if (SemaRef.getCurBlock() &&
1692 !SemaRef.getCurBlock()->ReturnType.isNull())
1693 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001695 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001696 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1697 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001698 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001699 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001700
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001701 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001702 Builder.AddTypedTextChunk("goto");
1703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1704 Builder.AddPlaceholderChunk("label");
1705 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001706
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001707 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001708 Builder.AddTypedTextChunk("using");
1709 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1710 Builder.AddTextChunk("namespace");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddPlaceholderChunk("identifier");
1713 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001714 }
1715
1716 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001717 case Sema::PCC_ForInit:
1718 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001719 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001720 // Fall through: conditions and statements can have expressions.
1721
Douglas Gregor02688102010-09-14 23:59:36 +00001722 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001723 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1724 CCC == Sema::PCC_ParenthesizedExpression) {
1725 // (__bridge <type>)<expression>
1726 Builder.AddTypedTextChunk("__bridge");
1727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1728 Builder.AddPlaceholderChunk("type");
1729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1730 Builder.AddPlaceholderChunk("expression");
1731 Results.AddResult(Result(Builder.TakeString()));
1732
1733 // (__bridge_transfer <Objective-C type>)<expression>
1734 Builder.AddTypedTextChunk("__bridge_transfer");
1735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1736 Builder.AddPlaceholderChunk("Objective-C type");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Builder.AddPlaceholderChunk("expression");
1739 Results.AddResult(Result(Builder.TakeString()));
1740
1741 // (__bridge_retained <CF type>)<expression>
1742 Builder.AddTypedTextChunk("__bridge_retained");
1743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1744 Builder.AddPlaceholderChunk("CF type");
1745 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Results.AddResult(Result(Builder.TakeString()));
1748 }
1749 // Fall through
1750
John McCallf312b1e2010-08-26 23:41:50 +00001751 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001752 if (SemaRef.getLangOptions().CPlusPlus) {
1753 // 'this', if we're in a non-static member function.
Douglas Gregor8ca72082011-10-18 21:20:17 +00001754 QualType ThisTy = SemaRef.getCurrentThisType(false);
1755 if (!ThisTy.isNull()) {
1756 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1757 SemaRef.Context,
1758 Policy,
1759 Allocator));
1760 Builder.AddTypedTextChunk("this");
1761 Results.AddResult(Result(Builder.TakeString()));
1762 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001763
Douglas Gregor8ca72082011-10-18 21:20:17 +00001764 // true
1765 Builder.AddResultTypeChunk("bool");
1766 Builder.AddTypedTextChunk("true");
1767 Results.AddResult(Result(Builder.TakeString()));
1768
1769 // false
1770 Builder.AddResultTypeChunk("bool");
1771 Builder.AddTypedTextChunk("false");
1772 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001773
Douglas Gregorec3310a2011-04-12 02:47:21 +00001774 if (SemaRef.getLangOptions().RTTI) {
1775 // dynamic_cast < type-id > ( expression )
1776 Builder.AddTypedTextChunk("dynamic_cast");
1777 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1778 Builder.AddPlaceholderChunk("type");
1779 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1780 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1781 Builder.AddPlaceholderChunk("expression");
1782 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1783 Results.AddResult(Result(Builder.TakeString()));
1784 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001785
1786 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001787 Builder.AddTypedTextChunk("static_cast");
1788 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1789 Builder.AddPlaceholderChunk("type");
1790 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1791 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1792 Builder.AddPlaceholderChunk("expression");
1793 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("reinterpret_cast");
1798 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1799 Builder.AddPlaceholderChunk("type");
1800 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1801 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1802 Builder.AddPlaceholderChunk("expression");
1803 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1804 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001805
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001806 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001807 Builder.AddTypedTextChunk("const_cast");
1808 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1809 Builder.AddPlaceholderChunk("type");
1810 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1811 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1812 Builder.AddPlaceholderChunk("expression");
1813 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1814 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001815
Douglas Gregorec3310a2011-04-12 02:47:21 +00001816 if (SemaRef.getLangOptions().RTTI) {
1817 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001818 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001819 Builder.AddTypedTextChunk("typeid");
1820 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1821 Builder.AddPlaceholderChunk("expression-or-type");
1822 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1823 Results.AddResult(Result(Builder.TakeString()));
1824 }
1825
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001826 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001827 Builder.AddTypedTextChunk("new");
1828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1829 Builder.AddPlaceholderChunk("type");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expressions");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001835 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001836 Builder.AddTypedTextChunk("new");
1837 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1838 Builder.AddPlaceholderChunk("type");
1839 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1840 Builder.AddPlaceholderChunk("size");
1841 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1842 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1843 Builder.AddPlaceholderChunk("expressions");
1844 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1845 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001846
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001847 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001848 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001849 Builder.AddTypedTextChunk("delete");
1850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1851 Builder.AddPlaceholderChunk("expression");
1852 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001853
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001854 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001855 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001856 Builder.AddTypedTextChunk("delete");
1857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1858 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1859 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1860 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1861 Builder.AddPlaceholderChunk("expression");
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001863
Douglas Gregorec3310a2011-04-12 02:47:21 +00001864 if (SemaRef.getLangOptions().CXXExceptions) {
1865 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001866 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001867 Builder.AddTypedTextChunk("throw");
1868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1869 Builder.AddPlaceholderChunk("expression");
1870 Results.AddResult(Result(Builder.TakeString()));
1871 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001872
Douglas Gregor12e13132010-05-26 22:00:08 +00001873 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001874
1875 if (SemaRef.getLangOptions().CPlusPlus0x) {
1876 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001877 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001878 Builder.AddTypedTextChunk("nullptr");
1879 Results.AddResult(Result(Builder.TakeString()));
1880
1881 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001882 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001883 Builder.AddTypedTextChunk("alignof");
1884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1885 Builder.AddPlaceholderChunk("type");
1886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1887 Results.AddResult(Result(Builder.TakeString()));
1888
1889 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001890 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001891 Builder.AddTypedTextChunk("noexcept");
1892 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1893 Builder.AddPlaceholderChunk("expression");
1894 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1895 Results.AddResult(Result(Builder.TakeString()));
1896
1897 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001898 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001899 Builder.AddTypedTextChunk("sizeof...");
1900 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1901 Builder.AddPlaceholderChunk("parameter-pack");
1902 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1903 Results.AddResult(Result(Builder.TakeString()));
1904 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001905 }
1906
1907 if (SemaRef.getLangOptions().ObjC1) {
1908 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001909 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1910 // The interface can be NULL.
1911 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001912 if (ID->getSuperClass()) {
1913 std::string SuperType;
1914 SuperType = ID->getSuperClass()->getNameAsString();
1915 if (Method->isInstanceMethod())
1916 SuperType += " *";
1917
1918 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1919 Builder.AddTypedTextChunk("super");
1920 Results.AddResult(Result(Builder.TakeString()));
1921 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001922 }
1923
Douglas Gregorbca403c2010-01-13 23:51:12 +00001924 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001925 }
1926
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001927 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001928 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001929 Builder.AddTypedTextChunk("sizeof");
1930 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1931 Builder.AddPlaceholderChunk("expression-or-type");
1932 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1933 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001934 break;
1935 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001936
John McCallf312b1e2010-08-26 23:41:50 +00001937 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001938 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001939 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001940 }
1941
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001942 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1943 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001944
John McCallf312b1e2010-08-26 23:41:50 +00001945 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001946 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001947}
1948
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001949/// \brief If the given declaration has an associated type, add it as a result
1950/// type chunk.
1951static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001952 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001953 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001954 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001955 if (!ND)
1956 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001957
1958 // Skip constructors and conversion functions, which have their return types
1959 // built into their names.
1960 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1961 return;
1962
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001963 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001964 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001965 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1966 T = Function->getResultType();
1967 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1968 T = Method->getResultType();
1969 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1970 T = FunTmpl->getTemplatedDecl()->getResultType();
1971 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1972 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1973 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1974 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001975 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001976 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001977 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001978 T = Property->getType();
1979
1980 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1981 return;
1982
Douglas Gregor8987b232011-09-27 23:30:47 +00001983 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001984 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001985}
1986
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001987static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001988 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001989 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1990 if (Sentinel->getSentinel() == 0) {
1991 if (Context.getLangOptions().ObjC1 &&
1992 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001993 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001994 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001995 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001996 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001997 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001998 }
1999}
2000
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002001static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2002 std::string Result;
2003 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002004 Result += "in ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002005 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002006 Result += "inout ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002007 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002008 Result += "out ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002009 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002010 Result += "bycopy ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002011 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002012 Result += "byref ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002013 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002014 Result += "oneway ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002015 return Result;
2016}
2017
Douglas Gregor83482d12010-08-24 16:15:59 +00002018static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002019 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002020 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002021 bool SuppressName = false,
2022 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002023 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2024 if (Param->getType()->isDependentType() ||
2025 !Param->getType()->isBlockPointerType()) {
2026 // The argument for a dependent or non-block parameter is a placeholder
2027 // containing that parameter's type.
2028 std::string Result;
2029
Douglas Gregoraba48082010-08-29 19:47:46 +00002030 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002031 Result = Param->getIdentifier()->getName();
2032
John McCallf85e1932011-06-15 23:02:42 +00002033 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002034
2035 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002036 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2037 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002038 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002039 Result += Param->getIdentifier()->getName();
2040 }
2041 return Result;
2042 }
2043
2044 // The argument for a block pointer parameter is a block literal with
2045 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002046 FunctionTypeLoc *Block = 0;
2047 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002048 TypeLoc TL;
2049 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2050 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2051 while (true) {
2052 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002053 if (!SuppressBlock) {
2054 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2055 if (TypeSourceInfo *InnerTSInfo
2056 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2057 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2058 continue;
2059 }
2060 }
2061
2062 // Look through qualified types
2063 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2064 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002065 continue;
2066 }
2067 }
2068
Douglas Gregor83482d12010-08-24 16:15:59 +00002069 // Try to get the function prototype behind the block pointer type,
2070 // then we're done.
2071 if (BlockPointerTypeLoc *BlockPtr
2072 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002073 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002074 Block = dyn_cast<FunctionTypeLoc>(&TL);
2075 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002076 }
2077 break;
2078 }
2079 }
2080
2081 if (!Block) {
2082 // We were unable to find a FunctionProtoTypeLoc with parameter names
2083 // for the block; just use the parameter type as a placeholder.
2084 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002085 if (!ObjCMethodParam && Param->getIdentifier())
2086 Result = Param->getIdentifier()->getName();
2087
John McCallf85e1932011-06-15 23:02:42 +00002088 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002089
2090 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002091 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2092 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002093 if (Param->getIdentifier())
2094 Result += Param->getIdentifier()->getName();
2095 }
2096
2097 return Result;
2098 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002099
Douglas Gregor83482d12010-08-24 16:15:59 +00002100 // We have the function prototype behind the block pointer type, as it was
2101 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002102 std::string Result;
2103 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002104 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002105 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002106
2107 // Format the parameter list.
2108 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002109 if (!BlockProto || Block->getNumArgs() == 0) {
2110 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002111 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002112 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002113 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002114 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002115 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002116 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2117 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002118 Params += ", ";
2119 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2120 /*SuppressName=*/false,
2121 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002122
Douglas Gregor830072c2011-02-15 22:37:09 +00002123 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002124 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002125 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002126 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002127 }
Douglas Gregor38276252010-09-08 22:47:51 +00002128
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002129 if (SuppressBlock) {
2130 // Format as a parameter.
2131 Result = Result + " (^";
2132 if (Param->getIdentifier())
2133 Result += Param->getIdentifier()->getName();
2134 Result += ")";
2135 Result += Params;
2136 } else {
2137 // Format as a block literal argument.
2138 Result = '^' + Result;
2139 Result += Params;
2140
2141 if (Param->getIdentifier())
2142 Result += Param->getIdentifier()->getName();
2143 }
2144
Douglas Gregor83482d12010-08-24 16:15:59 +00002145 return Result;
2146}
2147
Douglas Gregor86d9a522009-09-21 16:56:56 +00002148/// \brief Add function parameter chunks to the given code completion string.
2149static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002150 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002151 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002152 CodeCompletionBuilder &Result,
2153 unsigned Start = 0,
2154 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002155 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002156 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002157
Douglas Gregor218937c2011-02-01 19:23:04 +00002158 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002159 ParmVarDecl *Param = Function->getParamDecl(P);
2160
Douglas Gregor218937c2011-02-01 19:23:04 +00002161 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002162 // When we see an optional default argument, put that argument and
2163 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002164 CodeCompletionBuilder Opt(Result.getAllocator());
2165 if (!FirstParameter)
2166 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002167 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002168 Result.AddOptionalChunk(Opt.TakeString());
2169 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002170 }
2171
Douglas Gregor218937c2011-02-01 19:23:04 +00002172 if (FirstParameter)
2173 FirstParameter = false;
2174 else
2175 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2176
2177 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002178
2179 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002180 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2181 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002182
Douglas Gregore17794f2010-08-31 05:13:43 +00002183 if (Function->isVariadic() && P == N - 1)
2184 PlaceholderStr += ", ...";
2185
Douglas Gregor86d9a522009-09-21 16:56:56 +00002186 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002187 Result.AddPlaceholderChunk(
2188 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002189 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002190
2191 if (const FunctionProtoType *Proto
2192 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002193 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002194 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002195 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002196
Douglas Gregor218937c2011-02-01 19:23:04 +00002197 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002198 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002199}
2200
2201/// \brief Add template parameter chunks to the given code completion string.
2202static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002203 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002204 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002205 CodeCompletionBuilder &Result,
2206 unsigned MaxParameters = 0,
2207 unsigned Start = 0,
2208 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002209 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002210 bool FirstParameter = true;
2211
2212 TemplateParameterList *Params = Template->getTemplateParameters();
2213 TemplateParameterList::iterator PEnd = Params->end();
2214 if (MaxParameters)
2215 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002216 for (TemplateParameterList::iterator P = Params->begin() + Start;
2217 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002218 bool HasDefaultArg = false;
2219 std::string PlaceholderStr;
2220 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2221 if (TTP->wasDeclaredWithTypename())
2222 PlaceholderStr = "typename";
2223 else
2224 PlaceholderStr = "class";
2225
2226 if (TTP->getIdentifier()) {
2227 PlaceholderStr += ' ';
2228 PlaceholderStr += TTP->getIdentifier()->getName();
2229 }
2230
2231 HasDefaultArg = TTP->hasDefaultArgument();
2232 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002233 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002234 if (NTTP->getIdentifier())
2235 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002236 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002237 HasDefaultArg = NTTP->hasDefaultArgument();
2238 } else {
2239 assert(isa<TemplateTemplateParmDecl>(*P));
2240 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2241
2242 // Since putting the template argument list into the placeholder would
2243 // be very, very long, we just use an abbreviation.
2244 PlaceholderStr = "template<...> class";
2245 if (TTP->getIdentifier()) {
2246 PlaceholderStr += ' ';
2247 PlaceholderStr += TTP->getIdentifier()->getName();
2248 }
2249
2250 HasDefaultArg = TTP->hasDefaultArgument();
2251 }
2252
Douglas Gregor218937c2011-02-01 19:23:04 +00002253 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002254 // When we see an optional default argument, put that argument and
2255 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002256 CodeCompletionBuilder Opt(Result.getAllocator());
2257 if (!FirstParameter)
2258 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002259 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002260 P - Params->begin(), true);
2261 Result.AddOptionalChunk(Opt.TakeString());
2262 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002263 }
2264
Douglas Gregor218937c2011-02-01 19:23:04 +00002265 InDefaultArg = false;
2266
Douglas Gregor86d9a522009-09-21 16:56:56 +00002267 if (FirstParameter)
2268 FirstParameter = false;
2269 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002271
2272 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002273 Result.AddPlaceholderChunk(
2274 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002275 }
2276}
2277
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002278/// \brief Add a qualifier to the given code-completion string, if the
2279/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002280static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002281AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002282 NestedNameSpecifier *Qualifier,
2283 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002284 ASTContext &Context,
2285 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002286 if (!Qualifier)
2287 return;
2288
2289 std::string PrintedNNS;
2290 {
2291 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002292 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002293 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002294 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002295 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002296 else
Douglas Gregordae68752011-02-01 22:57:45 +00002297 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002298}
2299
Douglas Gregor218937c2011-02-01 19:23:04 +00002300static void
2301AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2302 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002303 const FunctionProtoType *Proto
2304 = Function->getType()->getAs<FunctionProtoType>();
2305 if (!Proto || !Proto->getTypeQuals())
2306 return;
2307
Douglas Gregora63f6de2011-02-01 21:15:40 +00002308 // FIXME: Add ref-qualifier!
2309
2310 // Handle single qualifiers without copying
2311 if (Proto->getTypeQuals() == Qualifiers::Const) {
2312 Result.AddInformativeChunk(" const");
2313 return;
2314 }
2315
2316 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2317 Result.AddInformativeChunk(" volatile");
2318 return;
2319 }
2320
2321 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2322 Result.AddInformativeChunk(" restrict");
2323 return;
2324 }
2325
2326 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002327 std::string QualsStr;
2328 if (Proto->getTypeQuals() & Qualifiers::Const)
2329 QualsStr += " const";
2330 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2331 QualsStr += " volatile";
2332 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2333 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002334 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002335}
2336
Douglas Gregor6f942b22010-09-21 16:06:22 +00002337/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002338static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2339 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002340 typedef CodeCompletionString::Chunk Chunk;
2341
2342 DeclarationName Name = ND->getDeclName();
2343 if (!Name)
2344 return;
2345
2346 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002347 case DeclarationName::CXXOperatorName: {
2348 const char *OperatorName = 0;
2349 switch (Name.getCXXOverloadedOperator()) {
2350 case OO_None:
2351 case OO_Conditional:
2352 case NUM_OVERLOADED_OPERATORS:
2353 OperatorName = "operator";
2354 break;
2355
2356#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2357 case OO_##Name: OperatorName = "operator" Spelling; break;
2358#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2359#include "clang/Basic/OperatorKinds.def"
2360
2361 case OO_New: OperatorName = "operator new"; break;
2362 case OO_Delete: OperatorName = "operator delete"; break;
2363 case OO_Array_New: OperatorName = "operator new[]"; break;
2364 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2365 case OO_Call: OperatorName = "operator()"; break;
2366 case OO_Subscript: OperatorName = "operator[]"; break;
2367 }
2368 Result.AddTypedTextChunk(OperatorName);
2369 break;
2370 }
2371
Douglas Gregor6f942b22010-09-21 16:06:22 +00002372 case DeclarationName::Identifier:
2373 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002374 case DeclarationName::CXXDestructorName:
2375 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002376 Result.AddTypedTextChunk(
2377 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002378 break;
2379
2380 case DeclarationName::CXXUsingDirective:
2381 case DeclarationName::ObjCZeroArgSelector:
2382 case DeclarationName::ObjCOneArgSelector:
2383 case DeclarationName::ObjCMultiArgSelector:
2384 break;
2385
2386 case DeclarationName::CXXConstructorName: {
2387 CXXRecordDecl *Record = 0;
2388 QualType Ty = Name.getCXXNameType();
2389 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2390 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2391 else if (const InjectedClassNameType *InjectedTy
2392 = Ty->getAs<InjectedClassNameType>())
2393 Record = InjectedTy->getDecl();
2394 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002395 Result.AddTypedTextChunk(
2396 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002397 break;
2398 }
2399
Douglas Gregordae68752011-02-01 22:57:45 +00002400 Result.AddTypedTextChunk(
2401 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002402 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002403 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002404 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002405 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002406 }
2407 break;
2408 }
2409 }
2410}
2411
Douglas Gregor86d9a522009-09-21 16:56:56 +00002412/// \brief If possible, create a new code completion string for the given
2413/// result.
2414///
2415/// \returns Either a new, heap-allocated code completion string describing
2416/// how to use this result, or NULL to indicate that the string or name of the
2417/// result is all that is needed.
2418CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002419CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002420 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002421 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002422 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002423
Douglas Gregor8987b232011-09-27 23:30:47 +00002424 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002425 if (Kind == RK_Pattern) {
2426 Pattern->Priority = Priority;
2427 Pattern->Availability = Availability;
2428 return Pattern;
2429 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002430
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002431 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002432 Result.AddTypedTextChunk(Keyword);
2433 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002434 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002435
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002436 if (Kind == RK_Macro) {
2437 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002438 assert(MI && "Not a macro?");
2439
Douglas Gregordae68752011-02-01 22:57:45 +00002440 Result.AddTypedTextChunk(
2441 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002442
2443 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002444 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002445
2446 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002447 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002448 bool CombineVariadicArgument = false;
2449 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2450 if (MI->isVariadic() && AEnd - A > 1) {
2451 AEnd -= 2;
2452 CombineVariadicArgument = true;
2453 }
2454 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002455 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002456 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002457
Douglas Gregore4244702011-07-30 08:17:44 +00002458 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002459 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002460 Result.AddPlaceholderChunk(
2461 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002462 continue;
2463 }
2464
Douglas Gregore4244702011-07-30 08:17:44 +00002465 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002466 // variadic macros, providing a single placeholder for the rest of the
2467 // arguments.
2468 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002469 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002470 else {
2471 std::string Arg = (*A)->getName();
2472 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002473 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002474 }
2475 }
Douglas Gregore4244702011-07-30 08:17:44 +00002476
2477 if (CombineVariadicArgument) {
2478 // Handle the next-to-last argument, combining it with the variadic
2479 // argument.
2480 std::string LastArg = (*A)->getName();
2481 ++A;
2482 if ((*A)->isStr("__VA_ARGS__"))
2483 LastArg += ", ...";
2484 else
2485 LastArg += ", " + (*A)->getName().str() + "...";
2486 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2487 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002488 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2489 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002490 }
2491
Douglas Gregord8e8a582010-05-25 21:41:55 +00002492 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002493 NamedDecl *ND = Declaration;
2494
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002495 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002496 Result.AddTypedTextChunk(
2497 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002498 Result.AddTextChunk("::");
2499 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002500 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002501
2502 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2503 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2504 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2505 }
2506 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002507
Douglas Gregor8987b232011-09-27 23:30:47 +00002508 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002509
Douglas Gregor86d9a522009-09-21 16:56:56 +00002510 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002511 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002512 S.Context, Policy);
2513 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002514 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002515 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002516 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002517 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002518 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002519 }
2520
2521 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002522 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002523 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002524 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002525 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002526
Douglas Gregor86d9a522009-09-21 16:56:56 +00002527 // Figure out which template parameters are deduced (or have default
2528 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002529 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002530 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2531 unsigned LastDeducibleArgument;
2532 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2533 --LastDeducibleArgument) {
2534 if (!Deduced[LastDeducibleArgument - 1]) {
2535 // C++0x: Figure out if the template argument has a default. If so,
2536 // the user doesn't need to type this argument.
2537 // FIXME: We need to abstract template parameters better!
2538 bool HasDefaultArg = false;
2539 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002540 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002541 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2542 HasDefaultArg = TTP->hasDefaultArgument();
2543 else if (NonTypeTemplateParmDecl *NTTP
2544 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2545 HasDefaultArg = NTTP->hasDefaultArgument();
2546 else {
2547 assert(isa<TemplateTemplateParmDecl>(Param));
2548 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002549 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002550 }
2551
2552 if (!HasDefaultArg)
2553 break;
2554 }
2555 }
2556
2557 if (LastDeducibleArgument) {
2558 // Some of the function template arguments cannot be deduced from a
2559 // function call, so we introduce an explicit template argument list
2560 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002561 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002562 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002563 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002564 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002565 }
2566
2567 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002568 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002569 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002570 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002571 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002572 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002573 }
2574
2575 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002576 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002577 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002578 Result.AddTypedTextChunk(
2579 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002580 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002581 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002582 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2583 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002584 }
2585
Douglas Gregor9630eb62009-11-17 16:44:22 +00002586 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002587 Selector Sel = Method->getSelector();
2588 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002589 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002590 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002591 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002592 }
2593
Douglas Gregor813d8342011-02-18 22:29:55 +00002594 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002595 SelName += ':';
2596 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002597 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002598 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002599 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002600
2601 // If there is only one parameter, and we're past it, add an empty
2602 // typed-text chunk since there is nothing to type.
2603 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002604 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002605 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002606 unsigned Idx = 0;
2607 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2608 PEnd = Method->param_end();
2609 P != PEnd; (void)++P, ++Idx) {
2610 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002611 std::string Keyword;
2612 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002613 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002614 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002615 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002616 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002617 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002618 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002619 else
Douglas Gregordae68752011-02-01 22:57:45 +00002620 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002621 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002622
2623 // If we're before the starting parameter, skip the placeholder.
2624 if (Idx < StartParameter)
2625 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002626
2627 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002628
2629 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002630 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002631 else {
John McCallf85e1932011-06-15 23:02:42 +00002632 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002633 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2634 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002635 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002636 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002637 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002638 }
2639
Douglas Gregore17794f2010-08-31 05:13:43 +00002640 if (Method->isVariadic() && (P + 1) == PEnd)
2641 Arg += ", ...";
2642
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002643 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002644 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002645 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002646 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002647 else
Douglas Gregordae68752011-02-01 22:57:45 +00002648 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002649 }
2650
Douglas Gregor2a17af02009-12-23 00:21:46 +00002651 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002652 if (Method->param_size() == 0) {
2653 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002654 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002655 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002656 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002657 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002658 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002659 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002660
2661 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002662 }
2663
Douglas Gregor218937c2011-02-01 19:23:04 +00002664 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002665 }
2666
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002667 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002668 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002669 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002670
Douglas Gregordae68752011-02-01 22:57:45 +00002671 Result.AddTypedTextChunk(
2672 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002673 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002674}
2675
Douglas Gregor86d802e2009-09-23 00:34:09 +00002676CodeCompletionString *
2677CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2678 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002679 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002680 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002681 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002682 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002683
Douglas Gregor218937c2011-02-01 19:23:04 +00002684 // FIXME: Set priority, availability appropriately.
2685 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002686 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002687 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002688 const FunctionProtoType *Proto
2689 = dyn_cast<FunctionProtoType>(getFunctionType());
2690 if (!FDecl && !Proto) {
2691 // Function without a prototype. Just give the return type and a
2692 // highlighted ellipsis.
2693 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002694 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002695 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002696 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002697 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2698 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2699 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2700 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002701 }
2702
2703 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002704 Result.AddTextChunk(
2705 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002706 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002707 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002708 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002709 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002710
Douglas Gregor218937c2011-02-01 19:23:04 +00002711 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002712 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2713 for (unsigned I = 0; I != NumParams; ++I) {
2714 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002715 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002716
2717 std::string ArgString;
2718 QualType ArgType;
2719
2720 if (FDecl) {
2721 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2722 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2723 } else {
2724 ArgType = Proto->getArgType(I);
2725 }
2726
John McCallf85e1932011-06-15 23:02:42 +00002727 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002728
2729 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002730 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002731 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002732 else
Douglas Gregordae68752011-02-01 22:57:45 +00002733 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002734 }
2735
2736 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002737 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002738 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002739 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002740 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002741 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002742 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002743 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002744
Douglas Gregor218937c2011-02-01 19:23:04 +00002745 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002746}
2747
Chris Lattner5f9e2722011-07-23 10:55:15 +00002748unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002749 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002750 bool PreferredTypeIsPointer) {
2751 unsigned Priority = CCP_Macro;
2752
Douglas Gregorb05496d2010-09-20 21:11:48 +00002753 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2754 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2755 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002756 Priority = CCP_Constant;
2757 if (PreferredTypeIsPointer)
2758 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002759 }
2760 // Treat "YES", "NO", "true", and "false" as constants.
2761 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2762 MacroName.equals("true") || MacroName.equals("false"))
2763 Priority = CCP_Constant;
2764 // Treat "bool" as a type.
2765 else if (MacroName.equals("bool"))
2766 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2767
Douglas Gregor1827e102010-08-16 16:18:59 +00002768
2769 return Priority;
2770}
2771
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002772CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2773 if (!D)
2774 return CXCursor_UnexposedDecl;
2775
2776 switch (D->getKind()) {
2777 case Decl::Enum: return CXCursor_EnumDecl;
2778 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2779 case Decl::Field: return CXCursor_FieldDecl;
2780 case Decl::Function:
2781 return CXCursor_FunctionDecl;
2782 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2783 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2784 case Decl::ObjCClass:
2785 // FIXME
2786 return CXCursor_UnexposedDecl;
2787 case Decl::ObjCForwardProtocol:
2788 // FIXME
2789 return CXCursor_UnexposedDecl;
2790 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2791 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2792 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2793 case Decl::ObjCMethod:
2794 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2795 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2796 case Decl::CXXMethod: return CXCursor_CXXMethod;
2797 case Decl::CXXConstructor: return CXCursor_Constructor;
2798 case Decl::CXXDestructor: return CXCursor_Destructor;
2799 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2800 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2801 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2802 case Decl::ParmVar: return CXCursor_ParmDecl;
2803 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002804 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002805 case Decl::Var: return CXCursor_VarDecl;
2806 case Decl::Namespace: return CXCursor_Namespace;
2807 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2808 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2809 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2810 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2811 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2812 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002813 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002814 case Decl::ClassTemplatePartialSpecialization:
2815 return CXCursor_ClassTemplatePartialSpecialization;
2816 case Decl::UsingDirective: return CXCursor_UsingDirective;
2817
2818 case Decl::Using:
2819 case Decl::UnresolvedUsingValue:
2820 case Decl::UnresolvedUsingTypename:
2821 return CXCursor_UsingDeclaration;
2822
Douglas Gregor352697a2011-06-03 23:08:58 +00002823 case Decl::ObjCPropertyImpl:
2824 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2825 case ObjCPropertyImplDecl::Dynamic:
2826 return CXCursor_ObjCDynamicDecl;
2827
2828 case ObjCPropertyImplDecl::Synthesize:
2829 return CXCursor_ObjCSynthesizeDecl;
2830 }
2831 break;
2832
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002833 default:
2834 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2835 switch (TD->getTagKind()) {
2836 case TTK_Struct: return CXCursor_StructDecl;
2837 case TTK_Class: return CXCursor_ClassDecl;
2838 case TTK_Union: return CXCursor_UnionDecl;
2839 case TTK_Enum: return CXCursor_EnumDecl;
2840 }
2841 }
2842 }
2843
2844 return CXCursor_UnexposedDecl;
2845}
2846
Douglas Gregor590c7d52010-07-08 20:55:51 +00002847static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2848 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002849 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002850
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002851 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002852
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002853 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2854 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002855 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002856 Results.AddResult(Result(M->first,
2857 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002858 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002859 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002860 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002861
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002862 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002863
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002864}
2865
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002866static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2867 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002868 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002869
2870 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002871
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002872 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2873 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2874 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2875 Results.AddResult(Result("__func__", CCP_Constant));
2876 Results.ExitScope();
2877}
2878
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002879static void HandleCodeCompleteResults(Sema *S,
2880 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002881 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002882 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002883 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002884 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002885 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002886}
2887
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002888static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2889 Sema::ParserCompletionContext PCC) {
2890 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002891 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002892 return CodeCompletionContext::CCC_TopLevel;
2893
John McCallf312b1e2010-08-26 23:41:50 +00002894 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002895 return CodeCompletionContext::CCC_ClassStructUnion;
2896
John McCallf312b1e2010-08-26 23:41:50 +00002897 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002898 return CodeCompletionContext::CCC_ObjCInterface;
2899
John McCallf312b1e2010-08-26 23:41:50 +00002900 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002901 return CodeCompletionContext::CCC_ObjCImplementation;
2902
John McCallf312b1e2010-08-26 23:41:50 +00002903 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002904 return CodeCompletionContext::CCC_ObjCIvarList;
2905
John McCallf312b1e2010-08-26 23:41:50 +00002906 case Sema::PCC_Template:
2907 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002908 if (S.CurContext->isFileContext())
2909 return CodeCompletionContext::CCC_TopLevel;
2910 else if (S.CurContext->isRecord())
2911 return CodeCompletionContext::CCC_ClassStructUnion;
2912 else
2913 return CodeCompletionContext::CCC_Other;
2914
John McCallf312b1e2010-08-26 23:41:50 +00002915 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002916 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002917
John McCallf312b1e2010-08-26 23:41:50 +00002918 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002919 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2920 S.getLangOptions().ObjC1)
2921 return CodeCompletionContext::CCC_ParenthesizedExpression;
2922 else
2923 return CodeCompletionContext::CCC_Expression;
2924
2925 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002926 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002927 return CodeCompletionContext::CCC_Expression;
2928
John McCallf312b1e2010-08-26 23:41:50 +00002929 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002930 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002931
John McCallf312b1e2010-08-26 23:41:50 +00002932 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002933 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002934
2935 case Sema::PCC_ParenthesizedExpression:
2936 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002937
2938 case Sema::PCC_LocalDeclarationSpecifiers:
2939 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002940 }
2941
2942 return CodeCompletionContext::CCC_Other;
2943}
2944
Douglas Gregorf6961522010-08-27 21:18:54 +00002945/// \brief If we're in a C++ virtual member function, add completion results
2946/// that invoke the functions we override, since it's common to invoke the
2947/// overridden function as well as adding new functionality.
2948///
2949/// \param S The semantic analysis object for which we are generating results.
2950///
2951/// \param InContext This context in which the nested-name-specifier preceding
2952/// the code-completion point
2953static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2954 ResultBuilder &Results) {
2955 // Look through blocks.
2956 DeclContext *CurContext = S.CurContext;
2957 while (isa<BlockDecl>(CurContext))
2958 CurContext = CurContext->getParent();
2959
2960
2961 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2962 if (!Method || !Method->isVirtual())
2963 return;
2964
2965 // We need to have names for all of the parameters, if we're going to
2966 // generate a forwarding call.
2967 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2968 PEnd = Method->param_end();
2969 P != PEnd;
2970 ++P) {
2971 if (!(*P)->getDeclName())
2972 return;
2973 }
2974
Douglas Gregor8987b232011-09-27 23:30:47 +00002975 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002976 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2977 MEnd = Method->end_overridden_methods();
2978 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002979 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002980 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2981 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2982 continue;
2983
2984 // If we need a nested-name-specifier, add one now.
2985 if (!InContext) {
2986 NestedNameSpecifier *NNS
2987 = getRequiredQualification(S.Context, CurContext,
2988 Overridden->getDeclContext());
2989 if (NNS) {
2990 std::string Str;
2991 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002992 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002993 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002994 }
2995 } else if (!InContext->Equals(Overridden->getDeclContext()))
2996 continue;
2997
Douglas Gregordae68752011-02-01 22:57:45 +00002998 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002999 Overridden->getNameAsString()));
3000 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003001 bool FirstParam = true;
3002 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3003 PEnd = Method->param_end();
3004 P != PEnd; ++P) {
3005 if (FirstParam)
3006 FirstParam = false;
3007 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003008 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003009
Douglas Gregordae68752011-02-01 22:57:45 +00003010 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003011 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003012 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003013 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3014 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003015 CCP_SuperCompletion,
3016 CXCursor_CXXMethod));
3017 Results.Ignore(Overridden);
3018 }
3019}
3020
Douglas Gregor01dfea02010-01-10 23:08:15 +00003021void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003022 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003023 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003024 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003025 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003026 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003027
Douglas Gregor01dfea02010-01-10 23:08:15 +00003028 // Determine how to filter results, e.g., so that the names of
3029 // values (functions, enumerators, function templates, etc.) are
3030 // only allowed where we can have an expression.
3031 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003032 case PCC_Namespace:
3033 case PCC_Class:
3034 case PCC_ObjCInterface:
3035 case PCC_ObjCImplementation:
3036 case PCC_ObjCInstanceVariableList:
3037 case PCC_Template:
3038 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003039 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003040 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003041 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3042 break;
3043
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003044 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003045 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003046 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003047 case PCC_ForInit:
3048 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003049 if (WantTypesInContext(CompletionContext, getLangOptions()))
3050 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3051 else
3052 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003053
3054 if (getLangOptions().CPlusPlus)
3055 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003056 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003057
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003058 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003059 // Unfiltered
3060 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003061 }
3062
Douglas Gregor3cdee122010-08-26 16:36:48 +00003063 // If we are in a C++ non-static member function, check the qualifiers on
3064 // the member function to filter/prioritize the results list.
3065 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3066 if (CurMethod->isInstance())
3067 Results.setObjectTypeQualifiers(
3068 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3069
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003070 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003071 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3072 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003073
Douglas Gregorbca403c2010-01-13 23:51:12 +00003074 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003075 Results.ExitScope();
3076
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003077 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003078 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003079 case PCC_Expression:
3080 case PCC_Statement:
3081 case PCC_RecoveryInFunction:
3082 if (S->getFnParent())
3083 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3084 break;
3085
3086 case PCC_Namespace:
3087 case PCC_Class:
3088 case PCC_ObjCInterface:
3089 case PCC_ObjCImplementation:
3090 case PCC_ObjCInstanceVariableList:
3091 case PCC_Template:
3092 case PCC_MemberTemplate:
3093 case PCC_ForInit:
3094 case PCC_Condition:
3095 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003096 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003097 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003098 }
3099
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003100 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003101 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003102
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003103 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003104 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003105}
3106
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003107static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3108 ParsedType Receiver,
3109 IdentifierInfo **SelIdents,
3110 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003111 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003112 bool IsSuper,
3113 ResultBuilder &Results);
3114
3115void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3116 bool AllowNonIdentifiers,
3117 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003118 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003119 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003120 AllowNestedNameSpecifiers
3121 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3122 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003123 Results.EnterNewScope();
3124
3125 // Type qualifiers can come after names.
3126 Results.AddResult(Result("const"));
3127 Results.AddResult(Result("volatile"));
3128 if (getLangOptions().C99)
3129 Results.AddResult(Result("restrict"));
3130
3131 if (getLangOptions().CPlusPlus) {
3132 if (AllowNonIdentifiers) {
3133 Results.AddResult(Result("operator"));
3134 }
3135
3136 // Add nested-name-specifiers.
3137 if (AllowNestedNameSpecifiers) {
3138 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003139 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003140 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3141 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3142 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003143 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003144 }
3145 }
3146 Results.ExitScope();
3147
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003148 // If we're in a context where we might have an expression (rather than a
3149 // declaration), and what we've seen so far is an Objective-C type that could
3150 // be a receiver of a class message, this may be a class message send with
3151 // the initial opening bracket '[' missing. Add appropriate completions.
3152 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3153 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3154 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3155 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3156 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3157 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3158 DS.getTypeQualifiers() == 0 &&
3159 S &&
3160 (S->getFlags() & Scope::DeclScope) != 0 &&
3161 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3162 Scope::FunctionPrototypeScope |
3163 Scope::AtCatchScope)) == 0) {
3164 ParsedType T = DS.getRepAsType();
3165 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003166 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003167 }
3168
Douglas Gregor4497dd42010-08-24 04:59:56 +00003169 // Note that we intentionally suppress macro results here, since we do not
3170 // encourage using macros to produce the names of entities.
3171
Douglas Gregor52779fb2010-09-23 23:01:17 +00003172 HandleCodeCompleteResults(this, CodeCompleter,
3173 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003174 Results.data(), Results.size());
3175}
3176
Douglas Gregorfb629412010-08-23 21:17:50 +00003177struct Sema::CodeCompleteExpressionData {
3178 CodeCompleteExpressionData(QualType PreferredType = QualType())
3179 : PreferredType(PreferredType), IntegralConstantExpression(false),
3180 ObjCCollection(false) { }
3181
3182 QualType PreferredType;
3183 bool IntegralConstantExpression;
3184 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003185 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003186};
3187
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003188/// \brief Perform code-completion in an expression context when we know what
3189/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003190///
3191/// \param IntegralConstantExpression Only permit integral constant
3192/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003193void Sema::CodeCompleteExpression(Scope *S,
3194 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003195 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003196 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3197 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003198 if (Data.ObjCCollection)
3199 Results.setFilter(&ResultBuilder::IsObjCCollection);
3200 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003201 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003202 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003203 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3204 else
3205 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003206
3207 if (!Data.PreferredType.isNull())
3208 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3209
3210 // Ignore any declarations that we were told that we don't care about.
3211 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3212 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003213
3214 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003215 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3216 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003217
3218 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003219 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003220 Results.ExitScope();
3221
Douglas Gregor590c7d52010-07-08 20:55:51 +00003222 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003223 if (!Data.PreferredType.isNull())
3224 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3225 || Data.PreferredType->isMemberPointerType()
3226 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003227
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003228 if (S->getFnParent() &&
3229 !Data.ObjCCollection &&
3230 !Data.IntegralConstantExpression)
3231 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3232
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003233 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003234 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003235 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003236 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3237 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003238 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003239}
3240
Douglas Gregorac5fd842010-09-18 01:28:11 +00003241void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3242 if (E.isInvalid())
3243 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3244 else if (getLangOptions().ObjC1)
3245 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003246}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003247
Douglas Gregor73449212010-12-09 23:01:55 +00003248/// \brief The set of properties that have already been added, referenced by
3249/// property name.
3250typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3251
Douglas Gregor95ac6552009-11-18 01:29:26 +00003252static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003253 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003254 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003255 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003256 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003257 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003258 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003259
3260 // Add properties in this container.
3261 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3262 PEnd = Container->prop_end();
3263 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003264 ++P) {
3265 if (AddedProperties.insert(P->getIdentifier()))
3266 Results.MaybeAddResult(Result(*P, 0), CurContext);
3267 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003268
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003269 // Add nullary methods
3270 if (AllowNullaryMethods) {
3271 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003272 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003273 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3274 MEnd = Container->meth_end();
3275 M != MEnd; ++M) {
3276 if (M->getSelector().isUnarySelector())
3277 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3278 if (AddedProperties.insert(Name)) {
3279 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003280 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003281 Builder.AddTypedTextChunk(
3282 Results.getAllocator().CopyString(Name->getName()));
3283
3284 CXAvailabilityKind Availability = CXAvailability_Available;
3285 switch (M->getAvailability()) {
3286 case AR_Available:
3287 case AR_NotYetIntroduced:
3288 Availability = CXAvailability_Available;
3289 break;
3290
3291 case AR_Deprecated:
3292 Availability = CXAvailability_Deprecated;
3293 break;
3294
3295 case AR_Unavailable:
3296 Availability = CXAvailability_NotAvailable;
3297 break;
3298 }
3299
3300 Results.MaybeAddResult(Result(Builder.TakeString(),
3301 CCP_MemberDeclaration + CCD_MethodAsProperty,
3302 M->isInstanceMethod()
3303 ? CXCursor_ObjCInstanceMethodDecl
3304 : CXCursor_ObjCClassMethodDecl,
3305 Availability),
3306 CurContext);
3307 }
3308 }
3309 }
3310
3311
Douglas Gregor95ac6552009-11-18 01:29:26 +00003312 // Add properties in referenced protocols.
3313 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3314 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3315 PEnd = Protocol->protocol_end();
3316 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003317 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3318 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003319 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003320 if (AllowCategories) {
3321 // Look through categories.
3322 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3323 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003324 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3325 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003326 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003327
3328 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003329 for (ObjCInterfaceDecl::all_protocol_iterator
3330 I = IFace->all_referenced_protocol_begin(),
3331 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003332 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3333 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003334
3335 // Look in the superclass.
3336 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003337 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3338 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003339 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003340 } else if (const ObjCCategoryDecl *Category
3341 = dyn_cast<ObjCCategoryDecl>(Container)) {
3342 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003343 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3344 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003345 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003346 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3347 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003348 }
3349}
3350
Richard Trieuf81e5a92011-09-09 02:00:50 +00003351void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003352 SourceLocation OpLoc,
3353 bool IsArrow) {
3354 if (!BaseE || !CodeCompleter)
3355 return;
3356
John McCall0a2c5e22010-08-25 06:19:51 +00003357 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003358
Douglas Gregor81b747b2009-09-17 21:32:03 +00003359 Expr *Base = static_cast<Expr *>(BaseE);
3360 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003361
3362 if (IsArrow) {
3363 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3364 BaseType = Ptr->getPointeeType();
3365 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003366 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003367 else
3368 return;
3369 }
3370
Douglas Gregor3da626b2011-07-07 16:03:39 +00003371 enum CodeCompletionContext::Kind contextKind;
3372
3373 if (IsArrow) {
3374 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3375 }
3376 else {
3377 if (BaseType->isObjCObjectPointerType() ||
3378 BaseType->isObjCObjectOrInterfaceType()) {
3379 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3380 }
3381 else {
3382 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3383 }
3384 }
3385
Douglas Gregor218937c2011-02-01 19:23:04 +00003386 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003387 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003388 BaseType),
3389 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003390 Results.EnterNewScope();
3391 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003392 // Indicate that we are performing a member access, and the cv-qualifiers
3393 // for the base object type.
3394 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3395
Douglas Gregor95ac6552009-11-18 01:29:26 +00003396 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003397 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003398 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003399 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3400 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003401
Douglas Gregor95ac6552009-11-18 01:29:26 +00003402 if (getLangOptions().CPlusPlus) {
3403 if (!Results.empty()) {
3404 // The "template" keyword can follow "->" or "." in the grammar.
3405 // However, we only want to suggest the template keyword if something
3406 // is dependent.
3407 bool IsDependent = BaseType->isDependentType();
3408 if (!IsDependent) {
3409 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3410 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3411 IsDependent = Ctx->isDependentContext();
3412 break;
3413 }
3414 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003415
Douglas Gregor95ac6552009-11-18 01:29:26 +00003416 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003417 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003418 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003419 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003420 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3421 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003422 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003423
3424 // Add property results based on our interface.
3425 const ObjCObjectPointerType *ObjCPtr
3426 = BaseType->getAsObjCInterfacePointerType();
3427 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003428 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3429 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003430 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003431
3432 // Add properties from the protocols in a qualified interface.
3433 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3434 E = ObjCPtr->qual_end();
3435 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003436 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3437 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003438 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003439 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003440 // Objective-C instance variable access.
3441 ObjCInterfaceDecl *Class = 0;
3442 if (const ObjCObjectPointerType *ObjCPtr
3443 = BaseType->getAs<ObjCObjectPointerType>())
3444 Class = ObjCPtr->getInterfaceDecl();
3445 else
John McCallc12c5bb2010-05-15 11:32:37 +00003446 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003447
3448 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003449 if (Class) {
3450 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3451 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003452 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3453 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003454 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003455 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003456
3457 // FIXME: How do we cope with isa?
3458
3459 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003460
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003461 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003462 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003463 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003464 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003465}
3466
Douglas Gregor374929f2009-09-18 15:37:17 +00003467void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3468 if (!CodeCompleter)
3469 return;
3470
John McCall0a2c5e22010-08-25 06:19:51 +00003471 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003472 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003473 enum CodeCompletionContext::Kind ContextKind
3474 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003475 switch ((DeclSpec::TST)TagSpec) {
3476 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003477 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003478 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003479 break;
3480
3481 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003482 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003483 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003484 break;
3485
3486 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003487 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003488 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003489 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003490 break;
3491
3492 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003493 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003494 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003495
Douglas Gregor218937c2011-02-01 19:23:04 +00003496 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003497 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003498
3499 // First pass: look for tags.
3500 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003501 LookupVisibleDecls(S, LookupTagName, Consumer,
3502 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003503
Douglas Gregor8071e422010-08-15 06:18:01 +00003504 if (CodeCompleter->includeGlobals()) {
3505 // Second pass: look for nested name specifiers.
3506 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3507 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3508 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003509
Douglas Gregor52779fb2010-09-23 23:01:17 +00003510 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003511 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003512}
3513
Douglas Gregor1a480c42010-08-27 17:35:51 +00003514void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003515 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3516 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003517 Results.EnterNewScope();
3518 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3519 Results.AddResult("const");
3520 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3521 Results.AddResult("volatile");
3522 if (getLangOptions().C99 &&
3523 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3524 Results.AddResult("restrict");
3525 Results.ExitScope();
3526 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003527 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003528 Results.data(), Results.size());
3529}
3530
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003531void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003532 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003533 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003534
John McCall781472f2010-08-25 08:40:02 +00003535 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003536 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3537 if (!type->isEnumeralType()) {
3538 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003539 Data.IntegralConstantExpression = true;
3540 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003541 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003542 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003543
3544 // Code-complete the cases of a switch statement over an enumeration type
3545 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003546 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003547
3548 // Determine which enumerators we have already seen in the switch statement.
3549 // FIXME: Ideally, we would also be able to look *past* the code-completion
3550 // token, in case we are code-completing in the middle of the switch and not
3551 // at the end. However, we aren't able to do so at the moment.
3552 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003553 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003554 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3555 SC = SC->getNextSwitchCase()) {
3556 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3557 if (!Case)
3558 continue;
3559
3560 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3561 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3562 if (EnumConstantDecl *Enumerator
3563 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3564 // We look into the AST of the case statement to determine which
3565 // enumerator was named. Alternatively, we could compute the value of
3566 // the integral constant expression, then compare it against the
3567 // values of each enumerator. However, value-based approach would not
3568 // work as well with C++ templates where enumerators declared within a
3569 // template are type- and value-dependent.
3570 EnumeratorsSeen.insert(Enumerator);
3571
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003572 // If this is a qualified-id, keep track of the nested-name-specifier
3573 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003574 //
3575 // switch (TagD.getKind()) {
3576 // case TagDecl::TK_enum:
3577 // break;
3578 // case XXX
3579 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003580 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003581 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3582 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003583 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003584 }
3585 }
3586
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003587 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3588 // If there are no prior enumerators in C++, check whether we have to
3589 // qualify the names of the enumerators that we suggest, because they
3590 // may not be visible in this scope.
3591 Qualifier = getRequiredQualification(Context, CurContext,
3592 Enum->getDeclContext());
3593
3594 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3595 }
3596
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003597 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003598 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3599 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003600 Results.EnterNewScope();
3601 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3602 EEnd = Enum->enumerator_end();
3603 E != EEnd; ++E) {
3604 if (EnumeratorsSeen.count(*E))
3605 continue;
3606
Douglas Gregor5c722c702011-02-18 23:30:37 +00003607 CodeCompletionResult R(*E, Qualifier);
3608 R.Priority = CCP_EnumInCase;
3609 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003610 }
3611 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003612
Douglas Gregor3da626b2011-07-07 16:03:39 +00003613 //We need to make sure we're setting the right context,
3614 //so only say we include macros if the code completer says we do
3615 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3616 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003617 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003618 kind = CodeCompletionContext::CCC_OtherWithMacros;
3619 }
3620
3621
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003622 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003623 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003624 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003625}
3626
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003627namespace {
3628 struct IsBetterOverloadCandidate {
3629 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003630 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003631
3632 public:
John McCall5769d612010-02-08 23:07:23 +00003633 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3634 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003635
3636 bool
3637 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003638 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003639 }
3640 };
3641}
3642
Douglas Gregord28dcd72010-05-30 06:10:08 +00003643static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3644 if (NumArgs && !Args)
3645 return true;
3646
3647 for (unsigned I = 0; I != NumArgs; ++I)
3648 if (!Args[I])
3649 return true;
3650
3651 return false;
3652}
3653
Richard Trieuf81e5a92011-09-09 02:00:50 +00003654void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3655 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003656 if (!CodeCompleter)
3657 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003658
3659 // When we're code-completing for a call, we fall back to ordinary
3660 // name code-completion whenever we can't produce specific
3661 // results. We may want to revisit this strategy in the future,
3662 // e.g., by merging the two kinds of results.
3663
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003664 Expr *Fn = (Expr *)FnIn;
3665 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003666
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003667 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003668 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003669 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003670 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003671 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003672 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003673
John McCall3b4294e2009-12-16 12:17:52 +00003674 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003675 SourceLocation Loc = Fn->getExprLoc();
3676 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003677
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003678 // FIXME: What if we're calling something that isn't a function declaration?
3679 // FIXME: What if we're calling a pseudo-destructor?
3680 // FIXME: What if we're calling a member function?
3681
Douglas Gregorc0265402010-01-21 15:46:19 +00003682 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003683 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003684
John McCall3b4294e2009-12-16 12:17:52 +00003685 Expr *NakedFn = Fn->IgnoreParenCasts();
3686 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3687 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3688 /*PartialOverloading=*/ true);
3689 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3690 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003691 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003692 if (!getLangOptions().CPlusPlus ||
3693 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003694 Results.push_back(ResultCandidate(FDecl));
3695 else
John McCall86820f52010-01-26 01:37:31 +00003696 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003697 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3698 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003699 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003700 }
John McCall3b4294e2009-12-16 12:17:52 +00003701 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003702
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003703 QualType ParamType;
3704
Douglas Gregorc0265402010-01-21 15:46:19 +00003705 if (!CandidateSet.empty()) {
3706 // Sort the overload candidate set by placing the best overloads first.
3707 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003708 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003709
Douglas Gregorc0265402010-01-21 15:46:19 +00003710 // Add the remaining viable overload candidates as code-completion reslults.
3711 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3712 CandEnd = CandidateSet.end();
3713 Cand != CandEnd; ++Cand) {
3714 if (Cand->Viable)
3715 Results.push_back(ResultCandidate(Cand->Function));
3716 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003717
3718 // From the viable candidates, try to determine the type of this parameter.
3719 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3720 if (const FunctionType *FType = Results[I].getFunctionType())
3721 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3722 if (NumArgs < Proto->getNumArgs()) {
3723 if (ParamType.isNull())
3724 ParamType = Proto->getArgType(NumArgs);
3725 else if (!Context.hasSameUnqualifiedType(
3726 ParamType.getNonReferenceType(),
3727 Proto->getArgType(NumArgs).getNonReferenceType())) {
3728 ParamType = QualType();
3729 break;
3730 }
3731 }
3732 }
3733 } else {
3734 // Try to determine the parameter type from the type of the expression
3735 // being called.
3736 QualType FunctionType = Fn->getType();
3737 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3738 FunctionType = Ptr->getPointeeType();
3739 else if (const BlockPointerType *BlockPtr
3740 = FunctionType->getAs<BlockPointerType>())
3741 FunctionType = BlockPtr->getPointeeType();
3742 else if (const MemberPointerType *MemPtr
3743 = FunctionType->getAs<MemberPointerType>())
3744 FunctionType = MemPtr->getPointeeType();
3745
3746 if (const FunctionProtoType *Proto
3747 = FunctionType->getAs<FunctionProtoType>()) {
3748 if (NumArgs < Proto->getNumArgs())
3749 ParamType = Proto->getArgType(NumArgs);
3750 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003751 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003752
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003753 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003754 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003755 else
3756 CodeCompleteExpression(S, ParamType);
3757
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003758 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003759 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3760 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003761}
3762
John McCalld226f652010-08-21 09:40:31 +00003763void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3764 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003765 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003766 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003767 return;
3768 }
3769
3770 CodeCompleteExpression(S, VD->getType());
3771}
3772
3773void Sema::CodeCompleteReturn(Scope *S) {
3774 QualType ResultType;
3775 if (isa<BlockDecl>(CurContext)) {
3776 if (BlockScopeInfo *BSI = getCurBlock())
3777 ResultType = BSI->ReturnType;
3778 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3779 ResultType = Function->getResultType();
3780 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3781 ResultType = Method->getResultType();
3782
3783 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003784 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003785 else
3786 CodeCompleteExpression(S, ResultType);
3787}
3788
Douglas Gregord2d8be62011-07-30 08:36:53 +00003789void Sema::CodeCompleteAfterIf(Scope *S) {
3790 typedef CodeCompletionResult Result;
3791 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3792 mapCodeCompletionContext(*this, PCC_Statement));
3793 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3794 Results.EnterNewScope();
3795
3796 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3797 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3798 CodeCompleter->includeGlobals());
3799
3800 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3801
3802 // "else" block
3803 CodeCompletionBuilder Builder(Results.getAllocator());
3804 Builder.AddTypedTextChunk("else");
3805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3806 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3807 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3808 Builder.AddPlaceholderChunk("statements");
3809 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3810 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3811 Results.AddResult(Builder.TakeString());
3812
3813 // "else if" block
3814 Builder.AddTypedTextChunk("else");
3815 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3816 Builder.AddTextChunk("if");
3817 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3818 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3819 if (getLangOptions().CPlusPlus)
3820 Builder.AddPlaceholderChunk("condition");
3821 else
3822 Builder.AddPlaceholderChunk("expression");
3823 Builder.AddChunk(CodeCompletionString::CK_RightParen);
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 Results.ExitScope();
3833
3834 if (S->getFnParent())
3835 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3836
3837 if (CodeCompleter->includeMacros())
3838 AddMacroResults(PP, Results);
3839
3840 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3841 Results.data(),Results.size());
3842}
3843
Richard Trieuf81e5a92011-09-09 02:00:50 +00003844void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003845 if (LHS)
3846 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3847 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003848 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003849}
3850
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003851void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003852 bool EnteringContext) {
3853 if (!SS.getScopeRep() || !CodeCompleter)
3854 return;
3855
Douglas Gregor86d9a522009-09-21 16:56:56 +00003856 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3857 if (!Ctx)
3858 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003859
3860 // Try to instantiate any non-dependent declaration contexts before
3861 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003862 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003863 return;
3864
Douglas Gregor218937c2011-02-01 19:23:04 +00003865 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3866 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003867 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003868
Douglas Gregor86d9a522009-09-21 16:56:56 +00003869 // The "template" keyword can follow "::" in the grammar, but only
3870 // put it into the grammar if the nested-name-specifier is dependent.
3871 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3872 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003873 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003874
3875 // Add calls to overridden virtual functions, if there are any.
3876 //
3877 // FIXME: This isn't wonderful, because we don't know whether we're actually
3878 // in a context that permits expressions. This is a general issue with
3879 // qualified-id completions.
3880 if (!EnteringContext)
3881 MaybeAddOverrideCalls(*this, Ctx, Results);
3882 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003883
Douglas Gregorf6961522010-08-27 21:18:54 +00003884 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3885 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3886
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003887 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003888 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003889 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003890}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003891
3892void Sema::CodeCompleteUsing(Scope *S) {
3893 if (!CodeCompleter)
3894 return;
3895
Douglas Gregor218937c2011-02-01 19:23:04 +00003896 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003897 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3898 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003899 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003900
3901 // If we aren't in class scope, we could see the "namespace" keyword.
3902 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003903 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003904
3905 // After "using", we can see anything that would start a
3906 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003907 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003908 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3909 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003910 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003911
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003912 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003913 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003914 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003915}
3916
3917void Sema::CodeCompleteUsingDirective(Scope *S) {
3918 if (!CodeCompleter)
3919 return;
3920
Douglas Gregor86d9a522009-09-21 16:56:56 +00003921 // After "using namespace", we expect to see a namespace name or namespace
3922 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003923 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3924 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003925 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003926 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003927 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003928 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3929 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003930 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003931 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003932 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003933 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003934}
3935
3936void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3937 if (!CodeCompleter)
3938 return;
3939
Douglas Gregor86d9a522009-09-21 16:56:56 +00003940 DeclContext *Ctx = (DeclContext *)S->getEntity();
3941 if (!S->getParent())
3942 Ctx = Context.getTranslationUnitDecl();
3943
Douglas Gregor52779fb2010-09-23 23:01:17 +00003944 bool SuppressedGlobalResults
3945 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3946
Douglas Gregor218937c2011-02-01 19:23:04 +00003947 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003948 SuppressedGlobalResults
3949 ? CodeCompletionContext::CCC_Namespace
3950 : CodeCompletionContext::CCC_Other,
3951 &ResultBuilder::IsNamespace);
3952
3953 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003954 // We only want to see those namespaces that have already been defined
3955 // within this scope, because its likely that the user is creating an
3956 // extended namespace declaration. Keep track of the most recent
3957 // definition of each namespace.
3958 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3959 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3960 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3961 NS != NSEnd; ++NS)
3962 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3963
3964 // Add the most recent definition (or extended definition) of each
3965 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003966 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003967 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3968 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3969 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003970 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003971 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003972 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003973 }
3974
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003975 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003976 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003977 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003978}
3979
3980void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3981 if (!CodeCompleter)
3982 return;
3983
Douglas Gregor86d9a522009-09-21 16:56:56 +00003984 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003985 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3986 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003987 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003988 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003989 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3990 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003991 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003992 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003993 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003994}
3995
Douglas Gregored8d3222009-09-18 20:05:18 +00003996void Sema::CodeCompleteOperatorName(Scope *S) {
3997 if (!CodeCompleter)
3998 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003999
John McCall0a2c5e22010-08-25 06:19:51 +00004000 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004001 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4002 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004003 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004004 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004005
Douglas Gregor86d9a522009-09-21 16:56:56 +00004006 // Add the names of overloadable operators.
4007#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4008 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004009 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004010#include "clang/Basic/OperatorKinds.def"
4011
4012 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004013 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004014 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004015 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4016 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004017
4018 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004019 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004020 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004021
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004022 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004023 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004024 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004025}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004026
Douglas Gregor0133f522010-08-28 00:00:50 +00004027void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004028 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004029 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004030 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004031 CXXConstructorDecl *Constructor
4032 = static_cast<CXXConstructorDecl *>(ConstructorD);
4033 if (!Constructor)
4034 return;
4035
Douglas Gregor218937c2011-02-01 19:23:04 +00004036 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004037 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004038 Results.EnterNewScope();
4039
4040 // Fill in any already-initialized fields or base classes.
4041 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4042 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4043 for (unsigned I = 0; I != NumInitializers; ++I) {
4044 if (Initializers[I]->isBaseInitializer())
4045 InitializedBases.insert(
4046 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4047 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004048 InitializedFields.insert(cast<FieldDecl>(
4049 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004050 }
4051
4052 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004053 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004054 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004055 CXXRecordDecl *ClassDecl = Constructor->getParent();
4056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4057 BaseEnd = ClassDecl->bases_end();
4058 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004059 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4060 SawLastInitializer
4061 = NumInitializers > 0 &&
4062 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4063 Context.hasSameUnqualifiedType(Base->getType(),
4064 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004065 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004066 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004067
Douglas Gregor218937c2011-02-01 19:23:04 +00004068 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004069 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004070 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4072 Builder.AddPlaceholderChunk("args");
4073 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4074 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004075 SawLastInitializer? CCP_NextInitializer
4076 : CCP_MemberDeclaration));
4077 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004078 }
4079
4080 // Add completions for virtual base classes.
4081 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4082 BaseEnd = ClassDecl->vbases_end();
4083 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004084 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4085 SawLastInitializer
4086 = NumInitializers > 0 &&
4087 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4088 Context.hasSameUnqualifiedType(Base->getType(),
4089 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004090 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004091 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004092
Douglas Gregor218937c2011-02-01 19:23:04 +00004093 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004094 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004095 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004096 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4097 Builder.AddPlaceholderChunk("args");
4098 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4099 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004100 SawLastInitializer? CCP_NextInitializer
4101 : CCP_MemberDeclaration));
4102 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004103 }
4104
4105 // Add completions for members.
4106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4107 FieldEnd = ClassDecl->field_end();
4108 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004109 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4110 SawLastInitializer
4111 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004112 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4113 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004114 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004115 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004116
4117 if (!Field->getDeclName())
4118 continue;
4119
Douglas Gregordae68752011-02-01 22:57:45 +00004120 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004121 Field->getIdentifier()->getName()));
4122 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4123 Builder.AddPlaceholderChunk("args");
4124 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4125 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004126 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004127 : CCP_MemberDeclaration,
4128 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004129 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004130 }
4131 Results.ExitScope();
4132
Douglas Gregor52779fb2010-09-23 23:01:17 +00004133 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004134 Results.data(), Results.size());
4135}
4136
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004137// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4138// true or false.
4139#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004140static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004141 ResultBuilder &Results,
4142 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004143 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004144 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004145 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004146
Douglas Gregor218937c2011-02-01 19:23:04 +00004147 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004148 if (LangOpts.ObjC2) {
4149 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004150 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4151 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4152 Builder.AddPlaceholderChunk("property");
4153 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004154
4155 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004156 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4158 Builder.AddPlaceholderChunk("property");
4159 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004160 }
4161}
4162
Douglas Gregorbca403c2010-01-13 23:51:12 +00004163static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004164 ResultBuilder &Results,
4165 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004166 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004167
4168 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004169 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004170
4171 if (LangOpts.ObjC2) {
4172 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004173 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004174
4175 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004176 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004177
4178 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004179 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004180 }
4181}
4182
Douglas Gregorbca403c2010-01-13 23:51:12 +00004183static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004184 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004185 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004186
4187 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004188 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4189 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4190 Builder.AddPlaceholderChunk("name");
4191 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004192
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004193 if (Results.includeCodePatterns()) {
4194 // @interface name
4195 // FIXME: Could introduce the whole pattern, including superclasses and
4196 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004197 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4198 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4199 Builder.AddPlaceholderChunk("class");
4200 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004201
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004202 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004203 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4204 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4205 Builder.AddPlaceholderChunk("protocol");
4206 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004207
4208 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004209 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4210 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4211 Builder.AddPlaceholderChunk("class");
4212 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004213 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004214
4215 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004216 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4217 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4218 Builder.AddPlaceholderChunk("alias");
4219 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4220 Builder.AddPlaceholderChunk("class");
4221 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004222}
4223
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004224void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004225 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004226 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4227 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004228 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004229 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004230 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004231 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004232 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004233 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004234 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004235 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004236 HandleCodeCompleteResults(this, CodeCompleter,
4237 CodeCompletionContext::CCC_Other,
4238 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004239}
4240
Douglas Gregorbca403c2010-01-13 23:51:12 +00004241static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004242 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004243 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004244
4245 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004246 const char *EncodeType = "char[]";
4247 if (Results.getSema().getLangOptions().CPlusPlus ||
4248 Results.getSema().getLangOptions().ConstStrings)
4249 EncodeType = " const char[]";
4250 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004251 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4253 Builder.AddPlaceholderChunk("type-name");
4254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4255 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004256
4257 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004258 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004259 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4260 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4261 Builder.AddPlaceholderChunk("protocol-name");
4262 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4263 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004264
4265 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004266 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004267 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4268 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4269 Builder.AddPlaceholderChunk("selector");
4270 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4271 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004272}
4273
Douglas Gregorbca403c2010-01-13 23:51:12 +00004274static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004275 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004276 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004277
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004278 if (Results.includeCodePatterns()) {
4279 // @try { statements } @catch ( declaration ) { statements } @finally
4280 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004281 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4282 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4283 Builder.AddPlaceholderChunk("statements");
4284 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4285 Builder.AddTextChunk("@catch");
4286 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4287 Builder.AddPlaceholderChunk("parameter");
4288 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4289 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4290 Builder.AddPlaceholderChunk("statements");
4291 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4292 Builder.AddTextChunk("@finally");
4293 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4294 Builder.AddPlaceholderChunk("statements");
4295 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4296 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004297 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004298
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004299 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004300 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4301 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4302 Builder.AddPlaceholderChunk("expression");
4303 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004304
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004305 if (Results.includeCodePatterns()) {
4306 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004307 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4308 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4309 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4310 Builder.AddPlaceholderChunk("expression");
4311 Builder.AddChunk(CodeCompletionString::CK_RightParen);
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
Douglas Gregorbca403c2010-01-13 23:51:12 +00004319static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004320 ResultBuilder &Results,
4321 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004322 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004323 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4324 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4325 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004326 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004327 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004328}
4329
4330void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004331 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4332 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004333 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004334 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004335 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004336 HandleCodeCompleteResults(this, CodeCompleter,
4337 CodeCompletionContext::CCC_Other,
4338 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004339}
4340
4341void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004342 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4343 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004344 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004345 AddObjCStatementResults(Results, false);
4346 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004347 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004348 HandleCodeCompleteResults(this, CodeCompleter,
4349 CodeCompletionContext::CCC_Other,
4350 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004351}
4352
4353void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004354 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4355 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004356 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004357 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004358 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004359 HandleCodeCompleteResults(this, CodeCompleter,
4360 CodeCompletionContext::CCC_Other,
4361 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004362}
4363
Douglas Gregor988358f2009-11-19 00:14:45 +00004364/// \brief Determine whether the addition of the given flag to an Objective-C
4365/// property's attributes will cause a conflict.
4366static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4367 // Check if we've already added this flag.
4368 if (Attributes & NewFlag)
4369 return true;
4370
4371 Attributes |= NewFlag;
4372
4373 // Check for collisions with "readonly".
4374 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4375 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4376 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004377 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004378 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004379 ObjCDeclSpec::DQ_PR_retain |
4380 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004381 return true;
4382
John McCallf85e1932011-06-15 23:02:42 +00004383 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004384 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004385 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004386 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004387 ObjCDeclSpec::DQ_PR_retain|
4388 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004389 if (AssignCopyRetMask &&
4390 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004391 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004392 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004393 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4394 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004395 return true;
4396
4397 return false;
4398}
4399
Douglas Gregora93b1082009-11-18 23:08:07 +00004400void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004401 if (!CodeCompleter)
4402 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004403
Steve Naroffece8e712009-10-08 21:55:05 +00004404 unsigned Attributes = ODS.getPropertyAttributes();
4405
John McCall0a2c5e22010-08-25 06:19:51 +00004406 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004407 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4408 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004409 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004410 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004411 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004412 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004413 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004414 if (!ObjCPropertyFlagConflicts(Attributes,
4415 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4416 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004417 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004418 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004419 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004420 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004421 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4422 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004423 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004424 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004425 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004426 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004427 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4428 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004429 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004430 CodeCompletionBuilder Setter(Results.getAllocator());
4431 Setter.AddTypedTextChunk("setter");
4432 Setter.AddTextChunk(" = ");
4433 Setter.AddPlaceholderChunk("method");
4434 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004435 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004436 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004437 CodeCompletionBuilder Getter(Results.getAllocator());
4438 Getter.AddTypedTextChunk("getter");
4439 Getter.AddTextChunk(" = ");
4440 Getter.AddPlaceholderChunk("method");
4441 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004442 }
Steve Naroffece8e712009-10-08 21:55:05 +00004443 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004444 HandleCodeCompleteResults(this, CodeCompleter,
4445 CodeCompletionContext::CCC_Other,
4446 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004447}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004448
Douglas Gregor4ad96852009-11-19 07:41:15 +00004449/// \brief Descripts the kind of Objective-C method that we want to find
4450/// via code completion.
4451enum ObjCMethodKind {
4452 MK_Any, //< Any kind of method, provided it means other specified criteria.
4453 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4454 MK_OneArgSelector //< One-argument selector.
4455};
4456
Douglas Gregor458433d2010-08-26 15:07:07 +00004457static bool isAcceptableObjCSelector(Selector Sel,
4458 ObjCMethodKind WantKind,
4459 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004460 unsigned NumSelIdents,
4461 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004462 if (NumSelIdents > Sel.getNumArgs())
4463 return false;
4464
4465 switch (WantKind) {
4466 case MK_Any: break;
4467 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4468 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4469 }
4470
Douglas Gregorcf544262010-11-17 21:36:08 +00004471 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4472 return false;
4473
Douglas Gregor458433d2010-08-26 15:07:07 +00004474 for (unsigned I = 0; I != NumSelIdents; ++I)
4475 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4476 return false;
4477
4478 return true;
4479}
4480
Douglas Gregor4ad96852009-11-19 07:41:15 +00004481static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4482 ObjCMethodKind WantKind,
4483 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004484 unsigned NumSelIdents,
4485 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004486 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004487 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488}
Douglas Gregord36adf52010-09-16 16:06:31 +00004489
4490namespace {
4491 /// \brief A set of selectors, which is used to avoid introducing multiple
4492 /// completions with the same selector into the result set.
4493 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4494}
4495
Douglas Gregor36ecb042009-11-17 23:22:23 +00004496/// \brief Add all of the Objective-C methods in the given Objective-C
4497/// container to the set of results.
4498///
4499/// The container will be a class, protocol, category, or implementation of
4500/// any of the above. This mether will recurse to include methods from
4501/// the superclasses of classes along with their categories, protocols, and
4502/// implementations.
4503///
4504/// \param Container the container in which we'll look to find methods.
4505///
4506/// \param WantInstance whether to add instance methods (only); if false, this
4507/// routine will add factory methods (only).
4508///
4509/// \param CurContext the context in which we're performing the lookup that
4510/// finds methods.
4511///
Douglas Gregorcf544262010-11-17 21:36:08 +00004512/// \param AllowSameLength Whether we allow a method to be added to the list
4513/// when it has the same number of parameters as we have selector identifiers.
4514///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004515/// \param Results the structure into which we'll add results.
4516static void AddObjCMethods(ObjCContainerDecl *Container,
4517 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004518 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004519 IdentifierInfo **SelIdents,
4520 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004521 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004522 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004523 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004524 ResultBuilder &Results,
4525 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004526 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004527 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4528 MEnd = Container->meth_end();
4529 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004530 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4531 // Check whether the selector identifiers we've been given are a
4532 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004533 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4534 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004535 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004536
Douglas Gregord36adf52010-09-16 16:06:31 +00004537 if (!Selectors.insert((*M)->getSelector()))
4538 continue;
4539
Douglas Gregord3c68542009-11-19 01:08:35 +00004540 Result R = Result(*M, 0);
4541 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004542 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004543 if (!InOriginalClass)
4544 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004545 Results.MaybeAddResult(R, CurContext);
4546 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004547 }
4548
Douglas Gregore396c7b2010-09-16 15:34:59 +00004549 // Visit the protocols of protocols.
4550 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4551 const ObjCList<ObjCProtocolDecl> &Protocols
4552 = Protocol->getReferencedProtocols();
4553 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4554 E = Protocols.end();
4555 I != E; ++I)
4556 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004557 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004558 }
4559
Douglas Gregor36ecb042009-11-17 23:22:23 +00004560 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4561 if (!IFace)
4562 return;
4563
4564 // Add methods in protocols.
4565 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4566 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4567 E = Protocols.end();
4568 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004569 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004570 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004571
4572 // Add methods in categories.
4573 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4574 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004575 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004576 NumSelIdents, CurContext, Selectors, AllowSameLength,
4577 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004578
4579 // Add a categories protocol methods.
4580 const ObjCList<ObjCProtocolDecl> &Protocols
4581 = CatDecl->getReferencedProtocols();
4582 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4583 E = Protocols.end();
4584 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004585 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004586 NumSelIdents, CurContext, Selectors, AllowSameLength,
4587 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004588
4589 // Add methods in category implementations.
4590 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004591 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004592 NumSelIdents, CurContext, Selectors, AllowSameLength,
4593 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004594 }
4595
4596 // Add methods in superclass.
4597 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004598 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004599 SelIdents, NumSelIdents, CurContext, Selectors,
4600 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004601
4602 // Add methods in our implementation, if any.
4603 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004604 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004605 NumSelIdents, CurContext, Selectors, AllowSameLength,
4606 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004607}
4608
4609
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004610void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004611 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004612
4613 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004614 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004615 if (!Class) {
4616 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004617 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004618 Class = Category->getClassInterface();
4619
4620 if (!Class)
4621 return;
4622 }
4623
4624 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004625 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4626 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004627 Results.EnterNewScope();
4628
Douglas Gregord36adf52010-09-16 16:06:31 +00004629 VisitedSelectorSet Selectors;
4630 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004631 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004632 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004633 HandleCodeCompleteResults(this, CodeCompleter,
4634 CodeCompletionContext::CCC_Other,
4635 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004636}
4637
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004638void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004639 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004640
4641 // Try to find the interface where setters might live.
4642 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004643 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004644 if (!Class) {
4645 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004646 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004647 Class = Category->getClassInterface();
4648
4649 if (!Class)
4650 return;
4651 }
4652
4653 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004654 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4655 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004656 Results.EnterNewScope();
4657
Douglas Gregord36adf52010-09-16 16:06:31 +00004658 VisitedSelectorSet Selectors;
4659 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004660 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004661
4662 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004663 HandleCodeCompleteResults(this, CodeCompleter,
4664 CodeCompletionContext::CCC_Other,
4665 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004666}
4667
Douglas Gregorafc45782011-02-15 22:19:42 +00004668void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4669 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004670 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004671 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4672 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004673 Results.EnterNewScope();
4674
4675 // Add context-sensitive, Objective-C parameter-passing keywords.
4676 bool AddedInOut = false;
4677 if ((DS.getObjCDeclQualifier() &
4678 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4679 Results.AddResult("in");
4680 Results.AddResult("inout");
4681 AddedInOut = true;
4682 }
4683 if ((DS.getObjCDeclQualifier() &
4684 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4685 Results.AddResult("out");
4686 if (!AddedInOut)
4687 Results.AddResult("inout");
4688 }
4689 if ((DS.getObjCDeclQualifier() &
4690 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4691 ObjCDeclSpec::DQ_Oneway)) == 0) {
4692 Results.AddResult("bycopy");
4693 Results.AddResult("byref");
4694 Results.AddResult("oneway");
4695 }
4696
Douglas Gregorafc45782011-02-15 22:19:42 +00004697 // If we're completing the return type of an Objective-C method and the
4698 // identifier IBAction refers to a macro, provide a completion item for
4699 // an action, e.g.,
4700 // IBAction)<#selector#>:(id)sender
4701 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4702 Context.Idents.get("IBAction").hasMacroDefinition()) {
4703 typedef CodeCompletionString::Chunk Chunk;
4704 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4705 CXAvailability_Available);
4706 Builder.AddTypedTextChunk("IBAction");
4707 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4708 Builder.AddPlaceholderChunk("selector");
4709 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4710 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4711 Builder.AddTextChunk("id");
4712 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4713 Builder.AddTextChunk("sender");
4714 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4715 }
4716
Douglas Gregord32b0222010-08-24 01:06:58 +00004717 // Add various builtin type names and specifiers.
4718 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4719 Results.ExitScope();
4720
4721 // Add the various type names
4722 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4723 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4724 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4725 CodeCompleter->includeGlobals());
4726
4727 if (CodeCompleter->includeMacros())
4728 AddMacroResults(PP, Results);
4729
4730 HandleCodeCompleteResults(this, CodeCompleter,
4731 CodeCompletionContext::CCC_Type,
4732 Results.data(), Results.size());
4733}
4734
Douglas Gregor22f56992010-04-06 19:22:33 +00004735/// \brief When we have an expression with type "id", we may assume
4736/// that it has some more-specific class type based on knowledge of
4737/// common uses of Objective-C. This routine returns that class type,
4738/// or NULL if no better result could be determined.
4739static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004740 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004741 if (!Msg)
4742 return 0;
4743
4744 Selector Sel = Msg->getSelector();
4745 if (Sel.isNull())
4746 return 0;
4747
4748 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4749 if (!Id)
4750 return 0;
4751
4752 ObjCMethodDecl *Method = Msg->getMethodDecl();
4753 if (!Method)
4754 return 0;
4755
4756 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004757 ObjCInterfaceDecl *IFace = 0;
4758 switch (Msg->getReceiverKind()) {
4759 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004760 if (const ObjCObjectType *ObjType
4761 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4762 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004763 break;
4764
4765 case ObjCMessageExpr::Instance: {
4766 QualType T = Msg->getInstanceReceiver()->getType();
4767 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4768 IFace = Ptr->getInterfaceDecl();
4769 break;
4770 }
4771
4772 case ObjCMessageExpr::SuperInstance:
4773 case ObjCMessageExpr::SuperClass:
4774 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004775 }
4776
4777 if (!IFace)
4778 return 0;
4779
4780 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4781 if (Method->isInstanceMethod())
4782 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4783 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004784 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004785 .Case("autorelease", IFace)
4786 .Case("copy", IFace)
4787 .Case("copyWithZone", IFace)
4788 .Case("mutableCopy", IFace)
4789 .Case("mutableCopyWithZone", IFace)
4790 .Case("awakeFromCoder", IFace)
4791 .Case("replacementObjectFromCoder", IFace)
4792 .Case("class", IFace)
4793 .Case("classForCoder", IFace)
4794 .Case("superclass", Super)
4795 .Default(0);
4796
4797 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4798 .Case("new", IFace)
4799 .Case("alloc", IFace)
4800 .Case("allocWithZone", IFace)
4801 .Case("class", IFace)
4802 .Case("superclass", Super)
4803 .Default(0);
4804}
4805
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004806// Add a special completion for a message send to "super", which fills in the
4807// most likely case of forwarding all of our arguments to the superclass
4808// function.
4809///
4810/// \param S The semantic analysis object.
4811///
4812/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4813/// the "super" keyword. Otherwise, we just need to provide the arguments.
4814///
4815/// \param SelIdents The identifiers in the selector that have already been
4816/// provided as arguments for a send to "super".
4817///
4818/// \param NumSelIdents The number of identifiers in \p SelIdents.
4819///
4820/// \param Results The set of results to augment.
4821///
4822/// \returns the Objective-C method declaration that would be invoked by
4823/// this "super" completion. If NULL, no completion was added.
4824static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4825 IdentifierInfo **SelIdents,
4826 unsigned NumSelIdents,
4827 ResultBuilder &Results) {
4828 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4829 if (!CurMethod)
4830 return 0;
4831
4832 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4833 if (!Class)
4834 return 0;
4835
4836 // Try to find a superclass method with the same selector.
4837 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004838 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4839 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004840 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4841 CurMethod->isInstanceMethod());
4842
Douglas Gregor78bcd912011-02-16 00:51:18 +00004843 // Check in categories or class extensions.
4844 if (!SuperMethod) {
4845 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4846 Category = Category->getNextClassCategory())
4847 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4848 CurMethod->isInstanceMethod())))
4849 break;
4850 }
4851 }
4852
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004853 if (!SuperMethod)
4854 return 0;
4855
4856 // Check whether the superclass method has the same signature.
4857 if (CurMethod->param_size() != SuperMethod->param_size() ||
4858 CurMethod->isVariadic() != SuperMethod->isVariadic())
4859 return 0;
4860
4861 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4862 CurPEnd = CurMethod->param_end(),
4863 SuperP = SuperMethod->param_begin();
4864 CurP != CurPEnd; ++CurP, ++SuperP) {
4865 // Make sure the parameter types are compatible.
4866 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4867 (*SuperP)->getType()))
4868 return 0;
4869
4870 // Make sure we have a parameter name to forward!
4871 if (!(*CurP)->getIdentifier())
4872 return 0;
4873 }
4874
4875 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004876 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004877
4878 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004879 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4880 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004881
4882 // If we need the "super" keyword, add it (plus some spacing).
4883 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004884 Builder.AddTypedTextChunk("super");
4885 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004886 }
4887
4888 Selector Sel = CurMethod->getSelector();
4889 if (Sel.isUnarySelector()) {
4890 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004891 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004892 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004893 else
Douglas Gregordae68752011-02-01 22:57:45 +00004894 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004895 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004896 } else {
4897 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4898 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4899 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004900 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004901
4902 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004903 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004904 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004905 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004906 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004907 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004908 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004909 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004910 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004911 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004912 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004913 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004914 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004915 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004916 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004917 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004918 }
4919 }
4920 }
4921
Douglas Gregor218937c2011-02-01 19:23:04 +00004922 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004923 SuperMethod->isInstanceMethod()
4924 ? CXCursor_ObjCInstanceMethodDecl
4925 : CXCursor_ObjCClassMethodDecl));
4926 return SuperMethod;
4927}
4928
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004929void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004930 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004931 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4932 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004933 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004934
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004935 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4936 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004937 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4938 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004939
4940 // If we are in an Objective-C method inside a class that has a superclass,
4941 // add "super" as an option.
4942 if (ObjCMethodDecl *Method = getCurMethodDecl())
4943 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004944 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004945 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004946
4947 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4948 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004949
4950 Results.ExitScope();
4951
4952 if (CodeCompleter->includeMacros())
4953 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004954 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004955 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004956
4957}
4958
Douglas Gregor2725ca82010-04-21 19:57:20 +00004959void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4960 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004961 unsigned NumSelIdents,
4962 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004963 ObjCInterfaceDecl *CDecl = 0;
4964 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4965 // Figure out which interface we're in.
4966 CDecl = CurMethod->getClassInterface();
4967 if (!CDecl)
4968 return;
4969
4970 // Find the superclass of this class.
4971 CDecl = CDecl->getSuperClass();
4972 if (!CDecl)
4973 return;
4974
4975 if (CurMethod->isInstanceMethod()) {
4976 // We are inside an instance method, which means that the message
4977 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004978 // current object.
4979 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004980 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004981 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004982 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004983 }
4984
4985 // Fall through to send to the superclass in CDecl.
4986 } else {
4987 // "super" may be the name of a type or variable. Figure out which
4988 // it is.
4989 IdentifierInfo *Super = &Context.Idents.get("super");
4990 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4991 LookupOrdinaryName);
4992 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4993 // "super" names an interface. Use it.
4994 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004995 if (const ObjCObjectType *Iface
4996 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4997 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004998 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4999 // "super" names an unresolved type; we can't be more specific.
5000 } else {
5001 // Assume that "super" names some kind of value and parse that way.
5002 CXXScopeSpec SS;
5003 UnqualifiedId id;
5004 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005005 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005006 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005007 SelIdents, NumSelIdents,
5008 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005009 }
5010
5011 // Fall through
5012 }
5013
John McCallb3d87482010-08-24 05:47:05 +00005014 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005015 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005016 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005017 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005018 NumSelIdents, AtArgumentExpression,
5019 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005020}
5021
Douglas Gregorb9d77572010-09-21 00:03:25 +00005022/// \brief Given a set of code-completion results for the argument of a message
5023/// send, determine the preferred type (if any) for that argument expression.
5024static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5025 unsigned NumSelIdents) {
5026 typedef CodeCompletionResult Result;
5027 ASTContext &Context = Results.getSema().Context;
5028
5029 QualType PreferredType;
5030 unsigned BestPriority = CCP_Unlikely * 2;
5031 Result *ResultsData = Results.data();
5032 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5033 Result &R = ResultsData[I];
5034 if (R.Kind == Result::RK_Declaration &&
5035 isa<ObjCMethodDecl>(R.Declaration)) {
5036 if (R.Priority <= BestPriority) {
5037 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5038 if (NumSelIdents <= Method->param_size()) {
5039 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5040 ->getType();
5041 if (R.Priority < BestPriority || PreferredType.isNull()) {
5042 BestPriority = R.Priority;
5043 PreferredType = MyPreferredType;
5044 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5045 MyPreferredType)) {
5046 PreferredType = QualType();
5047 }
5048 }
5049 }
5050 }
5051 }
5052
5053 return PreferredType;
5054}
5055
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005056static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5057 ParsedType Receiver,
5058 IdentifierInfo **SelIdents,
5059 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005060 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005061 bool IsSuper,
5062 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005063 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005064 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005065
Douglas Gregor24a069f2009-11-17 17:59:40 +00005066 // If the given name refers to an interface type, retrieve the
5067 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005068 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005069 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005070 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005071 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5072 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005073 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005074
Douglas Gregor36ecb042009-11-17 23:22:23 +00005075 // Add all of the factory methods in this Objective-C class, its protocols,
5076 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005077 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005078
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005079 // If this is a send-to-super, try to add the special "super" send
5080 // completion.
5081 if (IsSuper) {
5082 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005083 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5084 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005085 Results.Ignore(SuperMethod);
5086 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005087
Douglas Gregor265f7492010-08-27 15:29:55 +00005088 // If we're inside an Objective-C method definition, prefer its selector to
5089 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005090 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005091 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005092
Douglas Gregord36adf52010-09-16 16:06:31 +00005093 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005094 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005095 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005096 SemaRef.CurContext, Selectors, AtArgumentExpression,
5097 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005098 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005099 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005100
Douglas Gregor719770d2010-04-06 17:30:22 +00005101 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005102 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005103 if (SemaRef.ExternalSource) {
5104 for (uint32_t I = 0,
5105 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005106 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005107 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5108 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005109 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005110
5111 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005112 }
5113 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005114
5115 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5116 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005117 M != MEnd; ++M) {
5118 for (ObjCMethodList *MethList = &M->second.second;
5119 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005120 MethList = MethList->Next) {
5121 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5122 NumSelIdents))
5123 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005124
Douglas Gregor13438f92010-04-06 16:40:00 +00005125 Result R(MethList->Method, 0);
5126 R.StartParameter = NumSelIdents;
5127 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005128 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005129 }
5130 }
5131 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005132
5133 Results.ExitScope();
5134}
Douglas Gregor13438f92010-04-06 16:40:00 +00005135
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005136void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5137 IdentifierInfo **SelIdents,
5138 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005139 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005140 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005141
5142 QualType T = this->GetTypeFromParser(Receiver);
5143
Douglas Gregor218937c2011-02-01 19:23:04 +00005144 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005145 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005146 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005147
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005148 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5149 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005150
5151 // If we're actually at the argument expression (rather than prior to the
5152 // selector), we're actually performing code completion for an expression.
5153 // Determine whether we have a single, best method. If so, we can
5154 // code-complete the expression using the corresponding parameter type as
5155 // our preferred type, improving completion results.
5156 if (AtArgumentExpression) {
5157 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005158 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005159 if (PreferredType.isNull())
5160 CodeCompleteOrdinaryName(S, PCC_Expression);
5161 else
5162 CodeCompleteExpression(S, PreferredType);
5163 return;
5164 }
5165
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005166 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005167 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005168 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005169}
5170
Richard Trieuf81e5a92011-09-09 02:00:50 +00005171void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005172 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005173 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005174 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005175 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005176 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005177
5178 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005179
Douglas Gregor36ecb042009-11-17 23:22:23 +00005180 // If necessary, apply function/array conversion to the receiver.
5181 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005182 if (RecExpr) {
5183 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5184 if (Conv.isInvalid()) // conversion failed. bail.
5185 return;
5186 RecExpr = Conv.take();
5187 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005188 QualType ReceiverType = RecExpr? RecExpr->getType()
5189 : Super? Context.getObjCObjectPointerType(
5190 Context.getObjCInterfaceType(Super))
5191 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005192
Douglas Gregorda892642010-11-08 21:12:30 +00005193 // If we're messaging an expression with type "id" or "Class", check
5194 // whether we know something special about the receiver that allows
5195 // us to assume a more-specific receiver type.
5196 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5197 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5198 if (ReceiverType->isObjCClassType())
5199 return CodeCompleteObjCClassMessage(S,
5200 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5201 SelIdents, NumSelIdents,
5202 AtArgumentExpression, Super);
5203
5204 ReceiverType = Context.getObjCObjectPointerType(
5205 Context.getObjCInterfaceType(IFace));
5206 }
5207
Douglas Gregor36ecb042009-11-17 23:22:23 +00005208 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005209 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005210 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005211 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005212
Douglas Gregor36ecb042009-11-17 23:22:23 +00005213 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005214
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005215 // If this is a send-to-super, try to add the special "super" send
5216 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005217 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005218 if (ObjCMethodDecl *SuperMethod
5219 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5220 Results))
5221 Results.Ignore(SuperMethod);
5222 }
5223
Douglas Gregor265f7492010-08-27 15:29:55 +00005224 // If we're inside an Objective-C method definition, prefer its selector to
5225 // others.
5226 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5227 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005228
Douglas Gregord36adf52010-09-16 16:06:31 +00005229 // Keep track of the selectors we've already added.
5230 VisitedSelectorSet Selectors;
5231
Douglas Gregorf74a4192009-11-18 00:06:18 +00005232 // Handle messages to Class. This really isn't a message to an instance
5233 // method, so we treat it the same way we would treat a message send to a
5234 // class method.
5235 if (ReceiverType->isObjCClassType() ||
5236 ReceiverType->isObjCQualifiedClassType()) {
5237 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5238 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005239 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005240 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005241 }
5242 }
5243 // Handle messages to a qualified ID ("id<foo>").
5244 else if (const ObjCObjectPointerType *QualID
5245 = ReceiverType->getAsObjCQualifiedIdType()) {
5246 // Search protocols for instance methods.
5247 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5248 E = QualID->qual_end();
5249 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005250 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005251 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005252 }
5253 // Handle messages to a pointer to interface type.
5254 else if (const ObjCObjectPointerType *IFacePtr
5255 = ReceiverType->getAsObjCInterfacePointerType()) {
5256 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005257 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005258 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5259 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005260
5261 // Search protocols for instance methods.
5262 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5263 E = IFacePtr->qual_end();
5264 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005265 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005266 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005267 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005268 // Handle messages to "id".
5269 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005270 // We're messaging "id", so provide all instance methods we know
5271 // about as code-completion results.
5272
5273 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005274 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005275 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005276 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5277 I != N; ++I) {
5278 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005279 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005280 continue;
5281
Sebastian Redldb9d2142010-08-02 23:18:59 +00005282 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005283 }
5284 }
5285
Sebastian Redldb9d2142010-08-02 23:18:59 +00005286 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5287 MEnd = MethodPool.end();
5288 M != MEnd; ++M) {
5289 for (ObjCMethodList *MethList = &M->second.first;
5290 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005291 MethList = MethList->Next) {
5292 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5293 NumSelIdents))
5294 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005295
5296 if (!Selectors.insert(MethList->Method->getSelector()))
5297 continue;
5298
Douglas Gregor13438f92010-04-06 16:40:00 +00005299 Result R(MethList->Method, 0);
5300 R.StartParameter = NumSelIdents;
5301 R.AllParametersAreInformative = false;
5302 Results.MaybeAddResult(R, CurContext);
5303 }
5304 }
5305 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005306 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005307
5308
5309 // If we're actually at the argument expression (rather than prior to the
5310 // selector), we're actually performing code completion for an expression.
5311 // Determine whether we have a single, best method. If so, we can
5312 // code-complete the expression using the corresponding parameter type as
5313 // our preferred type, improving completion results.
5314 if (AtArgumentExpression) {
5315 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5316 NumSelIdents);
5317 if (PreferredType.isNull())
5318 CodeCompleteOrdinaryName(S, PCC_Expression);
5319 else
5320 CodeCompleteExpression(S, PreferredType);
5321 return;
5322 }
5323
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005324 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005325 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005326 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005327}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005328
Douglas Gregorfb629412010-08-23 21:17:50 +00005329void Sema::CodeCompleteObjCForCollection(Scope *S,
5330 DeclGroupPtrTy IterationVar) {
5331 CodeCompleteExpressionData Data;
5332 Data.ObjCCollection = true;
5333
5334 if (IterationVar.getAsOpaquePtr()) {
5335 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5336 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5337 if (*I)
5338 Data.IgnoreDecls.push_back(*I);
5339 }
5340 }
5341
5342 CodeCompleteExpression(S, Data);
5343}
5344
Douglas Gregor458433d2010-08-26 15:07:07 +00005345void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5346 unsigned NumSelIdents) {
5347 // If we have an external source, load the entire class method
5348 // pool from the AST file.
5349 if (ExternalSource) {
5350 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5351 I != N; ++I) {
5352 Selector Sel = ExternalSource->GetExternalSelector(I);
5353 if (Sel.isNull() || MethodPool.count(Sel))
5354 continue;
5355
5356 ReadMethodPool(Sel);
5357 }
5358 }
5359
Douglas Gregor218937c2011-02-01 19:23:04 +00005360 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5361 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005362 Results.EnterNewScope();
5363 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5364 MEnd = MethodPool.end();
5365 M != MEnd; ++M) {
5366
5367 Selector Sel = M->first;
5368 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5369 continue;
5370
Douglas Gregor218937c2011-02-01 19:23:04 +00005371 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005372 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005373 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005374 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005375 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005376 continue;
5377 }
5378
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005379 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005380 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005381 if (I == NumSelIdents) {
5382 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005383 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005384 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005385 Accumulator.clear();
5386 }
5387 }
5388
Benjamin Kramera0651c52011-07-26 16:59:25 +00005389 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005390 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005391 }
Douglas Gregordae68752011-02-01 22:57:45 +00005392 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005393 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005394 }
5395 Results.ExitScope();
5396
5397 HandleCodeCompleteResults(this, CodeCompleter,
5398 CodeCompletionContext::CCC_SelectorName,
5399 Results.data(), Results.size());
5400}
5401
Douglas Gregor55385fe2009-11-18 04:19:12 +00005402/// \brief Add all of the protocol declarations that we find in the given
5403/// (translation unit) context.
5404static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005405 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005406 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005407 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005408
5409 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5410 DEnd = Ctx->decls_end();
5411 D != DEnd; ++D) {
5412 // Record any protocols we find.
5413 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005414 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005415 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005416
5417 // Record any forward-declared protocols we find.
5418 if (ObjCForwardProtocolDecl *Forward
5419 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5420 for (ObjCForwardProtocolDecl::protocol_iterator
5421 P = Forward->protocol_begin(),
5422 PEnd = Forward->protocol_end();
5423 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005424 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005425 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005426 }
5427 }
5428}
5429
5430void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5431 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005432 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5433 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005434
Douglas Gregor70c23352010-12-09 21:44:02 +00005435 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5436 Results.EnterNewScope();
5437
5438 // Tell the result set to ignore all of the protocols we have
5439 // already seen.
5440 // FIXME: This doesn't work when caching code-completion results.
5441 for (unsigned I = 0; I != NumProtocols; ++I)
5442 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5443 Protocols[I].second))
5444 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005445
Douglas Gregor70c23352010-12-09 21:44:02 +00005446 // Add all protocols.
5447 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5448 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005449
Douglas Gregor70c23352010-12-09 21:44:02 +00005450 Results.ExitScope();
5451 }
5452
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005453 HandleCodeCompleteResults(this, CodeCompleter,
5454 CodeCompletionContext::CCC_ObjCProtocolName,
5455 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005456}
5457
5458void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005459 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5460 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005461
Douglas Gregor70c23352010-12-09 21:44:02 +00005462 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5463 Results.EnterNewScope();
5464
5465 // Add all protocols.
5466 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5467 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005468
Douglas Gregor70c23352010-12-09 21:44:02 +00005469 Results.ExitScope();
5470 }
5471
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005472 HandleCodeCompleteResults(this, CodeCompleter,
5473 CodeCompletionContext::CCC_ObjCProtocolName,
5474 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005475}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005476
5477/// \brief Add all of the Objective-C interface declarations that we find in
5478/// the given (translation unit) context.
5479static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5480 bool OnlyForwardDeclarations,
5481 bool OnlyUnimplemented,
5482 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005483 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005484
5485 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5486 DEnd = Ctx->decls_end();
5487 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005488 // Record any interfaces we find.
5489 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5490 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5491 (!OnlyUnimplemented || !Class->getImplementation()))
5492 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005493
5494 // Record any forward-declared interfaces we find.
5495 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005496 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5497 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5498 (!OnlyUnimplemented || !IDecl->getImplementation()))
5499 Results.AddResult(Result(IDecl, 0), CurContext,
5500 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005501 }
5502 }
5503}
5504
5505void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005506 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5507 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005508 Results.EnterNewScope();
5509
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005510 if (CodeCompleter->includeGlobals()) {
5511 // Add all classes.
5512 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5513 false, Results);
5514 }
5515
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005516 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005517
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005518 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005519 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005520 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005521}
5522
Douglas Gregorc83c6872010-04-15 22:33:43 +00005523void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5524 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005525 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005526 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005527 Results.EnterNewScope();
5528
5529 // Make sure that we ignore the class we're currently defining.
5530 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005531 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005532 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005533 Results.Ignore(CurClass);
5534
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005535 if (CodeCompleter->includeGlobals()) {
5536 // Add all classes.
5537 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5538 false, Results);
5539 }
5540
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005541 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005542
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005543 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005544 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005545 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005546}
5547
5548void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005549 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5550 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005551 Results.EnterNewScope();
5552
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005553 if (CodeCompleter->includeGlobals()) {
5554 // Add all unimplemented classes.
5555 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5556 true, Results);
5557 }
5558
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005559 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005560
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005561 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005562 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005563 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005564}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005565
5566void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005567 IdentifierInfo *ClassName,
5568 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005569 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005570
Douglas Gregor218937c2011-02-01 19:23:04 +00005571 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005572 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005573
5574 // Ignore any categories we find that have already been implemented by this
5575 // interface.
5576 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5577 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005578 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005579 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5580 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5581 Category = Category->getNextClassCategory())
5582 CategoryNames.insert(Category->getIdentifier());
5583
5584 // Add all of the categories we know about.
5585 Results.EnterNewScope();
5586 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5587 for (DeclContext::decl_iterator D = TU->decls_begin(),
5588 DEnd = TU->decls_end();
5589 D != DEnd; ++D)
5590 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5591 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005592 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005593 Results.ExitScope();
5594
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005595 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005596 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005597 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005598}
5599
5600void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005601 IdentifierInfo *ClassName,
5602 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005603 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005604
5605 // Find the corresponding interface. If we couldn't find the interface, the
5606 // program itself is ill-formed. However, we'll try to be helpful still by
5607 // providing the list of all of the categories we know about.
5608 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005609 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005610 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5611 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005612 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005613
Douglas Gregor218937c2011-02-01 19:23:04 +00005614 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005615 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005616
5617 // Add all of the categories that have have corresponding interface
5618 // declarations in this class and any of its superclasses, except for
5619 // already-implemented categories in the class itself.
5620 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5621 Results.EnterNewScope();
5622 bool IgnoreImplemented = true;
5623 while (Class) {
5624 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5625 Category = Category->getNextClassCategory())
5626 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5627 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005628 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005629
5630 Class = Class->getSuperClass();
5631 IgnoreImplemented = false;
5632 }
5633 Results.ExitScope();
5634
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005635 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005636 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005637 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005638}
Douglas Gregor322328b2009-11-18 22:32:06 +00005639
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005640void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005641 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005642 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5643 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005644
5645 // Figure out where this @synthesize lives.
5646 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005647 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005648 if (!Container ||
5649 (!isa<ObjCImplementationDecl>(Container) &&
5650 !isa<ObjCCategoryImplDecl>(Container)))
5651 return;
5652
5653 // Ignore any properties that have already been implemented.
5654 for (DeclContext::decl_iterator D = Container->decls_begin(),
5655 DEnd = Container->decls_end();
5656 D != DEnd; ++D)
5657 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5658 Results.Ignore(PropertyImpl->getPropertyDecl());
5659
5660 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005661 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005662 Results.EnterNewScope();
5663 if (ObjCImplementationDecl *ClassImpl
5664 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005665 AddObjCProperties(ClassImpl->getClassInterface(), false,
5666 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005667 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005668 else
5669 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005670 false, /*AllowNullaryMethods=*/false, CurContext,
5671 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005672 Results.ExitScope();
5673
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005674 HandleCodeCompleteResults(this, CodeCompleter,
5675 CodeCompletionContext::CCC_Other,
5676 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005677}
5678
5679void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005680 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005681 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005682 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5683 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005684
5685 // Figure out where this @synthesize lives.
5686 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005687 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005688 if (!Container ||
5689 (!isa<ObjCImplementationDecl>(Container) &&
5690 !isa<ObjCCategoryImplDecl>(Container)))
5691 return;
5692
5693 // Figure out which interface we're looking into.
5694 ObjCInterfaceDecl *Class = 0;
5695 if (ObjCImplementationDecl *ClassImpl
5696 = dyn_cast<ObjCImplementationDecl>(Container))
5697 Class = ClassImpl->getClassInterface();
5698 else
5699 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5700 ->getClassInterface();
5701
Douglas Gregore8426052011-04-18 14:40:46 +00005702 // Determine the type of the property we're synthesizing.
5703 QualType PropertyType = Context.getObjCIdType();
5704 if (Class) {
5705 if (ObjCPropertyDecl *Property
5706 = Class->FindPropertyDeclaration(PropertyName)) {
5707 PropertyType
5708 = Property->getType().getNonReferenceType().getUnqualifiedType();
5709
5710 // Give preference to ivars
5711 Results.setPreferredType(PropertyType);
5712 }
5713 }
5714
Douglas Gregor322328b2009-11-18 22:32:06 +00005715 // Add all of the instance variables in this class and its superclasses.
5716 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005717 bool SawSimilarlyNamedIvar = false;
5718 std::string NameWithPrefix;
5719 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005720 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005721 std::string NameWithSuffix = PropertyName->getName().str();
5722 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005723 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005724 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5725 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005726 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5727
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005728 // Determine whether we've seen an ivar with a name similar to the
5729 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005730 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005731 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005732 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005733 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005734
5735 // Reduce the priority of this result by one, to give it a slight
5736 // advantage over other results whose names don't match so closely.
5737 if (Results.size() &&
5738 Results.data()[Results.size() - 1].Kind
5739 == CodeCompletionResult::RK_Declaration &&
5740 Results.data()[Results.size() - 1].Declaration == Ivar)
5741 Results.data()[Results.size() - 1].Priority--;
5742 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005743 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005744 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005745
5746 if (!SawSimilarlyNamedIvar) {
5747 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005748 // an ivar of the appropriate type.
5749 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005750 typedef CodeCompletionResult Result;
5751 CodeCompletionAllocator &Allocator = Results.getAllocator();
5752 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5753
Douglas Gregor8987b232011-09-27 23:30:47 +00005754 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005755 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005756 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005757 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5758 Results.AddResult(Result(Builder.TakeString(), Priority,
5759 CXCursor_ObjCIvarDecl));
5760 }
5761
Douglas Gregor322328b2009-11-18 22:32:06 +00005762 Results.ExitScope();
5763
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005764 HandleCodeCompleteResults(this, CodeCompleter,
5765 CodeCompletionContext::CCC_Other,
5766 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005767}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005768
Douglas Gregor408be5a2010-08-25 01:08:01 +00005769// Mapping from selectors to the methods that implement that selector, along
5770// with the "in original class" flag.
5771typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5772 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005773
5774/// \brief Find all of the methods that reside in the given container
5775/// (and its superclasses, protocols, etc.) that meet the given
5776/// criteria. Insert those methods into the map of known methods,
5777/// indexed by selector so they can be easily found.
5778static void FindImplementableMethods(ASTContext &Context,
5779 ObjCContainerDecl *Container,
5780 bool WantInstanceMethods,
5781 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005782 KnownMethodsMap &KnownMethods,
5783 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005784 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5785 // Recurse into protocols.
5786 const ObjCList<ObjCProtocolDecl> &Protocols
5787 = IFace->getReferencedProtocols();
5788 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005789 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005790 I != E; ++I)
5791 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005792 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005793
Douglas Gregorea766182010-10-18 18:21:28 +00005794 // Add methods from any class extensions and categories.
5795 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5796 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005797 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5798 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005799 KnownMethods, false);
5800
5801 // Visit the superclass.
5802 if (IFace->getSuperClass())
5803 FindImplementableMethods(Context, IFace->getSuperClass(),
5804 WantInstanceMethods, ReturnType,
5805 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005806 }
5807
5808 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5809 // Recurse into protocols.
5810 const ObjCList<ObjCProtocolDecl> &Protocols
5811 = Category->getReferencedProtocols();
5812 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005813 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005814 I != E; ++I)
5815 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005816 KnownMethods, InOriginalClass);
5817
5818 // If this category is the original class, jump to the interface.
5819 if (InOriginalClass && Category->getClassInterface())
5820 FindImplementableMethods(Context, Category->getClassInterface(),
5821 WantInstanceMethods, ReturnType, KnownMethods,
5822 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005823 }
5824
5825 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5826 // Recurse into protocols.
5827 const ObjCList<ObjCProtocolDecl> &Protocols
5828 = Protocol->getReferencedProtocols();
5829 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5830 E = Protocols.end();
5831 I != E; ++I)
5832 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005833 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005834 }
5835
5836 // Add methods in this container. This operation occurs last because
5837 // we want the methods from this container to override any methods
5838 // we've previously seen with the same selector.
5839 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5840 MEnd = Container->meth_end();
5841 M != MEnd; ++M) {
5842 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5843 if (!ReturnType.isNull() &&
5844 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5845 continue;
5846
Douglas Gregor408be5a2010-08-25 01:08:01 +00005847 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005848 }
5849 }
5850}
5851
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005852/// \brief Add the parenthesized return or parameter type chunk to a code
5853/// completion string.
5854static void AddObjCPassingTypeChunk(QualType Type,
5855 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005856 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005857 CodeCompletionBuilder &Builder) {
5858 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005859 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005860 Builder.getAllocator()));
5861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5862}
5863
5864/// \brief Determine whether the given class is or inherits from a class by
5865/// the given name.
5866static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005867 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005868 if (!Class)
5869 return false;
5870
5871 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5872 return true;
5873
5874 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5875}
5876
5877/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5878/// Key-Value Observing (KVO).
5879static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5880 bool IsInstanceMethod,
5881 QualType ReturnType,
5882 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005883 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005884 ResultBuilder &Results) {
5885 IdentifierInfo *PropName = Property->getIdentifier();
5886 if (!PropName || PropName->getLength() == 0)
5887 return;
5888
Douglas Gregor8987b232011-09-27 23:30:47 +00005889 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5890
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005891 // Builder that will create each code completion.
5892 typedef CodeCompletionResult Result;
5893 CodeCompletionAllocator &Allocator = Results.getAllocator();
5894 CodeCompletionBuilder Builder(Allocator);
5895
5896 // The selector table.
5897 SelectorTable &Selectors = Context.Selectors;
5898
5899 // The property name, copied into the code completion allocation region
5900 // on demand.
5901 struct KeyHolder {
5902 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005903 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005904 const char *CopiedKey;
5905
Chris Lattner5f9e2722011-07-23 10:55:15 +00005906 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005907 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5908
5909 operator const char *() {
5910 if (CopiedKey)
5911 return CopiedKey;
5912
5913 return CopiedKey = Allocator.CopyString(Key);
5914 }
5915 } Key(Allocator, PropName->getName());
5916
5917 // The uppercased name of the property name.
5918 std::string UpperKey = PropName->getName();
5919 if (!UpperKey.empty())
5920 UpperKey[0] = toupper(UpperKey[0]);
5921
5922 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5923 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5924 Property->getType());
5925 bool ReturnTypeMatchesVoid
5926 = ReturnType.isNull() || ReturnType->isVoidType();
5927
5928 // Add the normal accessor -(type)key.
5929 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005930 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005931 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5932 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005933 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005934
5935 Builder.AddTypedTextChunk(Key);
5936 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5937 CXCursor_ObjCInstanceMethodDecl));
5938 }
5939
5940 // If we have an integral or boolean property (or the user has provided
5941 // an integral or boolean return type), add the accessor -(type)isKey.
5942 if (IsInstanceMethod &&
5943 ((!ReturnType.isNull() &&
5944 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5945 (ReturnType.isNull() &&
5946 (Property->getType()->isIntegerType() ||
5947 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005948 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005949 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005950 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005951 if (ReturnType.isNull()) {
5952 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5953 Builder.AddTextChunk("BOOL");
5954 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5955 }
5956
5957 Builder.AddTypedTextChunk(
5958 Allocator.CopyString(SelectorId->getName()));
5959 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5960 CXCursor_ObjCInstanceMethodDecl));
5961 }
5962 }
5963
5964 // Add the normal mutator.
5965 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5966 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005967 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005968 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005969 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005970 if (ReturnType.isNull()) {
5971 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5972 Builder.AddTextChunk("void");
5973 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5974 }
5975
5976 Builder.AddTypedTextChunk(
5977 Allocator.CopyString(SelectorId->getName()));
5978 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005979 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005980 Builder.AddTextChunk(Key);
5981 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5982 CXCursor_ObjCInstanceMethodDecl));
5983 }
5984 }
5985
5986 // Indexed and unordered accessors
5987 unsigned IndexedGetterPriority = CCP_CodePattern;
5988 unsigned IndexedSetterPriority = CCP_CodePattern;
5989 unsigned UnorderedGetterPriority = CCP_CodePattern;
5990 unsigned UnorderedSetterPriority = CCP_CodePattern;
5991 if (const ObjCObjectPointerType *ObjCPointer
5992 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5993 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5994 // If this interface type is not provably derived from a known
5995 // collection, penalize the corresponding completions.
5996 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5997 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5998 if (!InheritsFromClassNamed(IFace, "NSArray"))
5999 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6000 }
6001
6002 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6003 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6004 if (!InheritsFromClassNamed(IFace, "NSSet"))
6005 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6006 }
6007 }
6008 } else {
6009 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6010 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6011 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6012 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6013 }
6014
6015 // Add -(NSUInteger)countOf<key>
6016 if (IsInstanceMethod &&
6017 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006018 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006019 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006020 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006021 if (ReturnType.isNull()) {
6022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6023 Builder.AddTextChunk("NSUInteger");
6024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6025 }
6026
6027 Builder.AddTypedTextChunk(
6028 Allocator.CopyString(SelectorId->getName()));
6029 Results.AddResult(Result(Builder.TakeString(),
6030 std::min(IndexedGetterPriority,
6031 UnorderedGetterPriority),
6032 CXCursor_ObjCInstanceMethodDecl));
6033 }
6034 }
6035
6036 // Indexed getters
6037 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6038 if (IsInstanceMethod &&
6039 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006040 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006041 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006042 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006043 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006044 if (ReturnType.isNull()) {
6045 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6046 Builder.AddTextChunk("id");
6047 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6048 }
6049
6050 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6051 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6052 Builder.AddTextChunk("NSUInteger");
6053 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6054 Builder.AddTextChunk("index");
6055 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6056 CXCursor_ObjCInstanceMethodDecl));
6057 }
6058 }
6059
6060 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6061 if (IsInstanceMethod &&
6062 (ReturnType.isNull() ||
6063 (ReturnType->isObjCObjectPointerType() &&
6064 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6065 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6066 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006067 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006068 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006069 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006070 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006071 if (ReturnType.isNull()) {
6072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6073 Builder.AddTextChunk("NSArray *");
6074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6075 }
6076
6077 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6079 Builder.AddTextChunk("NSIndexSet *");
6080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6081 Builder.AddTextChunk("indexes");
6082 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6083 CXCursor_ObjCInstanceMethodDecl));
6084 }
6085 }
6086
6087 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6088 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006089 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006090 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006091 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006092 &Context.Idents.get("range")
6093 };
6094
Douglas Gregore74c25c2011-05-04 23:50:46 +00006095 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006096 if (ReturnType.isNull()) {
6097 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6098 Builder.AddTextChunk("void");
6099 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6100 }
6101
6102 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6104 Builder.AddPlaceholderChunk("object-type");
6105 Builder.AddTextChunk(" **");
6106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6107 Builder.AddTextChunk("buffer");
6108 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6109 Builder.AddTypedTextChunk("range:");
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddTextChunk("NSRange");
6112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6113 Builder.AddTextChunk("inRange");
6114 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6115 CXCursor_ObjCInstanceMethodDecl));
6116 }
6117 }
6118
6119 // Mutable indexed accessors
6120
6121 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6122 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006123 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006124 IdentifierInfo *SelectorIds[2] = {
6125 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006126 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006127 };
6128
Douglas Gregore74c25c2011-05-04 23:50:46 +00006129 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006130 if (ReturnType.isNull()) {
6131 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6132 Builder.AddTextChunk("void");
6133 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6134 }
6135
6136 Builder.AddTypedTextChunk("insertObject:");
6137 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6138 Builder.AddPlaceholderChunk("object-type");
6139 Builder.AddTextChunk(" *");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 Builder.AddTextChunk("object");
6142 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6143 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6144 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6145 Builder.AddPlaceholderChunk("NSUInteger");
6146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6147 Builder.AddTextChunk("index");
6148 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6149 CXCursor_ObjCInstanceMethodDecl));
6150 }
6151 }
6152
6153 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6154 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006155 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006156 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006157 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006158 &Context.Idents.get("atIndexes")
6159 };
6160
Douglas Gregore74c25c2011-05-04 23:50:46 +00006161 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006162 if (ReturnType.isNull()) {
6163 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6164 Builder.AddTextChunk("void");
6165 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6166 }
6167
6168 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6169 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6170 Builder.AddTextChunk("NSArray *");
6171 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6172 Builder.AddTextChunk("array");
6173 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6174 Builder.AddTypedTextChunk("atIndexes:");
6175 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6176 Builder.AddPlaceholderChunk("NSIndexSet *");
6177 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6178 Builder.AddTextChunk("indexes");
6179 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6180 CXCursor_ObjCInstanceMethodDecl));
6181 }
6182 }
6183
6184 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6185 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006186 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006187 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006188 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006189 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006190 if (ReturnType.isNull()) {
6191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6192 Builder.AddTextChunk("void");
6193 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6194 }
6195
6196 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6198 Builder.AddTextChunk("NSUInteger");
6199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6200 Builder.AddTextChunk("index");
6201 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6202 CXCursor_ObjCInstanceMethodDecl));
6203 }
6204 }
6205
6206 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6207 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006208 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006209 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006210 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006211 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006212 if (ReturnType.isNull()) {
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddTextChunk("void");
6215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6216 }
6217
6218 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddTextChunk("NSIndexSet *");
6221 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6222 Builder.AddTextChunk("indexes");
6223 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6224 CXCursor_ObjCInstanceMethodDecl));
6225 }
6226 }
6227
6228 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6229 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006230 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006231 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006232 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006233 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006234 &Context.Idents.get("withObject")
6235 };
6236
Douglas Gregore74c25c2011-05-04 23:50:46 +00006237 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006238 if (ReturnType.isNull()) {
6239 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6240 Builder.AddTextChunk("void");
6241 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6242 }
6243
6244 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6245 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6246 Builder.AddPlaceholderChunk("NSUInteger");
6247 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6248 Builder.AddTextChunk("index");
6249 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6250 Builder.AddTypedTextChunk("withObject:");
6251 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6252 Builder.AddTextChunk("id");
6253 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6254 Builder.AddTextChunk("object");
6255 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6256 CXCursor_ObjCInstanceMethodDecl));
6257 }
6258 }
6259
6260 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6261 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006262 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006263 = (Twine("replace") + UpperKey + "AtIndexes").str();
6264 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006265 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006266 &Context.Idents.get(SelectorName1),
6267 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006268 };
6269
Douglas Gregore74c25c2011-05-04 23:50:46 +00006270 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006271 if (ReturnType.isNull()) {
6272 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6273 Builder.AddTextChunk("void");
6274 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6275 }
6276
6277 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6278 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6279 Builder.AddPlaceholderChunk("NSIndexSet *");
6280 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6281 Builder.AddTextChunk("indexes");
6282 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6283 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6284 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6285 Builder.AddTextChunk("NSArray *");
6286 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6287 Builder.AddTextChunk("array");
6288 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6289 CXCursor_ObjCInstanceMethodDecl));
6290 }
6291 }
6292
6293 // Unordered getters
6294 // - (NSEnumerator *)enumeratorOfKey
6295 if (IsInstanceMethod &&
6296 (ReturnType.isNull() ||
6297 (ReturnType->isObjCObjectPointerType() &&
6298 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6299 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6300 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006301 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006302 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006303 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006304 if (ReturnType.isNull()) {
6305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6306 Builder.AddTextChunk("NSEnumerator *");
6307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6308 }
6309
6310 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6311 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6312 CXCursor_ObjCInstanceMethodDecl));
6313 }
6314 }
6315
6316 // - (type *)memberOfKey:(type *)object
6317 if (IsInstanceMethod &&
6318 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006319 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006320 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006321 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006322 if (ReturnType.isNull()) {
6323 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6324 Builder.AddPlaceholderChunk("object-type");
6325 Builder.AddTextChunk(" *");
6326 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6327 }
6328
6329 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6330 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6331 if (ReturnType.isNull()) {
6332 Builder.AddPlaceholderChunk("object-type");
6333 Builder.AddTextChunk(" *");
6334 } else {
6335 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006336 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006337 Builder.getAllocator()));
6338 }
6339 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6340 Builder.AddTextChunk("object");
6341 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6342 CXCursor_ObjCInstanceMethodDecl));
6343 }
6344 }
6345
6346 // Mutable unordered accessors
6347 // - (void)addKeyObject:(type *)object
6348 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006349 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006350 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006351 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006352 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006353 if (ReturnType.isNull()) {
6354 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6355 Builder.AddTextChunk("void");
6356 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6357 }
6358
6359 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6360 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6361 Builder.AddPlaceholderChunk("object-type");
6362 Builder.AddTextChunk(" *");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 Builder.AddTextChunk("object");
6365 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6366 CXCursor_ObjCInstanceMethodDecl));
6367 }
6368 }
6369
6370 // - (void)addKey:(NSSet *)objects
6371 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006372 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006373 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006374 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006375 if (ReturnType.isNull()) {
6376 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6377 Builder.AddTextChunk("void");
6378 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6379 }
6380
6381 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("NSSet *");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 Builder.AddTextChunk("objects");
6386 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6387 CXCursor_ObjCInstanceMethodDecl));
6388 }
6389 }
6390
6391 // - (void)removeKeyObject:(type *)object
6392 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006393 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006394 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006395 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006396 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006397 if (ReturnType.isNull()) {
6398 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6399 Builder.AddTextChunk("void");
6400 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6401 }
6402
6403 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6404 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6405 Builder.AddPlaceholderChunk("object-type");
6406 Builder.AddTextChunk(" *");
6407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6408 Builder.AddTextChunk("object");
6409 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6410 CXCursor_ObjCInstanceMethodDecl));
6411 }
6412 }
6413
6414 // - (void)removeKey:(NSSet *)objects
6415 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006416 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006417 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006418 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006419 if (ReturnType.isNull()) {
6420 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6421 Builder.AddTextChunk("void");
6422 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6423 }
6424
6425 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6426 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6427 Builder.AddTextChunk("NSSet *");
6428 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6429 Builder.AddTextChunk("objects");
6430 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6431 CXCursor_ObjCInstanceMethodDecl));
6432 }
6433 }
6434
6435 // - (void)intersectKey:(NSSet *)objects
6436 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006437 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006438 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006439 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006440 if (ReturnType.isNull()) {
6441 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6442 Builder.AddTextChunk("void");
6443 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6444 }
6445
6446 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6447 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6448 Builder.AddTextChunk("NSSet *");
6449 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6450 Builder.AddTextChunk("objects");
6451 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6452 CXCursor_ObjCInstanceMethodDecl));
6453 }
6454 }
6455
6456 // Key-Value Observing
6457 // + (NSSet *)keyPathsForValuesAffectingKey
6458 if (!IsInstanceMethod &&
6459 (ReturnType.isNull() ||
6460 (ReturnType->isObjCObjectPointerType() &&
6461 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6462 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6463 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006464 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006465 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006466 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006467 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006468 if (ReturnType.isNull()) {
6469 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6470 Builder.AddTextChunk("NSSet *");
6471 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6472 }
6473
6474 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6475 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006476 CXCursor_ObjCClassMethodDecl));
6477 }
6478 }
6479
6480 // + (BOOL)automaticallyNotifiesObserversForKey
6481 if (!IsInstanceMethod &&
6482 (ReturnType.isNull() ||
6483 ReturnType->isIntegerType() ||
6484 ReturnType->isBooleanType())) {
6485 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006486 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006487 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6488 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6489 if (ReturnType.isNull()) {
6490 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6491 Builder.AddTextChunk("BOOL");
6492 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6493 }
6494
6495 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6496 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6497 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006498 }
6499 }
6500}
6501
Douglas Gregore8f5a172010-04-07 00:21:17 +00006502void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6503 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006504 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006505 // Determine the return type of the method we're declaring, if
6506 // provided.
6507 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006508 Decl *IDecl = 0;
6509 if (CurContext->isObjCContainer()) {
6510 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6511 IDecl = cast<Decl>(OCD);
6512 }
Douglas Gregorea766182010-10-18 18:21:28 +00006513 // Determine where we should start searching for methods.
6514 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006515 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006516 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006517 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6518 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006519 IsInImplementation = true;
6520 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006521 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006523 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006524 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006525 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006526 }
6527
6528 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006529 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006531 }
6532
Douglas Gregorea766182010-10-18 18:21:28 +00006533 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006534 HandleCodeCompleteResults(this, CodeCompleter,
6535 CodeCompletionContext::CCC_Other,
6536 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006537 return;
6538 }
6539
6540 // Find all of the methods that we could declare/implement here.
6541 KnownMethodsMap KnownMethods;
6542 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006543 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006544
Douglas Gregore8f5a172010-04-07 00:21:17 +00006545 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006546 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006547 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6548 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006549 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006550 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006551 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6552 MEnd = KnownMethods.end();
6553 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006554 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006555 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006556
6557 // If the result type was not already provided, add it to the
6558 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006559 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006560 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6561 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006562
6563 Selector Sel = Method->getSelector();
6564
6565 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006566 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006567 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006568
6569 // Add parameters to the pattern.
6570 unsigned I = 0;
6571 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6572 PEnd = Method->param_end();
6573 P != PEnd; (void)++P, ++I) {
6574 // Add the part of the selector name.
6575 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006576 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006577 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006578 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6579 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006580 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006581 } else
6582 break;
6583
6584 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006585 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6586 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006587
6588 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006589 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006590 }
6591
6592 if (Method->isVariadic()) {
6593 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006594 Builder.AddChunk(CodeCompletionString::CK_Comma);
6595 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006596 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006597
Douglas Gregor447107d2010-05-28 00:57:46 +00006598 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006599 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006600 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6601 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6602 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006603 if (!Method->getResultType()->isVoidType()) {
6604 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006605 Builder.AddTextChunk("return");
6606 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6607 Builder.AddPlaceholderChunk("expression");
6608 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006609 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006610 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006611
Douglas Gregor218937c2011-02-01 19:23:04 +00006612 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6613 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006614 }
6615
Douglas Gregor408be5a2010-08-25 01:08:01 +00006616 unsigned Priority = CCP_CodePattern;
6617 if (!M->second.second)
6618 Priority += CCD_InBaseClass;
6619
Douglas Gregor218937c2011-02-01 19:23:04 +00006620 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006621 Method->isInstanceMethod()
6622 ? CXCursor_ObjCInstanceMethodDecl
6623 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006624 }
6625
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006626 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6627 // the properties in this class and its categories.
6628 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006629 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006630 Containers.push_back(SearchDecl);
6631
Douglas Gregore74c25c2011-05-04 23:50:46 +00006632 VisitedSelectorSet KnownSelectors;
6633 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6634 MEnd = KnownMethods.end();
6635 M != MEnd; ++M)
6636 KnownSelectors.insert(M->first);
6637
6638
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006639 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6640 if (!IFace)
6641 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6642 IFace = Category->getClassInterface();
6643
6644 if (IFace) {
6645 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6646 Category = Category->getNextClassCategory())
6647 Containers.push_back(Category);
6648 }
6649
6650 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6651 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6652 PEnd = Containers[I]->prop_end();
6653 P != PEnd; ++P) {
6654 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006655 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006656 }
6657 }
6658 }
6659
Douglas Gregore8f5a172010-04-07 00:21:17 +00006660 Results.ExitScope();
6661
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006662 HandleCodeCompleteResults(this, CodeCompleter,
6663 CodeCompletionContext::CCC_Other,
6664 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006665}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006666
6667void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6668 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006669 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006670 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006671 IdentifierInfo **SelIdents,
6672 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006673 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006674 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006675 if (ExternalSource) {
6676 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6677 I != N; ++I) {
6678 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006679 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006680 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006681
6682 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006683 }
6684 }
6685
6686 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006687 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006688 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6689 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006690
6691 if (ReturnTy)
6692 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006693
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006694 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006695 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6696 MEnd = MethodPool.end();
6697 M != MEnd; ++M) {
6698 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6699 &M->second.second;
6700 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006701 MethList = MethList->Next) {
6702 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6703 NumSelIdents))
6704 continue;
6705
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006706 if (AtParameterName) {
6707 // Suggest parameter names we've seen before.
6708 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6709 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6710 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006711 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006712 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006713 Param->getIdentifier()->getName()));
6714 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006715 }
6716 }
6717
6718 continue;
6719 }
6720
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006721 Result R(MethList->Method, 0);
6722 R.StartParameter = NumSelIdents;
6723 R.AllParametersAreInformative = false;
6724 R.DeclaringEntity = true;
6725 Results.MaybeAddResult(R, CurContext);
6726 }
6727 }
6728
6729 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006730 HandleCodeCompleteResults(this, CodeCompleter,
6731 CodeCompletionContext::CCC_Other,
6732 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006733}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006734
Douglas Gregorf29c5232010-08-24 22:20:20 +00006735void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006736 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006737 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006738 Results.EnterNewScope();
6739
6740 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006741 CodeCompletionBuilder Builder(Results.getAllocator());
6742 Builder.AddTypedTextChunk("if");
6743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6744 Builder.AddPlaceholderChunk("condition");
6745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006746
6747 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 Builder.AddTypedTextChunk("ifdef");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddPlaceholderChunk("macro");
6751 Results.AddResult(Builder.TakeString());
6752
Douglas Gregorf44e8542010-08-24 19:08:16 +00006753 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006754 Builder.AddTypedTextChunk("ifndef");
6755 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6756 Builder.AddPlaceholderChunk("macro");
6757 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758
6759 if (InConditional) {
6760 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006761 Builder.AddTypedTextChunk("elif");
6762 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6763 Builder.AddPlaceholderChunk("condition");
6764 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006765
6766 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006767 Builder.AddTypedTextChunk("else");
6768 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006769
6770 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006771 Builder.AddTypedTextChunk("endif");
6772 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006773 }
6774
6775 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006776 Builder.AddTypedTextChunk("include");
6777 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6778 Builder.AddTextChunk("\"");
6779 Builder.AddPlaceholderChunk("header");
6780 Builder.AddTextChunk("\"");
6781 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006782
6783 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006784 Builder.AddTypedTextChunk("include");
6785 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6786 Builder.AddTextChunk("<");
6787 Builder.AddPlaceholderChunk("header");
6788 Builder.AddTextChunk(">");
6789 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006790
6791 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006792 Builder.AddTypedTextChunk("define");
6793 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6794 Builder.AddPlaceholderChunk("macro");
6795 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006796
6797 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006798 Builder.AddTypedTextChunk("define");
6799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6800 Builder.AddPlaceholderChunk("macro");
6801 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6802 Builder.AddPlaceholderChunk("args");
6803 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6804 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006805
6806 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006807 Builder.AddTypedTextChunk("undef");
6808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6809 Builder.AddPlaceholderChunk("macro");
6810 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006811
6812 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006813 Builder.AddTypedTextChunk("line");
6814 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6815 Builder.AddPlaceholderChunk("number");
6816 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006817
6818 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006819 Builder.AddTypedTextChunk("line");
6820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6821 Builder.AddPlaceholderChunk("number");
6822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6823 Builder.AddTextChunk("\"");
6824 Builder.AddPlaceholderChunk("filename");
6825 Builder.AddTextChunk("\"");
6826 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006827
6828 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006829 Builder.AddTypedTextChunk("error");
6830 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6831 Builder.AddPlaceholderChunk("message");
6832 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006833
6834 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006835 Builder.AddTypedTextChunk("pragma");
6836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6837 Builder.AddPlaceholderChunk("arguments");
6838 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006839
6840 if (getLangOptions().ObjC1) {
6841 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006842 Builder.AddTypedTextChunk("import");
6843 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6844 Builder.AddTextChunk("\"");
6845 Builder.AddPlaceholderChunk("header");
6846 Builder.AddTextChunk("\"");
6847 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006848
6849 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006850 Builder.AddTypedTextChunk("import");
6851 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6852 Builder.AddTextChunk("<");
6853 Builder.AddPlaceholderChunk("header");
6854 Builder.AddTextChunk(">");
6855 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006856 }
6857
6858 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006859 Builder.AddTypedTextChunk("include_next");
6860 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6861 Builder.AddTextChunk("\"");
6862 Builder.AddPlaceholderChunk("header");
6863 Builder.AddTextChunk("\"");
6864 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006865
6866 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006867 Builder.AddTypedTextChunk("include_next");
6868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6869 Builder.AddTextChunk("<");
6870 Builder.AddPlaceholderChunk("header");
6871 Builder.AddTextChunk(">");
6872 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006873
6874 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006875 Builder.AddTypedTextChunk("warning");
6876 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6877 Builder.AddPlaceholderChunk("message");
6878 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006879
6880 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6881 // completions for them. And __include_macros is a Clang-internal extension
6882 // that we don't want to encourage anyone to use.
6883
6884 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6885 Results.ExitScope();
6886
Douglas Gregorf44e8542010-08-24 19:08:16 +00006887 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006888 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006889 Results.data(), Results.size());
6890}
6891
6892void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006893 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006894 S->getFnParent()? Sema::PCC_RecoveryInFunction
6895 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006896}
6897
Douglas Gregorf29c5232010-08-24 22:20:20 +00006898void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006899 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006900 IsDefinition? CodeCompletionContext::CCC_MacroName
6901 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006902 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6903 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006904 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006905 Results.EnterNewScope();
6906 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6907 MEnd = PP.macro_end();
6908 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006909 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006910 M->first->getName()));
6911 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006912 }
6913 Results.ExitScope();
6914 } else if (IsDefinition) {
6915 // FIXME: Can we detect when the user just wrote an include guard above?
6916 }
6917
Douglas Gregor52779fb2010-09-23 23:01:17 +00006918 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006919 Results.data(), Results.size());
6920}
6921
Douglas Gregorf29c5232010-08-24 22:20:20 +00006922void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006923 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006924 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006925
6926 if (!CodeCompleter || CodeCompleter->includeMacros())
6927 AddMacroResults(PP, Results);
6928
6929 // defined (<macro>)
6930 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006931 CodeCompletionBuilder Builder(Results.getAllocator());
6932 Builder.AddTypedTextChunk("defined");
6933 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6935 Builder.AddPlaceholderChunk("macro");
6936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6937 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006938 Results.ExitScope();
6939
6940 HandleCodeCompleteResults(this, CodeCompleter,
6941 CodeCompletionContext::CCC_PreprocessorExpression,
6942 Results.data(), Results.size());
6943}
6944
6945void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6946 IdentifierInfo *Macro,
6947 MacroInfo *MacroInfo,
6948 unsigned Argument) {
6949 // FIXME: In the future, we could provide "overload" results, much like we
6950 // do for function calls.
6951
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006952 // Now just ignore this. There will be another code-completion callback
6953 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006954}
6955
Douglas Gregor55817af2010-08-25 17:04:25 +00006956void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006957 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006958 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006959 0, 0);
6960}
6961
Douglas Gregordae68752011-02-01 22:57:45 +00006962void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006963 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006964 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006965 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6966 CodeCompletionDeclConsumer Consumer(Builder,
6967 Context.getTranslationUnitDecl());
6968 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6969 Consumer);
6970 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006971
6972 if (!CodeCompleter || CodeCompleter->includeMacros())
6973 AddMacroResults(PP, Builder);
6974
6975 Results.clear();
6976 Results.insert(Results.end(),
6977 Builder.data(), Builder.data() + Builder.size());
6978}