blob: 3d1c3bca866ab4c8e1b79ce80d5635c7d14db44d [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 }
David Blaikie7530c032012-01-17 06:56:22 +0000599
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000600 case Type::Complex:
601 return STC_Arithmetic;
602
603 case Type::Pointer:
604 return STC_Pointer;
605
606 case Type::BlockPointer:
607 return STC_Block;
608
609 case Type::LValueReference:
610 case Type::RValueReference:
611 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
612
613 case Type::ConstantArray:
614 case Type::IncompleteArray:
615 case Type::VariableArray:
616 case Type::DependentSizedArray:
617 return STC_Array;
618
619 case Type::DependentSizedExtVector:
620 case Type::Vector:
621 case Type::ExtVector:
622 return STC_Arithmetic;
623
624 case Type::FunctionProto:
625 case Type::FunctionNoProto:
626 return STC_Function;
627
628 case Type::Record:
629 return STC_Record;
630
631 case Type::Enum:
632 return STC_Arithmetic;
633
634 case Type::ObjCObject:
635 case Type::ObjCInterface:
636 case Type::ObjCObjectPointer:
637 return STC_ObjectiveC;
638
639 default:
640 return STC_Other;
641 }
642}
643
644/// \brief Get the type that a given expression will have if this declaration
645/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000646QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000647 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
648
649 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
650 return C.getTypeDeclType(Type);
651 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
652 return C.getObjCInterfaceType(Iface);
653
654 QualType T;
655 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000656 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000657 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000658 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000659 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000660 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000661 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
662 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
663 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
664 T = Property->getType();
665 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
666 T = Value->getType();
667 else
668 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000669
670 // Dig through references, function pointers, and block pointers to
671 // get down to the likely type of an expression when the entity is
672 // used.
673 do {
674 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
675 T = Ref->getPointeeType();
676 continue;
677 }
678
679 if (const PointerType *Pointer = T->getAs<PointerType>()) {
680 if (Pointer->getPointeeType()->isFunctionType()) {
681 T = Pointer->getPointeeType();
682 continue;
683 }
684
685 break;
686 }
687
688 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
689 T = Block->getPointeeType();
690 continue;
691 }
692
693 if (const FunctionType *Function = T->getAs<FunctionType>()) {
694 T = Function->getResultType();
695 continue;
696 }
697
698 break;
699 } while (true);
700
701 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000702}
703
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000704void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
705 // If this is an Objective-C method declaration whose selector matches our
706 // preferred selector, give it a priority boost.
707 if (!PreferredSelector.isNull())
708 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
709 if (PreferredSelector == Method->getSelector())
710 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000711
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000712 // If we have a preferred type, adjust the priority for results with exactly-
713 // matching or nearly-matching types.
714 if (!PreferredType.isNull()) {
715 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
716 if (!T.isNull()) {
717 CanQualType TC = SemaRef.Context.getCanonicalType(T);
718 // Check for exactly-matching types (modulo qualifiers).
719 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
720 R.Priority /= CCF_ExactTypeMatch;
721 // Check for nearly-matching types, based on classification of each.
722 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000723 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000724 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
725 R.Priority /= CCF_SimilarTypeMatch;
726 }
727 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000728}
729
Douglas Gregor6f942b22010-09-21 16:06:22 +0000730void ResultBuilder::MaybeAddConstructorResults(Result R) {
731 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
732 !CompletionContext.wantConstructorResults())
733 return;
734
735 ASTContext &Context = SemaRef.Context;
736 NamedDecl *D = R.Declaration;
737 CXXRecordDecl *Record = 0;
738 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
739 Record = ClassTemplate->getTemplatedDecl();
740 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
741 // Skip specializations and partial specializations.
742 if (isa<ClassTemplateSpecializationDecl>(Record))
743 return;
744 } else {
745 // There are no constructors here.
746 return;
747 }
748
749 Record = Record->getDefinition();
750 if (!Record)
751 return;
752
753
754 QualType RecordTy = Context.getTypeDeclType(Record);
755 DeclarationName ConstructorName
756 = Context.DeclarationNames.getCXXConstructorName(
757 Context.getCanonicalType(RecordTy));
758 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
759 Ctors.first != Ctors.second; ++Ctors.first) {
760 R.Declaration = *Ctors.first;
761 R.CursorKind = getCursorKindForDecl(R.Declaration);
762 Results.push_back(R);
763 }
764}
765
Douglas Gregore495b7f2010-01-14 00:20:49 +0000766void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
767 assert(!ShadowMaps.empty() && "Must enter into a results scope");
768
769 if (R.Kind != Result::RK_Declaration) {
770 // For non-declaration results, just add the result.
771 Results.push_back(R);
772 return;
773 }
774
775 // Look through using declarations.
776 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
777 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
778 return;
779 }
780
781 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
782 unsigned IDNS = CanonDecl->getIdentifierNamespace();
783
Douglas Gregor45bcd432010-01-14 03:21:49 +0000784 bool AsNestedNameSpecifier = false;
785 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000786 return;
787
Douglas Gregor6f942b22010-09-21 16:06:22 +0000788 // C++ constructors are never found by name lookup.
789 if (isa<CXXConstructorDecl>(R.Declaration))
790 return;
791
Douglas Gregor86d9a522009-09-21 16:56:56 +0000792 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000793 ShadowMapEntry::iterator I, IEnd;
794 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
795 if (NamePos != SMap.end()) {
796 I = NamePos->second.begin();
797 IEnd = NamePos->second.end();
798 }
799
800 for (; I != IEnd; ++I) {
801 NamedDecl *ND = I->first;
802 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000803 if (ND->getCanonicalDecl() == CanonDecl) {
804 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000805 Results[Index].Declaration = R.Declaration;
806
Douglas Gregor86d9a522009-09-21 16:56:56 +0000807 // We're done.
808 return;
809 }
810 }
811
812 // This is a new declaration in this scope. However, check whether this
813 // declaration name is hidden by a similarly-named declaration in an outer
814 // scope.
815 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
816 --SMEnd;
817 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000818 ShadowMapEntry::iterator I, IEnd;
819 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
820 if (NamePos != SM->end()) {
821 I = NamePos->second.begin();
822 IEnd = NamePos->second.end();
823 }
824 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000825 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000826 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000827 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
828 Decl::IDNS_ObjCProtocol)))
829 continue;
830
831 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000832 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000833 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000834 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000835 continue;
836
837 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000838 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000839 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840
841 break;
842 }
843 }
844
845 // Make sure that any given declaration only shows up in the result set once.
846 if (!AllDeclsFound.insert(CanonDecl))
847 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000848
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000849 // If the filter is for nested-name-specifiers, then this result starts a
850 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000851 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000852 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000853 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000854 } else
855 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000856
Douglas Gregor0563c262009-09-22 23:15:58 +0000857 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000858 if (R.QualifierIsInformative && !R.Qualifier &&
859 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000860 DeclContext *Ctx = R.Declaration->getDeclContext();
861 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
862 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
863 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
864 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
865 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
866 else
867 R.QualifierIsInformative = false;
868 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000869
Douglas Gregor86d9a522009-09-21 16:56:56 +0000870 // Insert this result into the set of results and into the current shadow
871 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000872 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000873 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000874
875 if (!AsNestedNameSpecifier)
876 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000877}
878
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000879void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000880 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000881 if (R.Kind != Result::RK_Declaration) {
882 // For non-declaration results, just add the result.
883 Results.push_back(R);
884 return;
885 }
886
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000887 // Look through using declarations.
888 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
889 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
890 return;
891 }
892
Douglas Gregor45bcd432010-01-14 03:21:49 +0000893 bool AsNestedNameSpecifier = false;
894 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000895 return;
896
Douglas Gregor6f942b22010-09-21 16:06:22 +0000897 // C++ constructors are never found by name lookup.
898 if (isa<CXXConstructorDecl>(R.Declaration))
899 return;
900
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000901 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
902 return;
903
904 // Make sure that any given declaration only shows up in the result set once.
905 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
906 return;
907
908 // If the filter is for nested-name-specifiers, then this result starts a
909 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000910 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000911 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000912 R.Priority = CCP_NestedNameSpecifier;
913 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000914 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
915 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000916 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000917 R.QualifierIsInformative = true;
918
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000919 // If this result is supposed to have an informative qualifier, add one.
920 if (R.QualifierIsInformative && !R.Qualifier &&
921 !R.StartsNestedNameSpecifier) {
922 DeclContext *Ctx = R.Declaration->getDeclContext();
923 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
924 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
925 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
926 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000927 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000928 else
929 R.QualifierIsInformative = false;
930 }
931
Douglas Gregor12e13132010-05-26 22:00:08 +0000932 // Adjust the priority if this result comes from a base class.
933 if (InBaseClass)
934 R.Priority += CCD_InBaseClass;
935
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000936 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000937
Douglas Gregor3cdee122010-08-26 16:36:48 +0000938 if (HasObjectTypeQualifiers)
939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
940 if (Method->isInstance()) {
941 Qualifiers MethodQuals
942 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
943 if (ObjectTypeQualifiers == MethodQuals)
944 R.Priority += CCD_ObjectQualifierMatch;
945 else if (ObjectTypeQualifiers - MethodQuals) {
946 // The method cannot be invoked, because doing so would drop
947 // qualifiers.
948 return;
949 }
950 }
951
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000952 // Insert this result into the set of results.
953 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000954
955 if (!AsNestedNameSpecifier)
956 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000957}
958
Douglas Gregora4477812010-01-14 16:01:26 +0000959void ResultBuilder::AddResult(Result R) {
960 assert(R.Kind != Result::RK_Declaration &&
961 "Declaration results need more context");
962 Results.push_back(R);
963}
964
Douglas Gregor86d9a522009-09-21 16:56:56 +0000965/// \brief Enter into a new scope.
966void ResultBuilder::EnterNewScope() {
967 ShadowMaps.push_back(ShadowMap());
968}
969
970/// \brief Exit from the current scope.
971void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000972 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
973 EEnd = ShadowMaps.back().end();
974 E != EEnd;
975 ++E)
976 E->second.Destroy();
977
Douglas Gregor86d9a522009-09-21 16:56:56 +0000978 ShadowMaps.pop_back();
979}
980
Douglas Gregor791215b2009-09-21 20:51:25 +0000981/// \brief Determines whether this given declaration will be found by
982/// ordinary name lookup.
983bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000984 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
985
Douglas Gregor791215b2009-09-21 20:51:25 +0000986 unsigned IDNS = Decl::IDNS_Ordinary;
987 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000988 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000989 else if (SemaRef.getLangOptions().ObjC1) {
990 if (isa<ObjCIvarDecl>(ND))
991 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000992 }
993
Douglas Gregor791215b2009-09-21 20:51:25 +0000994 return ND->getIdentifierNamespace() & IDNS;
995}
996
Douglas Gregor01dfea02010-01-10 23:08:15 +0000997/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000998/// ordinary name lookup but is not a type name.
999bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1000 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1001 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1002 return false;
1003
1004 unsigned IDNS = Decl::IDNS_Ordinary;
1005 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001006 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001007 else if (SemaRef.getLangOptions().ObjC1) {
1008 if (isa<ObjCIvarDecl>(ND))
1009 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001010 }
1011
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001012 return ND->getIdentifierNamespace() & IDNS;
1013}
1014
Douglas Gregorf9578432010-07-28 21:50:18 +00001015bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1016 if (!IsOrdinaryNonTypeName(ND))
1017 return 0;
1018
1019 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1020 if (VD->getType()->isIntegralOrEnumerationType())
1021 return true;
1022
1023 return false;
1024}
1025
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001026/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001027/// ordinary name lookup.
1028bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001029 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1030
Douglas Gregor01dfea02010-01-10 23:08:15 +00001031 unsigned IDNS = Decl::IDNS_Ordinary;
1032 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001033 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001034
1035 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001036 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1037 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038}
1039
Douglas Gregor86d9a522009-09-21 16:56:56 +00001040/// \brief Determines whether the given declaration is suitable as the
1041/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1042bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1043 // Allow us to find class templates, too.
1044 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1045 ND = ClassTemplate->getTemplatedDecl();
1046
1047 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1048}
1049
1050/// \brief Determines whether the given declaration is an enumeration.
1051bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1052 return isa<EnumDecl>(ND);
1053}
1054
1055/// \brief Determines whether the given declaration is a class or struct.
1056bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1057 // Allow us to find class templates, too.
1058 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1059 ND = ClassTemplate->getTemplatedDecl();
1060
1061 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001062 return RD->getTagKind() == TTK_Class ||
1063 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001064
1065 return false;
1066}
1067
1068/// \brief Determines whether the given declaration is a union.
1069bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1070 // Allow us to find class templates, too.
1071 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1072 ND = ClassTemplate->getTemplatedDecl();
1073
1074 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001075 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001076
1077 return false;
1078}
1079
1080/// \brief Determines whether the given declaration is a namespace.
1081bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1082 return isa<NamespaceDecl>(ND);
1083}
1084
1085/// \brief Determines whether the given declaration is a namespace or
1086/// namespace alias.
1087bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1088 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1089}
1090
Douglas Gregor76282942009-12-11 17:31:05 +00001091/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001092bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001093 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1094 ND = Using->getTargetDecl();
1095
1096 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001097}
1098
Douglas Gregor76282942009-12-11 17:31:05 +00001099/// \brief Determines which members of a class should be visible via
1100/// "." or "->". Only value declarations, nested name specifiers, and
1101/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001102bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001103 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1104 ND = Using->getTargetDecl();
1105
Douglas Gregorce821962009-12-11 18:14:22 +00001106 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1107 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001108}
1109
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001110static bool isObjCReceiverType(ASTContext &C, QualType T) {
1111 T = C.getCanonicalType(T);
1112 switch (T->getTypeClass()) {
1113 case Type::ObjCObject:
1114 case Type::ObjCInterface:
1115 case Type::ObjCObjectPointer:
1116 return true;
1117
1118 case Type::Builtin:
1119 switch (cast<BuiltinType>(T)->getKind()) {
1120 case BuiltinType::ObjCId:
1121 case BuiltinType::ObjCClass:
1122 case BuiltinType::ObjCSel:
1123 return true;
1124
1125 default:
1126 break;
1127 }
1128 return false;
1129
1130 default:
1131 break;
1132 }
1133
1134 if (!C.getLangOptions().CPlusPlus)
1135 return false;
1136
1137 // FIXME: We could perform more analysis here to determine whether a
1138 // particular class type has any conversions to Objective-C types. For now,
1139 // just accept all class types.
1140 return T->isDependentType() || T->isRecordType();
1141}
1142
1143bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1144 QualType T = getDeclUsageType(SemaRef.Context, ND);
1145 if (T.isNull())
1146 return false;
1147
1148 T = SemaRef.Context.getBaseElementType(T);
1149 return isObjCReceiverType(SemaRef.Context, T);
1150}
1151
Douglas Gregorfb629412010-08-23 21:17:50 +00001152bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1153 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1154 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1155 return false;
1156
1157 QualType T = getDeclUsageType(SemaRef.Context, ND);
1158 if (T.isNull())
1159 return false;
1160
1161 T = SemaRef.Context.getBaseElementType(T);
1162 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1163 T->isObjCIdType() ||
1164 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1165}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001166
Douglas Gregor52779fb2010-09-23 23:01:17 +00001167bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1168 return false;
1169}
1170
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001171/// \rief Determines whether the given declaration is an Objective-C
1172/// instance variable.
1173bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1174 return isa<ObjCIvarDecl>(ND);
1175}
1176
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001177namespace {
1178 /// \brief Visible declaration consumer that adds a code-completion result
1179 /// for each visible declaration.
1180 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1181 ResultBuilder &Results;
1182 DeclContext *CurContext;
1183
1184 public:
1185 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1186 : Results(Results), CurContext(CurContext) { }
1187
Erik Verbruggend1205962011-10-06 07:27:49 +00001188 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1189 bool InBaseClass) {
1190 bool Accessible = true;
Douglas Gregor17015ef2011-11-03 16:51:37 +00001191 if (Ctx)
1192 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1193
Erik Verbruggend1205962011-10-06 07:27:49 +00001194 ResultBuilder::Result Result(ND, 0, false, Accessible);
1195 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001196 }
1197 };
1198}
1199
Douglas Gregor86d9a522009-09-21 16:56:56 +00001200/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001201static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001202 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001203 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001204 Results.AddResult(Result("short", CCP_Type));
1205 Results.AddResult(Result("long", CCP_Type));
1206 Results.AddResult(Result("signed", CCP_Type));
1207 Results.AddResult(Result("unsigned", CCP_Type));
1208 Results.AddResult(Result("void", CCP_Type));
1209 Results.AddResult(Result("char", CCP_Type));
1210 Results.AddResult(Result("int", CCP_Type));
1211 Results.AddResult(Result("float", CCP_Type));
1212 Results.AddResult(Result("double", CCP_Type));
1213 Results.AddResult(Result("enum", CCP_Type));
1214 Results.AddResult(Result("struct", CCP_Type));
1215 Results.AddResult(Result("union", CCP_Type));
1216 Results.AddResult(Result("const", CCP_Type));
1217 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001218
Douglas Gregor86d9a522009-09-21 16:56:56 +00001219 if (LangOpts.C99) {
1220 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001221 Results.AddResult(Result("_Complex", CCP_Type));
1222 Results.AddResult(Result("_Imaginary", CCP_Type));
1223 Results.AddResult(Result("_Bool", CCP_Type));
1224 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001225 }
1226
Douglas Gregor218937c2011-02-01 19:23:04 +00001227 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001228 if (LangOpts.CPlusPlus) {
1229 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001230 Results.AddResult(Result("bool", CCP_Type +
1231 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001232 Results.AddResult(Result("class", CCP_Type));
1233 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001234
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001235 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001236 Builder.AddTypedTextChunk("typename");
1237 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1238 Builder.AddPlaceholderChunk("qualifier");
1239 Builder.AddTextChunk("::");
1240 Builder.AddPlaceholderChunk("name");
1241 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001242
Douglas Gregor86d9a522009-09-21 16:56:56 +00001243 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001244 Results.AddResult(Result("auto", CCP_Type));
1245 Results.AddResult(Result("char16_t", CCP_Type));
1246 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001247
Douglas Gregor218937c2011-02-01 19:23:04 +00001248 Builder.AddTypedTextChunk("decltype");
1249 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1250 Builder.AddPlaceholderChunk("expression");
1251 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1252 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001253 }
1254 }
1255
1256 // GNU extensions
1257 if (LangOpts.GNUMode) {
1258 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001259 // Results.AddResult(Result("_Decimal32"));
1260 // Results.AddResult(Result("_Decimal64"));
1261 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001262
Douglas Gregor218937c2011-02-01 19:23:04 +00001263 Builder.AddTypedTextChunk("typeof");
1264 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1265 Builder.AddPlaceholderChunk("expression");
1266 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001267
Douglas Gregor218937c2011-02-01 19:23:04 +00001268 Builder.AddTypedTextChunk("typeof");
1269 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1270 Builder.AddPlaceholderChunk("type");
1271 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1272 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001273 }
1274}
1275
John McCallf312b1e2010-08-26 23:41:50 +00001276static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001277 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001279 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280 // Note: we don't suggest either "auto" or "register", because both
1281 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1282 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001283 Results.AddResult(Result("extern"));
1284 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001285}
1286
John McCallf312b1e2010-08-26 23:41:50 +00001287static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001288 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001290 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001291 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001292 case Sema::PCC_Class:
1293 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001294 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001295 Results.AddResult(Result("explicit"));
1296 Results.AddResult(Result("friend"));
1297 Results.AddResult(Result("mutable"));
1298 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001299 }
1300 // Fall through
1301
John McCallf312b1e2010-08-26 23:41:50 +00001302 case Sema::PCC_ObjCInterface:
1303 case Sema::PCC_ObjCImplementation:
1304 case Sema::PCC_Namespace:
1305 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001306 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001307 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001308 break;
1309
John McCallf312b1e2010-08-26 23:41:50 +00001310 case Sema::PCC_ObjCInstanceVariableList:
1311 case Sema::PCC_Expression:
1312 case Sema::PCC_Statement:
1313 case Sema::PCC_ForInit:
1314 case Sema::PCC_Condition:
1315 case Sema::PCC_RecoveryInFunction:
1316 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001317 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001318 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001319 break;
1320 }
1321}
1322
Douglas Gregorbca403c2010-01-13 23:51:12 +00001323static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1324static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001326 ResultBuilder &Results,
1327 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001328static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001329 ResultBuilder &Results,
1330 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001331static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001332 ResultBuilder &Results,
1333 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001334static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001335
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001336static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001337 CodeCompletionBuilder Builder(Results.getAllocator());
1338 Builder.AddTypedTextChunk("typedef");
1339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1340 Builder.AddPlaceholderChunk("type");
1341 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1342 Builder.AddPlaceholderChunk("name");
1343 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001344}
1345
John McCallf312b1e2010-08-26 23:41:50 +00001346static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001347 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001349 case Sema::PCC_Namespace:
1350 case Sema::PCC_Class:
1351 case Sema::PCC_ObjCInstanceVariableList:
1352 case Sema::PCC_Template:
1353 case Sema::PCC_MemberTemplate:
1354 case Sema::PCC_Statement:
1355 case Sema::PCC_RecoveryInFunction:
1356 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001357 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001358 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001359 return true;
1360
John McCallf312b1e2010-08-26 23:41:50 +00001361 case Sema::PCC_Expression:
1362 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001363 return LangOpts.CPlusPlus;
1364
1365 case Sema::PCC_ObjCInterface:
1366 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001367 return false;
1368
John McCallf312b1e2010-08-26 23:41:50 +00001369 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001370 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001371 }
David Blaikie7530c032012-01-17 06:56:22 +00001372
1373 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001374}
1375
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001376static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1377 const Preprocessor &PP) {
1378 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregor8ca72082011-10-18 21:20:17 +00001379 Policy.AnonymousTagLocations = false;
1380 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001381 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001382 return Policy;
1383}
1384
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001385/// \brief Retrieve a printing policy suitable for code completion.
1386static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1387 return getCompletionPrintingPolicy(S.Context, S.PP);
1388}
1389
Douglas Gregor8ca72082011-10-18 21:20:17 +00001390/// \brief Retrieve the string representation of the given type as a string
1391/// that has the appropriate lifetime for code completion.
1392///
1393/// This routine provides a fast path where we provide constant strings for
1394/// common type names.
1395static const char *GetCompletionTypeString(QualType T,
1396 ASTContext &Context,
1397 const PrintingPolicy &Policy,
1398 CodeCompletionAllocator &Allocator) {
1399 if (!T.getLocalQualifiers()) {
1400 // Built-in type names are constant strings.
1401 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1402 return BT->getName(Policy);
1403
1404 // Anonymous tag types are constant strings.
1405 if (const TagType *TagT = dyn_cast<TagType>(T))
1406 if (TagDecl *Tag = TagT->getDecl())
1407 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1408 switch (Tag->getTagKind()) {
1409 case TTK_Struct: return "struct <anonymous>";
1410 case TTK_Class: return "class <anonymous>";
1411 case TTK_Union: return "union <anonymous>";
1412 case TTK_Enum: return "enum <anonymous>";
1413 }
1414 }
1415 }
1416
1417 // Slow path: format the type as a string.
1418 std::string Result;
1419 T.getAsStringInternal(Result, Policy);
1420 return Allocator.CopyString(Result);
1421}
1422
Douglas Gregor01dfea02010-01-10 23:08:15 +00001423/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001424static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001425 Scope *S,
1426 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001427 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001428 CodeCompletionAllocator &Allocator = Results.getAllocator();
1429 CodeCompletionBuilder Builder(Allocator);
1430 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001431
John McCall0a2c5e22010-08-25 06:19:51 +00001432 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001433 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001434 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001436 if (Results.includeCodePatterns()) {
1437 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001438 Builder.AddTypedTextChunk("namespace");
1439 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1440 Builder.AddPlaceholderChunk("identifier");
1441 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1442 Builder.AddPlaceholderChunk("declarations");
1443 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1444 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1445 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001446 }
1447
Douglas Gregor01dfea02010-01-10 23:08:15 +00001448 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001449 Builder.AddTypedTextChunk("namespace");
1450 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1451 Builder.AddPlaceholderChunk("name");
1452 Builder.AddChunk(CodeCompletionString::CK_Equal);
1453 Builder.AddPlaceholderChunk("namespace");
1454 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001455
1456 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001457 Builder.AddTypedTextChunk("using");
1458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1459 Builder.AddTextChunk("namespace");
1460 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1461 Builder.AddPlaceholderChunk("identifier");
1462 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463
1464 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001465 Builder.AddTypedTextChunk("asm");
1466 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1467 Builder.AddPlaceholderChunk("string-literal");
1468 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1469 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001470
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001471 if (Results.includeCodePatterns()) {
1472 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001473 Builder.AddTypedTextChunk("template");
1474 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1475 Builder.AddPlaceholderChunk("declaration");
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001477 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001478 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001479
1480 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001481 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001482
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001483 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // Fall through
1485
John McCallf312b1e2010-08-26 23:41:50 +00001486 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001487 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001488 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001489 Builder.AddTypedTextChunk("using");
1490 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1491 Builder.AddPlaceholderChunk("qualifier");
1492 Builder.AddTextChunk("::");
1493 Builder.AddPlaceholderChunk("name");
1494 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001495
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001496 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001497 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001498 Builder.AddTypedTextChunk("using");
1499 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1500 Builder.AddTextChunk("typename");
1501 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1502 Builder.AddPlaceholderChunk("qualifier");
1503 Builder.AddTextChunk("::");
1504 Builder.AddPlaceholderChunk("name");
1505 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001506 }
1507
John McCallf312b1e2010-08-26 23:41:50 +00001508 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001509 AddTypedefResult(Results);
1510
Douglas Gregor01dfea02010-01-10 23:08:15 +00001511 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001512 Builder.AddTypedTextChunk("public");
1513 Builder.AddChunk(CodeCompletionString::CK_Colon);
1514 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001515
1516 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001517 Builder.AddTypedTextChunk("protected");
1518 Builder.AddChunk(CodeCompletionString::CK_Colon);
1519 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001520
1521 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001522 Builder.AddTypedTextChunk("private");
1523 Builder.AddChunk(CodeCompletionString::CK_Colon);
1524 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001525 }
1526 }
1527 // Fall through
1528
John McCallf312b1e2010-08-26 23:41:50 +00001529 case Sema::PCC_Template:
1530 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001531 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001533 Builder.AddTypedTextChunk("template");
1534 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1535 Builder.AddPlaceholderChunk("parameters");
1536 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1537 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001538 }
1539
Douglas Gregorbca403c2010-01-13 23:51:12 +00001540 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1541 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001542 break;
1543
John McCallf312b1e2010-08-26 23:41:50 +00001544 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001545 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1546 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1547 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001548 break;
1549
John McCallf312b1e2010-08-26 23:41:50 +00001550 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001551 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1552 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1553 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001554 break;
1555
John McCallf312b1e2010-08-26 23:41:50 +00001556 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001557 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001558 break;
1559
John McCallf312b1e2010-08-26 23:41:50 +00001560 case Sema::PCC_RecoveryInFunction:
1561 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001562 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001563
Douglas Gregorec3310a2011-04-12 02:47:21 +00001564 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1565 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001566 Builder.AddTypedTextChunk("try");
1567 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1568 Builder.AddPlaceholderChunk("statements");
1569 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1570 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1571 Builder.AddTextChunk("catch");
1572 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1573 Builder.AddPlaceholderChunk("declaration");
1574 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1575 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1576 Builder.AddPlaceholderChunk("statements");
1577 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1578 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1579 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001580 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001581 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001582 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001583
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (Results.includeCodePatterns()) {
1585 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001586 Builder.AddTypedTextChunk("if");
1587 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001588 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001589 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001590 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001591 Builder.AddPlaceholderChunk("expression");
1592 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1593 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1594 Builder.AddPlaceholderChunk("statements");
1595 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1596 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1597 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001598
Douglas Gregord8e8a582010-05-25 21:41:55 +00001599 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001600 Builder.AddTypedTextChunk("switch");
1601 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001602 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001603 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001604 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001605 Builder.AddPlaceholderChunk("expression");
1606 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1607 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1608 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1609 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1610 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001611 }
1612
Douglas Gregor01dfea02010-01-10 23:08:15 +00001613 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001614 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001615 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001616 Builder.AddTypedTextChunk("case");
1617 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1618 Builder.AddPlaceholderChunk("expression");
1619 Builder.AddChunk(CodeCompletionString::CK_Colon);
1620 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001621
1622 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001623 Builder.AddTypedTextChunk("default");
1624 Builder.AddChunk(CodeCompletionString::CK_Colon);
1625 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626 }
1627
Douglas Gregord8e8a582010-05-25 21:41:55 +00001628 if (Results.includeCodePatterns()) {
1629 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001630 Builder.AddTypedTextChunk("while");
1631 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001632 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001633 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001634 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddPlaceholderChunk("expression");
1636 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1637 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1638 Builder.AddPlaceholderChunk("statements");
1639 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1640 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1641 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001642
1643 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001644 Builder.AddTypedTextChunk("do");
1645 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1646 Builder.AddPlaceholderChunk("statements");
1647 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1648 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1649 Builder.AddTextChunk("while");
1650 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1651 Builder.AddPlaceholderChunk("expression");
1652 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1653 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001654
Douglas Gregord8e8a582010-05-25 21:41:55 +00001655 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001656 Builder.AddTypedTextChunk("for");
1657 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001658 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001659 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001660 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001661 Builder.AddPlaceholderChunk("init-expression");
1662 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1663 Builder.AddPlaceholderChunk("condition");
1664 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1665 Builder.AddPlaceholderChunk("inc-expression");
1666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1667 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1668 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1669 Builder.AddPlaceholderChunk("statements");
1670 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1671 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1672 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001673 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001674
1675 if (S->getContinueParent()) {
1676 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001677 Builder.AddTypedTextChunk("continue");
1678 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001679 }
1680
1681 if (S->getBreakParent()) {
1682 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001683 Builder.AddTypedTextChunk("break");
1684 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001685 }
1686
1687 // "return expression ;" or "return ;", depending on whether we
1688 // know the function is void or not.
1689 bool isVoid = false;
1690 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1691 isVoid = Function->getResultType()->isVoidType();
1692 else if (ObjCMethodDecl *Method
1693 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1694 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001695 else if (SemaRef.getCurBlock() &&
1696 !SemaRef.getCurBlock()->ReturnType.isNull())
1697 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001698 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001699 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1701 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001702 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001703 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001704
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001705 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001706 Builder.AddTypedTextChunk("goto");
1707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1708 Builder.AddPlaceholderChunk("label");
1709 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001710
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001711 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001712 Builder.AddTypedTextChunk("using");
1713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1714 Builder.AddTextChunk("namespace");
1715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1716 Builder.AddPlaceholderChunk("identifier");
1717 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001718 }
1719
1720 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001721 case Sema::PCC_ForInit:
1722 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001723 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001724 // Fall through: conditions and statements can have expressions.
1725
Douglas Gregor02688102010-09-14 23:59:36 +00001726 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001727 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1728 CCC == Sema::PCC_ParenthesizedExpression) {
1729 // (__bridge <type>)<expression>
1730 Builder.AddTypedTextChunk("__bridge");
1731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1732 Builder.AddPlaceholderChunk("type");
1733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1734 Builder.AddPlaceholderChunk("expression");
1735 Results.AddResult(Result(Builder.TakeString()));
1736
1737 // (__bridge_transfer <Objective-C type>)<expression>
1738 Builder.AddTypedTextChunk("__bridge_transfer");
1739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1740 Builder.AddPlaceholderChunk("Objective-C type");
1741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1742 Builder.AddPlaceholderChunk("expression");
1743 Results.AddResult(Result(Builder.TakeString()));
1744
1745 // (__bridge_retained <CF type>)<expression>
1746 Builder.AddTypedTextChunk("__bridge_retained");
1747 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1748 Builder.AddPlaceholderChunk("CF type");
1749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1750 Builder.AddPlaceholderChunk("expression");
1751 Results.AddResult(Result(Builder.TakeString()));
1752 }
1753 // Fall through
1754
John McCallf312b1e2010-08-26 23:41:50 +00001755 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001756 if (SemaRef.getLangOptions().CPlusPlus) {
1757 // 'this', if we're in a non-static member function.
Eli Friedman72899c32012-01-07 04:59:52 +00001758 QualType ThisTy = SemaRef.getCurrentThisType();
Douglas Gregor8ca72082011-10-18 21:20:17 +00001759 if (!ThisTy.isNull()) {
1760 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1761 SemaRef.Context,
1762 Policy,
1763 Allocator));
1764 Builder.AddTypedTextChunk("this");
1765 Results.AddResult(Result(Builder.TakeString()));
1766 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001767
Douglas Gregor8ca72082011-10-18 21:20:17 +00001768 // true
1769 Builder.AddResultTypeChunk("bool");
1770 Builder.AddTypedTextChunk("true");
1771 Results.AddResult(Result(Builder.TakeString()));
1772
1773 // false
1774 Builder.AddResultTypeChunk("bool");
1775 Builder.AddTypedTextChunk("false");
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001777
Douglas Gregorec3310a2011-04-12 02:47:21 +00001778 if (SemaRef.getLangOptions().RTTI) {
1779 // dynamic_cast < type-id > ( expression )
1780 Builder.AddTypedTextChunk("dynamic_cast");
1781 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1782 Builder.AddPlaceholderChunk("type");
1783 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1784 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1785 Builder.AddPlaceholderChunk("expression");
1786 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1787 Results.AddResult(Result(Builder.TakeString()));
1788 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001789
1790 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("static_cast");
1792 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1793 Builder.AddPlaceholderChunk("type");
1794 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1796 Builder.AddPlaceholderChunk("expression");
1797 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1798 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001799
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001800 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001801 Builder.AddTypedTextChunk("reinterpret_cast");
1802 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1803 Builder.AddPlaceholderChunk("type");
1804 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1805 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1806 Builder.AddPlaceholderChunk("expression");
1807 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1808 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001809
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001810 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001811 Builder.AddTypedTextChunk("const_cast");
1812 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1813 Builder.AddPlaceholderChunk("type");
1814 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1815 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1816 Builder.AddPlaceholderChunk("expression");
1817 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1818 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001819
Douglas Gregorec3310a2011-04-12 02:47:21 +00001820 if (SemaRef.getLangOptions().RTTI) {
1821 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001822 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001823 Builder.AddTypedTextChunk("typeid");
1824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1825 Builder.AddPlaceholderChunk("expression-or-type");
1826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1827 Results.AddResult(Result(Builder.TakeString()));
1828 }
1829
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001830 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001831 Builder.AddTypedTextChunk("new");
1832 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1833 Builder.AddPlaceholderChunk("type");
1834 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1835 Builder.AddPlaceholderChunk("expressions");
1836 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1837 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001838
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001839 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001840 Builder.AddTypedTextChunk("new");
1841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1842 Builder.AddPlaceholderChunk("type");
1843 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1844 Builder.AddPlaceholderChunk("size");
1845 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1846 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1847 Builder.AddPlaceholderChunk("expressions");
1848 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1849 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001850
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001851 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001852 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001853 Builder.AddTypedTextChunk("delete");
1854 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1855 Builder.AddPlaceholderChunk("expression");
1856 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001857
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001858 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001859 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001860 Builder.AddTypedTextChunk("delete");
1861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1862 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1863 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1864 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1865 Builder.AddPlaceholderChunk("expression");
1866 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001867
Douglas Gregorec3310a2011-04-12 02:47:21 +00001868 if (SemaRef.getLangOptions().CXXExceptions) {
1869 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001870 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001871 Builder.AddTypedTextChunk("throw");
1872 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1873 Builder.AddPlaceholderChunk("expression");
1874 Results.AddResult(Result(Builder.TakeString()));
1875 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001876
Douglas Gregor12e13132010-05-26 22:00:08 +00001877 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001878
1879 if (SemaRef.getLangOptions().CPlusPlus0x) {
1880 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001881 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001882 Builder.AddTypedTextChunk("nullptr");
1883 Results.AddResult(Result(Builder.TakeString()));
1884
1885 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001886 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001887 Builder.AddTypedTextChunk("alignof");
1888 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1889 Builder.AddPlaceholderChunk("type");
1890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1891 Results.AddResult(Result(Builder.TakeString()));
1892
1893 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001894 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001895 Builder.AddTypedTextChunk("noexcept");
1896 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1897 Builder.AddPlaceholderChunk("expression");
1898 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1899 Results.AddResult(Result(Builder.TakeString()));
1900
1901 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001902 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001903 Builder.AddTypedTextChunk("sizeof...");
1904 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1905 Builder.AddPlaceholderChunk("parameter-pack");
1906 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1907 Results.AddResult(Result(Builder.TakeString()));
1908 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001909 }
1910
1911 if (SemaRef.getLangOptions().ObjC1) {
1912 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001913 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1914 // The interface can be NULL.
1915 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001916 if (ID->getSuperClass()) {
1917 std::string SuperType;
1918 SuperType = ID->getSuperClass()->getNameAsString();
1919 if (Method->isInstanceMethod())
1920 SuperType += " *";
1921
1922 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1923 Builder.AddTypedTextChunk("super");
1924 Results.AddResult(Result(Builder.TakeString()));
1925 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001926 }
1927
Douglas Gregorbca403c2010-01-13 23:51:12 +00001928 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001929 }
1930
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001931 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001932 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001933 Builder.AddTypedTextChunk("sizeof");
1934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935 Builder.AddPlaceholderChunk("expression-or-type");
1936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001938 break;
1939 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001940
John McCallf312b1e2010-08-26 23:41:50 +00001941 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001942 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001943 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001944 }
1945
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001946 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1947 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001948
John McCallf312b1e2010-08-26 23:41:50 +00001949 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001950 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001951}
1952
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001953/// \brief If the given declaration has an associated type, add it as a result
1954/// type chunk.
1955static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001956 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001957 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001958 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001959 if (!ND)
1960 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001961
1962 // Skip constructors and conversion functions, which have their return types
1963 // built into their names.
1964 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1965 return;
1966
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001967 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001968 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001969 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1970 T = Function->getResultType();
1971 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1972 T = Method->getResultType();
1973 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1974 T = FunTmpl->getTemplatedDecl()->getResultType();
1975 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1976 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1977 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1978 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001979 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001980 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001981 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001982 T = Property->getType();
1983
1984 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1985 return;
1986
Douglas Gregor8987b232011-09-27 23:30:47 +00001987 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001988 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001989}
1990
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001991static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001992 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001993 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1994 if (Sentinel->getSentinel() == 0) {
1995 if (Context.getLangOptions().ObjC1 &&
1996 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001997 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001998 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001999 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002000 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002001 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002002 }
2003}
2004
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002005static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2006 std::string Result;
2007 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002008 Result += "in ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002009 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002010 Result += "inout ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002011 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002012 Result += "out ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002013 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002014 Result += "bycopy ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002015 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002016 Result += "byref ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002017 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002018 Result += "oneway ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002019 return Result;
2020}
2021
Douglas Gregor83482d12010-08-24 16:15:59 +00002022static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002023 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002024 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002025 bool SuppressName = false,
2026 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002027 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2028 if (Param->getType()->isDependentType() ||
2029 !Param->getType()->isBlockPointerType()) {
2030 // The argument for a dependent or non-block parameter is a placeholder
2031 // containing that parameter's type.
2032 std::string Result;
2033
Douglas Gregoraba48082010-08-29 19:47:46 +00002034 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002035 Result = Param->getIdentifier()->getName();
2036
John McCallf85e1932011-06-15 23:02:42 +00002037 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002038
2039 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002040 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2041 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002042 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002043 Result += Param->getIdentifier()->getName();
2044 }
2045 return Result;
2046 }
2047
2048 // The argument for a block pointer parameter is a block literal with
2049 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002050 FunctionTypeLoc *Block = 0;
2051 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002052 TypeLoc TL;
2053 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2054 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2055 while (true) {
2056 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002057 if (!SuppressBlock) {
2058 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2059 if (TypeSourceInfo *InnerTSInfo
2060 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2061 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2062 continue;
2063 }
2064 }
2065
2066 // Look through qualified types
2067 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2068 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002069 continue;
2070 }
2071 }
2072
Douglas Gregor83482d12010-08-24 16:15:59 +00002073 // Try to get the function prototype behind the block pointer type,
2074 // then we're done.
2075 if (BlockPointerTypeLoc *BlockPtr
2076 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002077 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002078 Block = dyn_cast<FunctionTypeLoc>(&TL);
2079 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002080 }
2081 break;
2082 }
2083 }
2084
2085 if (!Block) {
2086 // We were unable to find a FunctionProtoTypeLoc with parameter names
2087 // for the block; just use the parameter type as a placeholder.
2088 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002089 if (!ObjCMethodParam && Param->getIdentifier())
2090 Result = Param->getIdentifier()->getName();
2091
John McCallf85e1932011-06-15 23:02:42 +00002092 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002093
2094 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002095 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2096 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002097 if (Param->getIdentifier())
2098 Result += Param->getIdentifier()->getName();
2099 }
2100
2101 return Result;
2102 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002103
Douglas Gregor83482d12010-08-24 16:15:59 +00002104 // We have the function prototype behind the block pointer type, as it was
2105 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002106 std::string Result;
2107 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002108 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002109 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002110
2111 // Format the parameter list.
2112 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002113 if (!BlockProto || Block->getNumArgs() == 0) {
2114 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002115 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002116 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002117 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002118 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002119 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002120 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2121 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002122 Params += ", ";
2123 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2124 /*SuppressName=*/false,
2125 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002126
Douglas Gregor830072c2011-02-15 22:37:09 +00002127 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002128 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002129 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002130 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002131 }
Douglas Gregor38276252010-09-08 22:47:51 +00002132
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002133 if (SuppressBlock) {
2134 // Format as a parameter.
2135 Result = Result + " (^";
2136 if (Param->getIdentifier())
2137 Result += Param->getIdentifier()->getName();
2138 Result += ")";
2139 Result += Params;
2140 } else {
2141 // Format as a block literal argument.
2142 Result = '^' + Result;
2143 Result += Params;
2144
2145 if (Param->getIdentifier())
2146 Result += Param->getIdentifier()->getName();
2147 }
2148
Douglas Gregor83482d12010-08-24 16:15:59 +00002149 return Result;
2150}
2151
Douglas Gregor86d9a522009-09-21 16:56:56 +00002152/// \brief Add function parameter chunks to the given code completion string.
2153static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002154 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002155 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002156 CodeCompletionBuilder &Result,
2157 unsigned Start = 0,
2158 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002159 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002160 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002161
Douglas Gregor218937c2011-02-01 19:23:04 +00002162 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002163 ParmVarDecl *Param = Function->getParamDecl(P);
2164
Douglas Gregor218937c2011-02-01 19:23:04 +00002165 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166 // When we see an optional default argument, put that argument and
2167 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002168 CodeCompletionBuilder Opt(Result.getAllocator());
2169 if (!FirstParameter)
2170 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002171 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002172 Result.AddOptionalChunk(Opt.TakeString());
2173 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002174 }
2175
Douglas Gregor218937c2011-02-01 19:23:04 +00002176 if (FirstParameter)
2177 FirstParameter = false;
2178 else
2179 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2180
2181 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002182
2183 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002184 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2185 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002186
Douglas Gregore17794f2010-08-31 05:13:43 +00002187 if (Function->isVariadic() && P == N - 1)
2188 PlaceholderStr += ", ...";
2189
Douglas Gregor86d9a522009-09-21 16:56:56 +00002190 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002191 Result.AddPlaceholderChunk(
2192 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002193 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002194
2195 if (const FunctionProtoType *Proto
2196 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002197 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002198 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002199 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002200
Douglas Gregor218937c2011-02-01 19:23:04 +00002201 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002202 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002203}
2204
2205/// \brief Add template parameter chunks to the given code completion string.
2206static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002207 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002208 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002209 CodeCompletionBuilder &Result,
2210 unsigned MaxParameters = 0,
2211 unsigned Start = 0,
2212 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002213 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002214 bool FirstParameter = true;
2215
2216 TemplateParameterList *Params = Template->getTemplateParameters();
2217 TemplateParameterList::iterator PEnd = Params->end();
2218 if (MaxParameters)
2219 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002220 for (TemplateParameterList::iterator P = Params->begin() + Start;
2221 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002222 bool HasDefaultArg = false;
2223 std::string PlaceholderStr;
2224 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2225 if (TTP->wasDeclaredWithTypename())
2226 PlaceholderStr = "typename";
2227 else
2228 PlaceholderStr = "class";
2229
2230 if (TTP->getIdentifier()) {
2231 PlaceholderStr += ' ';
2232 PlaceholderStr += TTP->getIdentifier()->getName();
2233 }
2234
2235 HasDefaultArg = TTP->hasDefaultArgument();
2236 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002237 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002238 if (NTTP->getIdentifier())
2239 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002240 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002241 HasDefaultArg = NTTP->hasDefaultArgument();
2242 } else {
2243 assert(isa<TemplateTemplateParmDecl>(*P));
2244 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2245
2246 // Since putting the template argument list into the placeholder would
2247 // be very, very long, we just use an abbreviation.
2248 PlaceholderStr = "template<...> class";
2249 if (TTP->getIdentifier()) {
2250 PlaceholderStr += ' ';
2251 PlaceholderStr += TTP->getIdentifier()->getName();
2252 }
2253
2254 HasDefaultArg = TTP->hasDefaultArgument();
2255 }
2256
Douglas Gregor218937c2011-02-01 19:23:04 +00002257 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002258 // When we see an optional default argument, put that argument and
2259 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002260 CodeCompletionBuilder Opt(Result.getAllocator());
2261 if (!FirstParameter)
2262 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002263 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002264 P - Params->begin(), true);
2265 Result.AddOptionalChunk(Opt.TakeString());
2266 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002267 }
2268
Douglas Gregor218937c2011-02-01 19:23:04 +00002269 InDefaultArg = false;
2270
Douglas Gregor86d9a522009-09-21 16:56:56 +00002271 if (FirstParameter)
2272 FirstParameter = false;
2273 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002274 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002275
2276 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002277 Result.AddPlaceholderChunk(
2278 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002279 }
2280}
2281
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002282/// \brief Add a qualifier to the given code-completion string, if the
2283/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002284static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002285AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002286 NestedNameSpecifier *Qualifier,
2287 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002288 ASTContext &Context,
2289 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002290 if (!Qualifier)
2291 return;
2292
2293 std::string PrintedNNS;
2294 {
2295 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002296 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002297 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002298 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002299 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002300 else
Douglas Gregordae68752011-02-01 22:57:45 +00002301 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002302}
2303
Douglas Gregor218937c2011-02-01 19:23:04 +00002304static void
2305AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2306 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002307 const FunctionProtoType *Proto
2308 = Function->getType()->getAs<FunctionProtoType>();
2309 if (!Proto || !Proto->getTypeQuals())
2310 return;
2311
Douglas Gregora63f6de2011-02-01 21:15:40 +00002312 // FIXME: Add ref-qualifier!
2313
2314 // Handle single qualifiers without copying
2315 if (Proto->getTypeQuals() == Qualifiers::Const) {
2316 Result.AddInformativeChunk(" const");
2317 return;
2318 }
2319
2320 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2321 Result.AddInformativeChunk(" volatile");
2322 return;
2323 }
2324
2325 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2326 Result.AddInformativeChunk(" restrict");
2327 return;
2328 }
2329
2330 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002331 std::string QualsStr;
2332 if (Proto->getTypeQuals() & Qualifiers::Const)
2333 QualsStr += " const";
2334 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2335 QualsStr += " volatile";
2336 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2337 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002338 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002339}
2340
Douglas Gregor6f942b22010-09-21 16:06:22 +00002341/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002342static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2343 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002344 typedef CodeCompletionString::Chunk Chunk;
2345
2346 DeclarationName Name = ND->getDeclName();
2347 if (!Name)
2348 return;
2349
2350 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002351 case DeclarationName::CXXOperatorName: {
2352 const char *OperatorName = 0;
2353 switch (Name.getCXXOverloadedOperator()) {
2354 case OO_None:
2355 case OO_Conditional:
2356 case NUM_OVERLOADED_OPERATORS:
2357 OperatorName = "operator";
2358 break;
2359
2360#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2361 case OO_##Name: OperatorName = "operator" Spelling; break;
2362#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2363#include "clang/Basic/OperatorKinds.def"
2364
2365 case OO_New: OperatorName = "operator new"; break;
2366 case OO_Delete: OperatorName = "operator delete"; break;
2367 case OO_Array_New: OperatorName = "operator new[]"; break;
2368 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2369 case OO_Call: OperatorName = "operator()"; break;
2370 case OO_Subscript: OperatorName = "operator[]"; break;
2371 }
2372 Result.AddTypedTextChunk(OperatorName);
2373 break;
2374 }
2375
Douglas Gregor6f942b22010-09-21 16:06:22 +00002376 case DeclarationName::Identifier:
2377 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002378 case DeclarationName::CXXDestructorName:
2379 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002382 break;
2383
2384 case DeclarationName::CXXUsingDirective:
2385 case DeclarationName::ObjCZeroArgSelector:
2386 case DeclarationName::ObjCOneArgSelector:
2387 case DeclarationName::ObjCMultiArgSelector:
2388 break;
2389
2390 case DeclarationName::CXXConstructorName: {
2391 CXXRecordDecl *Record = 0;
2392 QualType Ty = Name.getCXXNameType();
2393 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2394 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2395 else if (const InjectedClassNameType *InjectedTy
2396 = Ty->getAs<InjectedClassNameType>())
2397 Record = InjectedTy->getDecl();
2398 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002399 Result.AddTypedTextChunk(
2400 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002401 break;
2402 }
2403
Douglas Gregordae68752011-02-01 22:57:45 +00002404 Result.AddTypedTextChunk(
2405 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002406 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002407 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002408 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002409 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002410 }
2411 break;
2412 }
2413 }
2414}
2415
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002416CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2417 CodeCompletionAllocator &Allocator) {
2418 return CreateCodeCompletionString(S.Context, S.PP, Allocator);
2419}
2420
Douglas Gregor86d9a522009-09-21 16:56:56 +00002421/// \brief If possible, create a new code completion string for the given
2422/// result.
2423///
2424/// \returns Either a new, heap-allocated code completion string describing
2425/// how to use this result, or NULL to indicate that the string or name of the
2426/// result is all that is needed.
2427CodeCompletionString *
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002428CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2429 Preprocessor &PP,
Douglas Gregordae68752011-02-01 22:57:45 +00002430 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002431 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002432 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002433
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002434 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregor218937c2011-02-01 19:23:04 +00002435 if (Kind == RK_Pattern) {
2436 Pattern->Priority = Priority;
2437 Pattern->Availability = Availability;
2438 return Pattern;
2439 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002440
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002441 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002442 Result.AddTypedTextChunk(Keyword);
2443 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002444 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002445
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002446 if (Kind == RK_Macro) {
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002447 MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002448 assert(MI && "Not a macro?");
2449
Douglas Gregordae68752011-02-01 22:57:45 +00002450 Result.AddTypedTextChunk(
2451 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002452
2453 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002454 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002455
2456 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002457 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002458 bool CombineVariadicArgument = false;
2459 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2460 if (MI->isVariadic() && AEnd - A > 1) {
2461 AEnd -= 2;
2462 CombineVariadicArgument = true;
2463 }
2464 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002465 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002466 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002467
Douglas Gregore4244702011-07-30 08:17:44 +00002468 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002469 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002470 Result.AddPlaceholderChunk(
2471 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002472 continue;
2473 }
2474
Douglas Gregore4244702011-07-30 08:17:44 +00002475 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002476 // variadic macros, providing a single placeholder for the rest of the
2477 // arguments.
2478 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002479 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002480 else {
2481 std::string Arg = (*A)->getName();
2482 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002483 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002484 }
2485 }
Douglas Gregore4244702011-07-30 08:17:44 +00002486
2487 if (CombineVariadicArgument) {
2488 // Handle the next-to-last argument, combining it with the variadic
2489 // argument.
2490 std::string LastArg = (*A)->getName();
2491 ++A;
2492 if ((*A)->isStr("__VA_ARGS__"))
2493 LastArg += ", ...";
2494 else
2495 LastArg += ", " + (*A)->getName().str() + "...";
2496 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2497 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002498 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2499 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002500 }
2501
Douglas Gregord8e8a582010-05-25 21:41:55 +00002502 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002503 NamedDecl *ND = Declaration;
2504
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002505 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002506 Result.AddTypedTextChunk(
2507 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002508 Result.AddTextChunk("::");
2509 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002510 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002511
2512 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2513 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2514 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2515 }
2516 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002517
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002518 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002519
Douglas Gregor86d9a522009-09-21 16:56:56 +00002520 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002521 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002522 Ctx, Policy);
2523 AddTypedNameChunk(Ctx, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002524 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002525 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002526 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002527 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002528 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002529 }
2530
2531 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002532 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002533 Ctx, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002534 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002535 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002536
Douglas Gregor86d9a522009-09-21 16:56:56 +00002537 // Figure out which template parameters are deduced (or have default
2538 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002539 SmallVector<bool, 16> Deduced;
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002540 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002541 unsigned LastDeducibleArgument;
2542 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2543 --LastDeducibleArgument) {
2544 if (!Deduced[LastDeducibleArgument - 1]) {
2545 // C++0x: Figure out if the template argument has a default. If so,
2546 // the user doesn't need to type this argument.
2547 // FIXME: We need to abstract template parameters better!
2548 bool HasDefaultArg = false;
2549 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002550 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002551 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2552 HasDefaultArg = TTP->hasDefaultArgument();
2553 else if (NonTypeTemplateParmDecl *NTTP
2554 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2555 HasDefaultArg = NTTP->hasDefaultArgument();
2556 else {
2557 assert(isa<TemplateTemplateParmDecl>(Param));
2558 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002559 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002560 }
2561
2562 if (!HasDefaultArg)
2563 break;
2564 }
2565 }
2566
2567 if (LastDeducibleArgument) {
2568 // Some of the function template arguments cannot be deduced from a
2569 // function call, so we introduce an explicit template argument list
2570 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002571 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002572 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002573 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002574 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002575 }
2576
2577 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002578 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002579 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002580 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002581 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002582 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002583 }
2584
2585 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002586 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002587 Ctx, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002588 Result.AddTypedTextChunk(
2589 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002590 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002591 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002592 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2593 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002594 }
2595
Douglas Gregor9630eb62009-11-17 16:44:22 +00002596 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002597 Selector Sel = Method->getSelector();
2598 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002599 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002600 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002601 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002602 }
2603
Douglas Gregor813d8342011-02-18 22:29:55 +00002604 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002605 SelName += ':';
2606 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002607 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002608 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002609 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002610
2611 // If there is only one parameter, and we're past it, add an empty
2612 // typed-text chunk since there is nothing to type.
2613 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002614 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002615 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002616 unsigned Idx = 0;
2617 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2618 PEnd = Method->param_end();
2619 P != PEnd; (void)++P, ++Idx) {
2620 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002621 std::string Keyword;
2622 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002623 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002624 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002625 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002626 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002627 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002628 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002629 else
Douglas Gregordae68752011-02-01 22:57:45 +00002630 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002631 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002632
2633 // If we're before the starting parameter, skip the placeholder.
2634 if (Idx < StartParameter)
2635 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002636
2637 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002638
2639 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002640 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002641 else {
John McCallf85e1932011-06-15 23:02:42 +00002642 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002643 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2644 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002645 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002646 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002647 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002648 }
2649
Douglas Gregore17794f2010-08-31 05:13:43 +00002650 if (Method->isVariadic() && (P + 1) == PEnd)
2651 Arg += ", ...";
2652
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002653 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002654 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002655 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002656 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002657 else
Douglas Gregordae68752011-02-01 22:57:45 +00002658 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002659 }
2660
Douglas Gregor2a17af02009-12-23 00:21:46 +00002661 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002662 if (Method->param_size() == 0) {
2663 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002664 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002665 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002666 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002667 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002668 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002669 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002670
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002671 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002672 }
2673
Douglas Gregor218937c2011-02-01 19:23:04 +00002674 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002675 }
2676
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002677 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002678 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002679 Ctx, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002680
Douglas Gregordae68752011-02-01 22:57:45 +00002681 Result.AddTypedTextChunk(
2682 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002683 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002684}
2685
Douglas Gregor86d802e2009-09-23 00:34:09 +00002686CodeCompletionString *
2687CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2688 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002689 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002690 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002691 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002692 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002693
Douglas Gregor218937c2011-02-01 19:23:04 +00002694 // FIXME: Set priority, availability appropriately.
2695 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002696 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002697 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002698 const FunctionProtoType *Proto
2699 = dyn_cast<FunctionProtoType>(getFunctionType());
2700 if (!FDecl && !Proto) {
2701 // Function without a prototype. Just give the return type and a
2702 // highlighted ellipsis.
2703 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002704 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002705 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002706 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002707 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2708 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2709 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2710 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002711 }
2712
2713 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002714 Result.AddTextChunk(
2715 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002716 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002717 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002718 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002719 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002720
Douglas Gregor218937c2011-02-01 19:23:04 +00002721 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002722 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2723 for (unsigned I = 0; I != NumParams; ++I) {
2724 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002725 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002726
2727 std::string ArgString;
2728 QualType ArgType;
2729
2730 if (FDecl) {
2731 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2732 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2733 } else {
2734 ArgType = Proto->getArgType(I);
2735 }
2736
John McCallf85e1932011-06-15 23:02:42 +00002737 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002738
2739 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002740 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002741 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002742 else
Douglas Gregordae68752011-02-01 22:57:45 +00002743 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002744 }
2745
2746 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002747 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002748 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002749 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002750 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002751 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002752 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002753 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002754
Douglas Gregor218937c2011-02-01 19:23:04 +00002755 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002756}
2757
Chris Lattner5f9e2722011-07-23 10:55:15 +00002758unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002759 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002760 bool PreferredTypeIsPointer) {
2761 unsigned Priority = CCP_Macro;
2762
Douglas Gregorb05496d2010-09-20 21:11:48 +00002763 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2764 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2765 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002766 Priority = CCP_Constant;
2767 if (PreferredTypeIsPointer)
2768 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002769 }
2770 // Treat "YES", "NO", "true", and "false" as constants.
2771 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2772 MacroName.equals("true") || MacroName.equals("false"))
2773 Priority = CCP_Constant;
2774 // Treat "bool" as a type.
2775 else if (MacroName.equals("bool"))
2776 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2777
Douglas Gregor1827e102010-08-16 16:18:59 +00002778
2779 return Priority;
2780}
2781
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002782CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2783 if (!D)
2784 return CXCursor_UnexposedDecl;
2785
2786 switch (D->getKind()) {
2787 case Decl::Enum: return CXCursor_EnumDecl;
2788 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2789 case Decl::Field: return CXCursor_FieldDecl;
2790 case Decl::Function:
2791 return CXCursor_FunctionDecl;
2792 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2793 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002794 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregor375bb142011-12-27 22:43:10 +00002795
2796 case Decl::ObjCInterface:
2797 if (cast<ObjCInterfaceDecl>(D)->isThisDeclarationADefinition())
2798 return CXCursor_ObjCInterfaceDecl;
2799
2800 // Forward declarations are not directly exposed.
2801 return CXCursor_UnexposedDecl;
2802
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002803 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2804 case Decl::ObjCMethod:
2805 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2806 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2807 case Decl::CXXMethod: return CXCursor_CXXMethod;
2808 case Decl::CXXConstructor: return CXCursor_Constructor;
2809 case Decl::CXXDestructor: return CXCursor_Destructor;
2810 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2811 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002812 case Decl::ObjCProtocol:
2813 if (cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition())
2814 return CXCursor_ObjCProtocolDecl;
2815
2816 return CXCursor_UnexposedDecl;
2817
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002818 case Decl::ParmVar: return CXCursor_ParmDecl;
2819 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002820 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002821 case Decl::Var: return CXCursor_VarDecl;
2822 case Decl::Namespace: return CXCursor_Namespace;
2823 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2824 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2825 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2826 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2827 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2828 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002829 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002830 case Decl::ClassTemplatePartialSpecialization:
2831 return CXCursor_ClassTemplatePartialSpecialization;
2832 case Decl::UsingDirective: return CXCursor_UsingDirective;
2833
2834 case Decl::Using:
2835 case Decl::UnresolvedUsingValue:
2836 case Decl::UnresolvedUsingTypename:
2837 return CXCursor_UsingDeclaration;
2838
Douglas Gregor352697a2011-06-03 23:08:58 +00002839 case Decl::ObjCPropertyImpl:
2840 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2841 case ObjCPropertyImplDecl::Dynamic:
2842 return CXCursor_ObjCDynamicDecl;
2843
2844 case ObjCPropertyImplDecl::Synthesize:
2845 return CXCursor_ObjCSynthesizeDecl;
2846 }
Douglas Gregor352697a2011-06-03 23:08:58 +00002847
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002848 default:
2849 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2850 switch (TD->getTagKind()) {
2851 case TTK_Struct: return CXCursor_StructDecl;
2852 case TTK_Class: return CXCursor_ClassDecl;
2853 case TTK_Union: return CXCursor_UnionDecl;
2854 case TTK_Enum: return CXCursor_EnumDecl;
2855 }
2856 }
2857 }
2858
2859 return CXCursor_UnexposedDecl;
2860}
2861
Douglas Gregor590c7d52010-07-08 20:55:51 +00002862static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2863 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002864 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002865
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002866 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002867
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002868 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2869 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002870 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002871 Results.AddResult(Result(M->first,
2872 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002873 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002874 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002875 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002876
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002877 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002878
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002879}
2880
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002881static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2882 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002883 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002884
2885 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002886
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002887 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2888 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2889 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2890 Results.AddResult(Result("__func__", CCP_Constant));
2891 Results.ExitScope();
2892}
2893
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002894static void HandleCodeCompleteResults(Sema *S,
2895 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002896 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002897 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002898 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002899 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002900 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002901}
2902
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002903static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2904 Sema::ParserCompletionContext PCC) {
2905 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002906 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002907 return CodeCompletionContext::CCC_TopLevel;
2908
John McCallf312b1e2010-08-26 23:41:50 +00002909 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002910 return CodeCompletionContext::CCC_ClassStructUnion;
2911
John McCallf312b1e2010-08-26 23:41:50 +00002912 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002913 return CodeCompletionContext::CCC_ObjCInterface;
2914
John McCallf312b1e2010-08-26 23:41:50 +00002915 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002916 return CodeCompletionContext::CCC_ObjCImplementation;
2917
John McCallf312b1e2010-08-26 23:41:50 +00002918 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002919 return CodeCompletionContext::CCC_ObjCIvarList;
2920
John McCallf312b1e2010-08-26 23:41:50 +00002921 case Sema::PCC_Template:
2922 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002923 if (S.CurContext->isFileContext())
2924 return CodeCompletionContext::CCC_TopLevel;
David Blaikie7530c032012-01-17 06:56:22 +00002925 if (S.CurContext->isRecord())
Douglas Gregor52779fb2010-09-23 23:01:17 +00002926 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie7530c032012-01-17 06:56:22 +00002927 return CodeCompletionContext::CCC_Other;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002928
John McCallf312b1e2010-08-26 23:41:50 +00002929 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002930 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002931
John McCallf312b1e2010-08-26 23:41:50 +00002932 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002933 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2934 S.getLangOptions().ObjC1)
2935 return CodeCompletionContext::CCC_ParenthesizedExpression;
2936 else
2937 return CodeCompletionContext::CCC_Expression;
2938
2939 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002940 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002941 return CodeCompletionContext::CCC_Expression;
2942
John McCallf312b1e2010-08-26 23:41:50 +00002943 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002944 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002945
John McCallf312b1e2010-08-26 23:41:50 +00002946 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002947 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002948
2949 case Sema::PCC_ParenthesizedExpression:
2950 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002951
2952 case Sema::PCC_LocalDeclarationSpecifiers:
2953 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002954 }
David Blaikie7530c032012-01-17 06:56:22 +00002955
2956 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002957}
2958
Douglas Gregorf6961522010-08-27 21:18:54 +00002959/// \brief If we're in a C++ virtual member function, add completion results
2960/// that invoke the functions we override, since it's common to invoke the
2961/// overridden function as well as adding new functionality.
2962///
2963/// \param S The semantic analysis object for which we are generating results.
2964///
2965/// \param InContext This context in which the nested-name-specifier preceding
2966/// the code-completion point
2967static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2968 ResultBuilder &Results) {
2969 // Look through blocks.
2970 DeclContext *CurContext = S.CurContext;
2971 while (isa<BlockDecl>(CurContext))
2972 CurContext = CurContext->getParent();
2973
2974
2975 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2976 if (!Method || !Method->isVirtual())
2977 return;
2978
2979 // We need to have names for all of the parameters, if we're going to
2980 // generate a forwarding call.
2981 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2982 PEnd = Method->param_end();
2983 P != PEnd;
2984 ++P) {
2985 if (!(*P)->getDeclName())
2986 return;
2987 }
2988
Douglas Gregor8987b232011-09-27 23:30:47 +00002989 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002990 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2991 MEnd = Method->end_overridden_methods();
2992 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002993 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002994 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2995 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2996 continue;
2997
2998 // If we need a nested-name-specifier, add one now.
2999 if (!InContext) {
3000 NestedNameSpecifier *NNS
3001 = getRequiredQualification(S.Context, CurContext,
3002 Overridden->getDeclContext());
3003 if (NNS) {
3004 std::string Str;
3005 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00003006 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003007 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003008 }
3009 } else if (!InContext->Equals(Overridden->getDeclContext()))
3010 continue;
3011
Douglas Gregordae68752011-02-01 22:57:45 +00003012 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003013 Overridden->getNameAsString()));
3014 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003015 bool FirstParam = true;
3016 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3017 PEnd = Method->param_end();
3018 P != PEnd; ++P) {
3019 if (FirstParam)
3020 FirstParam = false;
3021 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003022 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003023
Douglas Gregordae68752011-02-01 22:57:45 +00003024 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003025 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003026 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003027 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3028 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003029 CCP_SuperCompletion,
3030 CXCursor_CXXMethod));
3031 Results.Ignore(Overridden);
3032 }
3033}
3034
Douglas Gregor01dfea02010-01-10 23:08:15 +00003035void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003036 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003037 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003038 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003039 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003040 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003041
Douglas Gregor01dfea02010-01-10 23:08:15 +00003042 // Determine how to filter results, e.g., so that the names of
3043 // values (functions, enumerators, function templates, etc.) are
3044 // only allowed where we can have an expression.
3045 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003046 case PCC_Namespace:
3047 case PCC_Class:
3048 case PCC_ObjCInterface:
3049 case PCC_ObjCImplementation:
3050 case PCC_ObjCInstanceVariableList:
3051 case PCC_Template:
3052 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003053 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003054 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003055 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3056 break;
3057
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003058 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003059 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003060 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003061 case PCC_ForInit:
3062 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003063 if (WantTypesInContext(CompletionContext, getLangOptions()))
3064 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3065 else
3066 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003067
3068 if (getLangOptions().CPlusPlus)
3069 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003070 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003071
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003072 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003073 // Unfiltered
3074 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003075 }
3076
Douglas Gregor3cdee122010-08-26 16:36:48 +00003077 // If we are in a C++ non-static member function, check the qualifiers on
3078 // the member function to filter/prioritize the results list.
3079 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3080 if (CurMethod->isInstance())
3081 Results.setObjectTypeQualifiers(
3082 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3083
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003084 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003085 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3086 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003087
Douglas Gregorbca403c2010-01-13 23:51:12 +00003088 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003089 Results.ExitScope();
3090
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003091 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003092 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003093 case PCC_Expression:
3094 case PCC_Statement:
3095 case PCC_RecoveryInFunction:
3096 if (S->getFnParent())
3097 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3098 break;
3099
3100 case PCC_Namespace:
3101 case PCC_Class:
3102 case PCC_ObjCInterface:
3103 case PCC_ObjCImplementation:
3104 case PCC_ObjCInstanceVariableList:
3105 case PCC_Template:
3106 case PCC_MemberTemplate:
3107 case PCC_ForInit:
3108 case PCC_Condition:
3109 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003110 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003111 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003112 }
3113
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003114 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003115 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003116
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003117 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003118 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003119}
3120
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003121static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3122 ParsedType Receiver,
3123 IdentifierInfo **SelIdents,
3124 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003125 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003126 bool IsSuper,
3127 ResultBuilder &Results);
3128
3129void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3130 bool AllowNonIdentifiers,
3131 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003132 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003133 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003134 AllowNestedNameSpecifiers
3135 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3136 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003137 Results.EnterNewScope();
3138
3139 // Type qualifiers can come after names.
3140 Results.AddResult(Result("const"));
3141 Results.AddResult(Result("volatile"));
3142 if (getLangOptions().C99)
3143 Results.AddResult(Result("restrict"));
3144
3145 if (getLangOptions().CPlusPlus) {
3146 if (AllowNonIdentifiers) {
3147 Results.AddResult(Result("operator"));
3148 }
3149
3150 // Add nested-name-specifiers.
3151 if (AllowNestedNameSpecifiers) {
3152 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003153 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003154 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3155 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3156 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003157 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003158 }
3159 }
3160 Results.ExitScope();
3161
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003162 // If we're in a context where we might have an expression (rather than a
3163 // declaration), and what we've seen so far is an Objective-C type that could
3164 // be a receiver of a class message, this may be a class message send with
3165 // the initial opening bracket '[' missing. Add appropriate completions.
3166 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3167 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3168 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3169 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3170 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3171 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3172 DS.getTypeQualifiers() == 0 &&
3173 S &&
3174 (S->getFlags() & Scope::DeclScope) != 0 &&
3175 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3176 Scope::FunctionPrototypeScope |
3177 Scope::AtCatchScope)) == 0) {
3178 ParsedType T = DS.getRepAsType();
3179 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003180 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003181 }
3182
Douglas Gregor4497dd42010-08-24 04:59:56 +00003183 // Note that we intentionally suppress macro results here, since we do not
3184 // encourage using macros to produce the names of entities.
3185
Douglas Gregor52779fb2010-09-23 23:01:17 +00003186 HandleCodeCompleteResults(this, CodeCompleter,
3187 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003188 Results.data(), Results.size());
3189}
3190
Douglas Gregorfb629412010-08-23 21:17:50 +00003191struct Sema::CodeCompleteExpressionData {
3192 CodeCompleteExpressionData(QualType PreferredType = QualType())
3193 : PreferredType(PreferredType), IntegralConstantExpression(false),
3194 ObjCCollection(false) { }
3195
3196 QualType PreferredType;
3197 bool IntegralConstantExpression;
3198 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003199 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003200};
3201
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003202/// \brief Perform code-completion in an expression context when we know what
3203/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003204///
3205/// \param IntegralConstantExpression Only permit integral constant
3206/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003207void Sema::CodeCompleteExpression(Scope *S,
3208 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003209 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003210 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3211 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003212 if (Data.ObjCCollection)
3213 Results.setFilter(&ResultBuilder::IsObjCCollection);
3214 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003215 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003216 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003217 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3218 else
3219 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003220
3221 if (!Data.PreferredType.isNull())
3222 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3223
3224 // Ignore any declarations that we were told that we don't care about.
3225 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3226 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003227
3228 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003229 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3230 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003231
3232 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003233 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003234 Results.ExitScope();
3235
Douglas Gregor590c7d52010-07-08 20:55:51 +00003236 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003237 if (!Data.PreferredType.isNull())
3238 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3239 || Data.PreferredType->isMemberPointerType()
3240 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003241
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003242 if (S->getFnParent() &&
3243 !Data.ObjCCollection &&
3244 !Data.IntegralConstantExpression)
3245 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3246
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003247 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003248 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003249 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003250 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3251 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003252 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003253}
3254
Douglas Gregorac5fd842010-09-18 01:28:11 +00003255void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3256 if (E.isInvalid())
3257 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3258 else if (getLangOptions().ObjC1)
3259 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003260}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003261
Douglas Gregor73449212010-12-09 23:01:55 +00003262/// \brief The set of properties that have already been added, referenced by
3263/// property name.
3264typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3265
Douglas Gregor95ac6552009-11-18 01:29:26 +00003266static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003267 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003268 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003269 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003270 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003271 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003272 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003273
3274 // Add properties in this container.
3275 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3276 PEnd = Container->prop_end();
3277 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003278 ++P) {
3279 if (AddedProperties.insert(P->getIdentifier()))
3280 Results.MaybeAddResult(Result(*P, 0), CurContext);
3281 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003282
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003283 // Add nullary methods
3284 if (AllowNullaryMethods) {
3285 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003286 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003287 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3288 MEnd = Container->meth_end();
3289 M != MEnd; ++M) {
3290 if (M->getSelector().isUnarySelector())
3291 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3292 if (AddedProperties.insert(Name)) {
3293 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003294 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003295 Builder.AddTypedTextChunk(
3296 Results.getAllocator().CopyString(Name->getName()));
3297
3298 CXAvailabilityKind Availability = CXAvailability_Available;
3299 switch (M->getAvailability()) {
3300 case AR_Available:
3301 case AR_NotYetIntroduced:
3302 Availability = CXAvailability_Available;
3303 break;
3304
3305 case AR_Deprecated:
3306 Availability = CXAvailability_Deprecated;
3307 break;
3308
3309 case AR_Unavailable:
3310 Availability = CXAvailability_NotAvailable;
3311 break;
3312 }
3313
3314 Results.MaybeAddResult(Result(Builder.TakeString(),
3315 CCP_MemberDeclaration + CCD_MethodAsProperty,
3316 M->isInstanceMethod()
3317 ? CXCursor_ObjCInstanceMethodDecl
3318 : CXCursor_ObjCClassMethodDecl,
3319 Availability),
3320 CurContext);
3321 }
3322 }
3323 }
3324
3325
Douglas Gregor95ac6552009-11-18 01:29:26 +00003326 // Add properties in referenced protocols.
3327 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3328 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3329 PEnd = Protocol->protocol_end();
3330 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003331 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3332 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003333 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003334 if (AllowCategories) {
3335 // Look through categories.
3336 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3337 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003338 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3339 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003340 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003341
3342 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003343 for (ObjCInterfaceDecl::all_protocol_iterator
3344 I = IFace->all_referenced_protocol_begin(),
3345 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003346 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3347 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003348
3349 // Look in the superclass.
3350 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003351 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3352 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003353 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003354 } else if (const ObjCCategoryDecl *Category
3355 = dyn_cast<ObjCCategoryDecl>(Container)) {
3356 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003357 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3358 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003359 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003360 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3361 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003362 }
3363}
3364
Richard Trieuf81e5a92011-09-09 02:00:50 +00003365void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003366 SourceLocation OpLoc,
3367 bool IsArrow) {
3368 if (!BaseE || !CodeCompleter)
3369 return;
3370
John McCall0a2c5e22010-08-25 06:19:51 +00003371 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003372
Douglas Gregor81b747b2009-09-17 21:32:03 +00003373 Expr *Base = static_cast<Expr *>(BaseE);
3374 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003375
3376 if (IsArrow) {
3377 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3378 BaseType = Ptr->getPointeeType();
3379 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003380 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003381 else
3382 return;
3383 }
3384
Douglas Gregor3da626b2011-07-07 16:03:39 +00003385 enum CodeCompletionContext::Kind contextKind;
3386
3387 if (IsArrow) {
3388 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3389 }
3390 else {
3391 if (BaseType->isObjCObjectPointerType() ||
3392 BaseType->isObjCObjectOrInterfaceType()) {
3393 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3394 }
3395 else {
3396 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3397 }
3398 }
3399
Douglas Gregor218937c2011-02-01 19:23:04 +00003400 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003401 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003402 BaseType),
3403 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003404 Results.EnterNewScope();
3405 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003406 // Indicate that we are performing a member access, and the cv-qualifiers
3407 // for the base object type.
3408 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3409
Douglas Gregor95ac6552009-11-18 01:29:26 +00003410 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003411 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003412 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003413 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3414 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003415
Douglas Gregor95ac6552009-11-18 01:29:26 +00003416 if (getLangOptions().CPlusPlus) {
3417 if (!Results.empty()) {
3418 // The "template" keyword can follow "->" or "." in the grammar.
3419 // However, we only want to suggest the template keyword if something
3420 // is dependent.
3421 bool IsDependent = BaseType->isDependentType();
3422 if (!IsDependent) {
3423 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3424 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3425 IsDependent = Ctx->isDependentContext();
3426 break;
3427 }
3428 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003429
Douglas Gregor95ac6552009-11-18 01:29:26 +00003430 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003431 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003432 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003433 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003434 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3435 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003436 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003437
3438 // Add property results based on our interface.
3439 const ObjCObjectPointerType *ObjCPtr
3440 = BaseType->getAsObjCInterfacePointerType();
3441 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003442 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3443 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003444 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003445
3446 // Add properties from the protocols in a qualified interface.
3447 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3448 E = ObjCPtr->qual_end();
3449 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003450 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3451 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003452 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003453 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003454 // Objective-C instance variable access.
3455 ObjCInterfaceDecl *Class = 0;
3456 if (const ObjCObjectPointerType *ObjCPtr
3457 = BaseType->getAs<ObjCObjectPointerType>())
3458 Class = ObjCPtr->getInterfaceDecl();
3459 else
John McCallc12c5bb2010-05-15 11:32:37 +00003460 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003461
3462 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003463 if (Class) {
3464 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3465 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003466 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3467 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003468 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003469 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003470
3471 // FIXME: How do we cope with isa?
3472
3473 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003474
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003475 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003476 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003477 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003478 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003479}
3480
Douglas Gregor374929f2009-09-18 15:37:17 +00003481void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3482 if (!CodeCompleter)
3483 return;
3484
John McCall0a2c5e22010-08-25 06:19:51 +00003485 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003486 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003487 enum CodeCompletionContext::Kind ContextKind
3488 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003489 switch ((DeclSpec::TST)TagSpec) {
3490 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003491 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003492 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003493 break;
3494
3495 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003496 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003497 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003498 break;
3499
3500 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003501 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003502 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003503 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003504 break;
3505
3506 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003507 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003508 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003509
Douglas Gregor218937c2011-02-01 19:23:04 +00003510 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003511 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003512
3513 // First pass: look for tags.
3514 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003515 LookupVisibleDecls(S, LookupTagName, Consumer,
3516 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003517
Douglas Gregor8071e422010-08-15 06:18:01 +00003518 if (CodeCompleter->includeGlobals()) {
3519 // Second pass: look for nested name specifiers.
3520 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3521 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3522 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003523
Douglas Gregor52779fb2010-09-23 23:01:17 +00003524 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003525 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003526}
3527
Douglas Gregor1a480c42010-08-27 17:35:51 +00003528void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003529 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3530 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003531 Results.EnterNewScope();
3532 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3533 Results.AddResult("const");
3534 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3535 Results.AddResult("volatile");
3536 if (getLangOptions().C99 &&
3537 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3538 Results.AddResult("restrict");
3539 Results.ExitScope();
3540 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003541 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003542 Results.data(), Results.size());
3543}
3544
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003545void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003546 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003547 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003548
John McCall781472f2010-08-25 08:40:02 +00003549 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003550 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3551 if (!type->isEnumeralType()) {
3552 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003553 Data.IntegralConstantExpression = true;
3554 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003555 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003556 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003557
3558 // Code-complete the cases of a switch statement over an enumeration type
3559 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003560 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003561
3562 // Determine which enumerators we have already seen in the switch statement.
3563 // FIXME: Ideally, we would also be able to look *past* the code-completion
3564 // token, in case we are code-completing in the middle of the switch and not
3565 // at the end. However, we aren't able to do so at the moment.
3566 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003567 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003568 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3569 SC = SC->getNextSwitchCase()) {
3570 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3571 if (!Case)
3572 continue;
3573
3574 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3575 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3576 if (EnumConstantDecl *Enumerator
3577 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3578 // We look into the AST of the case statement to determine which
3579 // enumerator was named. Alternatively, we could compute the value of
3580 // the integral constant expression, then compare it against the
3581 // values of each enumerator. However, value-based approach would not
3582 // work as well with C++ templates where enumerators declared within a
3583 // template are type- and value-dependent.
3584 EnumeratorsSeen.insert(Enumerator);
3585
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003586 // If this is a qualified-id, keep track of the nested-name-specifier
3587 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003588 //
3589 // switch (TagD.getKind()) {
3590 // case TagDecl::TK_enum:
3591 // break;
3592 // case XXX
3593 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003594 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003595 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3596 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003597 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003598 }
3599 }
3600
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003601 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3602 // If there are no prior enumerators in C++, check whether we have to
3603 // qualify the names of the enumerators that we suggest, because they
3604 // may not be visible in this scope.
3605 Qualifier = getRequiredQualification(Context, CurContext,
3606 Enum->getDeclContext());
3607
3608 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3609 }
3610
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003611 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003612 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3613 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003614 Results.EnterNewScope();
3615 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3616 EEnd = Enum->enumerator_end();
3617 E != EEnd; ++E) {
3618 if (EnumeratorsSeen.count(*E))
3619 continue;
3620
Douglas Gregor5c722c702011-02-18 23:30:37 +00003621 CodeCompletionResult R(*E, Qualifier);
3622 R.Priority = CCP_EnumInCase;
3623 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003624 }
3625 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003626
Douglas Gregor3da626b2011-07-07 16:03:39 +00003627 //We need to make sure we're setting the right context,
3628 //so only say we include macros if the code completer says we do
3629 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3630 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003631 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003632 kind = CodeCompletionContext::CCC_OtherWithMacros;
3633 }
3634
3635
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003636 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003637 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003638 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003639}
3640
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003641namespace {
3642 struct IsBetterOverloadCandidate {
3643 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003644 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003645
3646 public:
John McCall5769d612010-02-08 23:07:23 +00003647 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3648 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003649
3650 bool
3651 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003652 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003653 }
3654 };
3655}
3656
Douglas Gregord28dcd72010-05-30 06:10:08 +00003657static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3658 if (NumArgs && !Args)
3659 return true;
3660
3661 for (unsigned I = 0; I != NumArgs; ++I)
3662 if (!Args[I])
3663 return true;
3664
3665 return false;
3666}
3667
Richard Trieuf81e5a92011-09-09 02:00:50 +00003668void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3669 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003670 if (!CodeCompleter)
3671 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003672
3673 // When we're code-completing for a call, we fall back to ordinary
3674 // name code-completion whenever we can't produce specific
3675 // results. We may want to revisit this strategy in the future,
3676 // e.g., by merging the two kinds of results.
3677
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003678 Expr *Fn = (Expr *)FnIn;
3679 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003680
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003681 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003682 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003683 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003684 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003685 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003686 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003687
John McCall3b4294e2009-12-16 12:17:52 +00003688 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003689 SourceLocation Loc = Fn->getExprLoc();
3690 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003691
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003692 // FIXME: What if we're calling something that isn't a function declaration?
3693 // FIXME: What if we're calling a pseudo-destructor?
3694 // FIXME: What if we're calling a member function?
3695
Douglas Gregorc0265402010-01-21 15:46:19 +00003696 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003697 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003698
John McCall3b4294e2009-12-16 12:17:52 +00003699 Expr *NakedFn = Fn->IgnoreParenCasts();
3700 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3701 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3702 /*PartialOverloading=*/ true);
3703 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3704 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003705 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003706 if (!getLangOptions().CPlusPlus ||
3707 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003708 Results.push_back(ResultCandidate(FDecl));
3709 else
John McCall86820f52010-01-26 01:37:31 +00003710 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003711 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3712 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003713 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003714 }
John McCall3b4294e2009-12-16 12:17:52 +00003715 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003716
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003717 QualType ParamType;
3718
Douglas Gregorc0265402010-01-21 15:46:19 +00003719 if (!CandidateSet.empty()) {
3720 // Sort the overload candidate set by placing the best overloads first.
3721 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003722 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003723
Douglas Gregorc0265402010-01-21 15:46:19 +00003724 // Add the remaining viable overload candidates as code-completion reslults.
3725 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3726 CandEnd = CandidateSet.end();
3727 Cand != CandEnd; ++Cand) {
3728 if (Cand->Viable)
3729 Results.push_back(ResultCandidate(Cand->Function));
3730 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003731
3732 // From the viable candidates, try to determine the type of this parameter.
3733 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3734 if (const FunctionType *FType = Results[I].getFunctionType())
3735 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3736 if (NumArgs < Proto->getNumArgs()) {
3737 if (ParamType.isNull())
3738 ParamType = Proto->getArgType(NumArgs);
3739 else if (!Context.hasSameUnqualifiedType(
3740 ParamType.getNonReferenceType(),
3741 Proto->getArgType(NumArgs).getNonReferenceType())) {
3742 ParamType = QualType();
3743 break;
3744 }
3745 }
3746 }
3747 } else {
3748 // Try to determine the parameter type from the type of the expression
3749 // being called.
3750 QualType FunctionType = Fn->getType();
3751 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3752 FunctionType = Ptr->getPointeeType();
3753 else if (const BlockPointerType *BlockPtr
3754 = FunctionType->getAs<BlockPointerType>())
3755 FunctionType = BlockPtr->getPointeeType();
3756 else if (const MemberPointerType *MemPtr
3757 = FunctionType->getAs<MemberPointerType>())
3758 FunctionType = MemPtr->getPointeeType();
3759
3760 if (const FunctionProtoType *Proto
3761 = FunctionType->getAs<FunctionProtoType>()) {
3762 if (NumArgs < Proto->getNumArgs())
3763 ParamType = Proto->getArgType(NumArgs);
3764 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003765 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003766
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003767 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003768 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003769 else
3770 CodeCompleteExpression(S, ParamType);
3771
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003772 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003773 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3774 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003775}
3776
John McCalld226f652010-08-21 09:40:31 +00003777void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3778 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003779 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003780 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003781 return;
3782 }
3783
3784 CodeCompleteExpression(S, VD->getType());
3785}
3786
3787void Sema::CodeCompleteReturn(Scope *S) {
3788 QualType ResultType;
3789 if (isa<BlockDecl>(CurContext)) {
3790 if (BlockScopeInfo *BSI = getCurBlock())
3791 ResultType = BSI->ReturnType;
3792 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3793 ResultType = Function->getResultType();
3794 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3795 ResultType = Method->getResultType();
3796
3797 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003798 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003799 else
3800 CodeCompleteExpression(S, ResultType);
3801}
3802
Douglas Gregord2d8be62011-07-30 08:36:53 +00003803void Sema::CodeCompleteAfterIf(Scope *S) {
3804 typedef CodeCompletionResult Result;
3805 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3806 mapCodeCompletionContext(*this, PCC_Statement));
3807 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3808 Results.EnterNewScope();
3809
3810 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3811 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3812 CodeCompleter->includeGlobals());
3813
3814 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3815
3816 // "else" block
3817 CodeCompletionBuilder Builder(Results.getAllocator());
3818 Builder.AddTypedTextChunk("else");
3819 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3820 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3821 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3822 Builder.AddPlaceholderChunk("statements");
3823 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3824 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3825 Results.AddResult(Builder.TakeString());
3826
3827 // "else if" block
3828 Builder.AddTypedTextChunk("else");
3829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3830 Builder.AddTextChunk("if");
3831 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3833 if (getLangOptions().CPlusPlus)
3834 Builder.AddPlaceholderChunk("condition");
3835 else
3836 Builder.AddPlaceholderChunk("expression");
3837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3838 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3839 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3840 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3841 Builder.AddPlaceholderChunk("statements");
3842 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3843 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3844 Results.AddResult(Builder.TakeString());
3845
3846 Results.ExitScope();
3847
3848 if (S->getFnParent())
3849 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3850
3851 if (CodeCompleter->includeMacros())
3852 AddMacroResults(PP, Results);
3853
3854 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3855 Results.data(),Results.size());
3856}
3857
Richard Trieuf81e5a92011-09-09 02:00:50 +00003858void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003859 if (LHS)
3860 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3861 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003862 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003863}
3864
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003865void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003866 bool EnteringContext) {
3867 if (!SS.getScopeRep() || !CodeCompleter)
3868 return;
3869
Douglas Gregor86d9a522009-09-21 16:56:56 +00003870 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3871 if (!Ctx)
3872 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003873
3874 // Try to instantiate any non-dependent declaration contexts before
3875 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003876 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003877 return;
3878
Douglas Gregor218937c2011-02-01 19:23:04 +00003879 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3880 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003881 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003882
Douglas Gregor86d9a522009-09-21 16:56:56 +00003883 // The "template" keyword can follow "::" in the grammar, but only
3884 // put it into the grammar if the nested-name-specifier is dependent.
3885 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3886 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003887 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003888
3889 // Add calls to overridden virtual functions, if there are any.
3890 //
3891 // FIXME: This isn't wonderful, because we don't know whether we're actually
3892 // in a context that permits expressions. This is a general issue with
3893 // qualified-id completions.
3894 if (!EnteringContext)
3895 MaybeAddOverrideCalls(*this, Ctx, Results);
3896 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003897
Douglas Gregorf6961522010-08-27 21:18:54 +00003898 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3899 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3900
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003901 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003902 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003903 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003904}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003905
3906void Sema::CodeCompleteUsing(Scope *S) {
3907 if (!CodeCompleter)
3908 return;
3909
Douglas Gregor218937c2011-02-01 19:23:04 +00003910 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003911 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3912 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003913 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003914
3915 // If we aren't in class scope, we could see the "namespace" keyword.
3916 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003917 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003918
3919 // After "using", we can see anything that would start a
3920 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003921 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003922 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3923 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003924 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003925
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003926 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003927 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003928 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003929}
3930
3931void Sema::CodeCompleteUsingDirective(Scope *S) {
3932 if (!CodeCompleter)
3933 return;
3934
Douglas Gregor86d9a522009-09-21 16:56:56 +00003935 // After "using namespace", we expect to see a namespace name or namespace
3936 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003937 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3938 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003939 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003940 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003941 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003942 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3943 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003944 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003945 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003946 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003947 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003948}
3949
3950void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3951 if (!CodeCompleter)
3952 return;
3953
Douglas Gregor86d9a522009-09-21 16:56:56 +00003954 DeclContext *Ctx = (DeclContext *)S->getEntity();
3955 if (!S->getParent())
3956 Ctx = Context.getTranslationUnitDecl();
3957
Douglas Gregor52779fb2010-09-23 23:01:17 +00003958 bool SuppressedGlobalResults
3959 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3960
Douglas Gregor218937c2011-02-01 19:23:04 +00003961 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003962 SuppressedGlobalResults
3963 ? CodeCompletionContext::CCC_Namespace
3964 : CodeCompletionContext::CCC_Other,
3965 &ResultBuilder::IsNamespace);
3966
3967 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003968 // We only want to see those namespaces that have already been defined
3969 // within this scope, because its likely that the user is creating an
3970 // extended namespace declaration. Keep track of the most recent
3971 // definition of each namespace.
3972 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3973 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3974 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3975 NS != NSEnd; ++NS)
3976 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3977
3978 // Add the most recent definition (or extended definition) of each
3979 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003980 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003981 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3982 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3983 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003984 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003985 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003986 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003987 }
3988
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003989 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003990 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003991 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003992}
3993
3994void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3995 if (!CodeCompleter)
3996 return;
3997
Douglas Gregor86d9a522009-09-21 16:56:56 +00003998 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003999 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4000 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004001 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004002 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004003 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4004 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004005 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004006 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004007 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004008}
4009
Douglas Gregored8d3222009-09-18 20:05:18 +00004010void Sema::CodeCompleteOperatorName(Scope *S) {
4011 if (!CodeCompleter)
4012 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004013
John McCall0a2c5e22010-08-25 06:19:51 +00004014 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004015 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4016 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004017 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004018 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004019
Douglas Gregor86d9a522009-09-21 16:56:56 +00004020 // Add the names of overloadable operators.
4021#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4022 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004023 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004024#include "clang/Basic/OperatorKinds.def"
4025
4026 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004027 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004028 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004029 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4030 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004031
4032 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004033 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004034 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004035
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004036 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004037 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004038 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004039}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004040
Douglas Gregor0133f522010-08-28 00:00:50 +00004041void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004042 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004043 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004044 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004045 CXXConstructorDecl *Constructor
4046 = static_cast<CXXConstructorDecl *>(ConstructorD);
4047 if (!Constructor)
4048 return;
4049
Douglas Gregor218937c2011-02-01 19:23:04 +00004050 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004051 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004052 Results.EnterNewScope();
4053
4054 // Fill in any already-initialized fields or base classes.
4055 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4056 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4057 for (unsigned I = 0; I != NumInitializers; ++I) {
4058 if (Initializers[I]->isBaseInitializer())
4059 InitializedBases.insert(
4060 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4061 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004062 InitializedFields.insert(cast<FieldDecl>(
4063 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004064 }
4065
4066 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004067 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004068 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004069 CXXRecordDecl *ClassDecl = Constructor->getParent();
4070 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4071 BaseEnd = ClassDecl->bases_end();
4072 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004073 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4074 SawLastInitializer
4075 = NumInitializers > 0 &&
4076 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4077 Context.hasSameUnqualifiedType(Base->getType(),
4078 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004079 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004080 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004081
Douglas Gregor218937c2011-02-01 19:23:04 +00004082 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004083 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004084 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004085 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4086 Builder.AddPlaceholderChunk("args");
4087 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4088 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004089 SawLastInitializer? CCP_NextInitializer
4090 : CCP_MemberDeclaration));
4091 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004092 }
4093
4094 // Add completions for virtual base classes.
4095 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4096 BaseEnd = ClassDecl->vbases_end();
4097 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004098 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4099 SawLastInitializer
4100 = NumInitializers > 0 &&
4101 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4102 Context.hasSameUnqualifiedType(Base->getType(),
4103 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004104 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004105 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004106
Douglas Gregor218937c2011-02-01 19:23:04 +00004107 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004108 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004109 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4111 Builder.AddPlaceholderChunk("args");
4112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4113 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004114 SawLastInitializer? CCP_NextInitializer
4115 : CCP_MemberDeclaration));
4116 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004117 }
4118
4119 // Add completions for members.
4120 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4121 FieldEnd = ClassDecl->field_end();
4122 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004123 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4124 SawLastInitializer
4125 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004126 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4127 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004128 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004129 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004130
4131 if (!Field->getDeclName())
4132 continue;
4133
Douglas Gregordae68752011-02-01 22:57:45 +00004134 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004135 Field->getIdentifier()->getName()));
4136 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4137 Builder.AddPlaceholderChunk("args");
4138 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4139 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004140 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004141 : CCP_MemberDeclaration,
4142 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004143 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004144 }
4145 Results.ExitScope();
4146
Douglas Gregor52779fb2010-09-23 23:01:17 +00004147 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004148 Results.data(), Results.size());
4149}
4150
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004151// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4152// true or false.
4153#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004154static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004155 ResultBuilder &Results,
4156 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004157 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004158 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004159 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004160
Douglas Gregor218937c2011-02-01 19:23:04 +00004161 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004162 if (LangOpts.ObjC2) {
4163 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004164 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4165 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4166 Builder.AddPlaceholderChunk("property");
4167 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004168
4169 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004170 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4171 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4172 Builder.AddPlaceholderChunk("property");
4173 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004174 }
4175}
4176
Douglas Gregorbca403c2010-01-13 23:51:12 +00004177static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004178 ResultBuilder &Results,
4179 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004180 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004181
4182 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004183 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004184
4185 if (LangOpts.ObjC2) {
4186 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004187 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004188
4189 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004190 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004191
4192 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004193 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004194 }
4195}
4196
Douglas Gregorbca403c2010-01-13 23:51:12 +00004197static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004198 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004199 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004200
4201 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004202 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4203 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4204 Builder.AddPlaceholderChunk("name");
4205 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004206
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004207 if (Results.includeCodePatterns()) {
4208 // @interface name
4209 // FIXME: Could introduce the whole pattern, including superclasses and
4210 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004211 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4212 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4213 Builder.AddPlaceholderChunk("class");
4214 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004215
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004216 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004217 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4218 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4219 Builder.AddPlaceholderChunk("protocol");
4220 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004221
4222 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004223 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4224 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4225 Builder.AddPlaceholderChunk("class");
4226 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004227 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004228
4229 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004230 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4231 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4232 Builder.AddPlaceholderChunk("alias");
4233 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4234 Builder.AddPlaceholderChunk("class");
4235 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004236}
4237
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004238void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004239 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004240 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4241 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004242 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004243 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004244 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004245 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004246 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004247 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004248 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004249 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004250 HandleCodeCompleteResults(this, CodeCompleter,
4251 CodeCompletionContext::CCC_Other,
4252 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004253}
4254
Douglas Gregorbca403c2010-01-13 23:51:12 +00004255static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004256 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004257 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004258
4259 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004260 const char *EncodeType = "char[]";
4261 if (Results.getSema().getLangOptions().CPlusPlus ||
4262 Results.getSema().getLangOptions().ConstStrings)
4263 EncodeType = " const char[]";
4264 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004265 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4266 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4267 Builder.AddPlaceholderChunk("type-name");
4268 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4269 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004270
4271 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004272 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004273 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4274 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4275 Builder.AddPlaceholderChunk("protocol-name");
4276 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4277 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004278
4279 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004280 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004281 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4282 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4283 Builder.AddPlaceholderChunk("selector");
4284 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4285 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004286}
4287
Douglas Gregorbca403c2010-01-13 23:51:12 +00004288static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004289 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004290 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004291
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004292 if (Results.includeCodePatterns()) {
4293 // @try { statements } @catch ( declaration ) { statements } @finally
4294 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004295 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4296 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4297 Builder.AddPlaceholderChunk("statements");
4298 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4299 Builder.AddTextChunk("@catch");
4300 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4301 Builder.AddPlaceholderChunk("parameter");
4302 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4303 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4304 Builder.AddPlaceholderChunk("statements");
4305 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4306 Builder.AddTextChunk("@finally");
4307 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4308 Builder.AddPlaceholderChunk("statements");
4309 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4310 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004311 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004312
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004313 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004314 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4315 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4316 Builder.AddPlaceholderChunk("expression");
4317 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004318
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004319 if (Results.includeCodePatterns()) {
4320 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004321 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4322 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4323 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4324 Builder.AddPlaceholderChunk("expression");
4325 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4326 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4327 Builder.AddPlaceholderChunk("statements");
4328 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4329 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004330 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004331}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004332
Douglas Gregorbca403c2010-01-13 23:51:12 +00004333static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004334 ResultBuilder &Results,
4335 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004336 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004337 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4338 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4339 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004340 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004341 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004342}
4343
4344void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004345 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4346 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004347 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004348 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004349 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004350 HandleCodeCompleteResults(this, CodeCompleter,
4351 CodeCompletionContext::CCC_Other,
4352 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004353}
4354
4355void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004356 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4357 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004358 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004359 AddObjCStatementResults(Results, false);
4360 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004361 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004362 HandleCodeCompleteResults(this, CodeCompleter,
4363 CodeCompletionContext::CCC_Other,
4364 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004365}
4366
4367void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004368 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4369 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004370 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004371 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004372 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004373 HandleCodeCompleteResults(this, CodeCompleter,
4374 CodeCompletionContext::CCC_Other,
4375 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004376}
4377
Douglas Gregor988358f2009-11-19 00:14:45 +00004378/// \brief Determine whether the addition of the given flag to an Objective-C
4379/// property's attributes will cause a conflict.
4380static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4381 // Check if we've already added this flag.
4382 if (Attributes & NewFlag)
4383 return true;
4384
4385 Attributes |= NewFlag;
4386
4387 // Check for collisions with "readonly".
4388 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4389 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4390 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004391 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004392 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004393 ObjCDeclSpec::DQ_PR_retain |
4394 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004395 return true;
4396
John McCallf85e1932011-06-15 23:02:42 +00004397 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004398 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004399 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004400 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004401 ObjCDeclSpec::DQ_PR_retain|
4402 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004403 if (AssignCopyRetMask &&
4404 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004405 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004406 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004407 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4408 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004409 return true;
4410
4411 return false;
4412}
4413
Douglas Gregora93b1082009-11-18 23:08:07 +00004414void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004415 if (!CodeCompleter)
4416 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004417
Steve Naroffece8e712009-10-08 21:55:05 +00004418 unsigned Attributes = ODS.getPropertyAttributes();
4419
John McCall0a2c5e22010-08-25 06:19:51 +00004420 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004421 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4422 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004423 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004424 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004425 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004426 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004427 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004428 if (!ObjCPropertyFlagConflicts(Attributes,
4429 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4430 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004431 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004432 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004433 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004434 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004435 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4436 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004437 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004438 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004439 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004440 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004441 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4442 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004443 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004444 CodeCompletionBuilder Setter(Results.getAllocator());
4445 Setter.AddTypedTextChunk("setter");
4446 Setter.AddTextChunk(" = ");
4447 Setter.AddPlaceholderChunk("method");
4448 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004449 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004450 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004451 CodeCompletionBuilder Getter(Results.getAllocator());
4452 Getter.AddTypedTextChunk("getter");
4453 Getter.AddTextChunk(" = ");
4454 Getter.AddPlaceholderChunk("method");
4455 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004456 }
Steve Naroffece8e712009-10-08 21:55:05 +00004457 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004458 HandleCodeCompleteResults(this, CodeCompleter,
4459 CodeCompletionContext::CCC_Other,
4460 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004461}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004462
Douglas Gregor4ad96852009-11-19 07:41:15 +00004463/// \brief Descripts the kind of Objective-C method that we want to find
4464/// via code completion.
4465enum ObjCMethodKind {
4466 MK_Any, //< Any kind of method, provided it means other specified criteria.
4467 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4468 MK_OneArgSelector //< One-argument selector.
4469};
4470
Douglas Gregor458433d2010-08-26 15:07:07 +00004471static bool isAcceptableObjCSelector(Selector Sel,
4472 ObjCMethodKind WantKind,
4473 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004474 unsigned NumSelIdents,
4475 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004476 if (NumSelIdents > Sel.getNumArgs())
4477 return false;
4478
4479 switch (WantKind) {
4480 case MK_Any: break;
4481 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4482 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4483 }
4484
Douglas Gregorcf544262010-11-17 21:36:08 +00004485 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4486 return false;
4487
Douglas Gregor458433d2010-08-26 15:07:07 +00004488 for (unsigned I = 0; I != NumSelIdents; ++I)
4489 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4490 return false;
4491
4492 return true;
4493}
4494
Douglas Gregor4ad96852009-11-19 07:41:15 +00004495static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4496 ObjCMethodKind WantKind,
4497 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004498 unsigned NumSelIdents,
4499 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004500 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004501 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004502}
Douglas Gregord36adf52010-09-16 16:06:31 +00004503
4504namespace {
4505 /// \brief A set of selectors, which is used to avoid introducing multiple
4506 /// completions with the same selector into the result set.
4507 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4508}
4509
Douglas Gregor36ecb042009-11-17 23:22:23 +00004510/// \brief Add all of the Objective-C methods in the given Objective-C
4511/// container to the set of results.
4512///
4513/// The container will be a class, protocol, category, or implementation of
4514/// any of the above. This mether will recurse to include methods from
4515/// the superclasses of classes along with their categories, protocols, and
4516/// implementations.
4517///
4518/// \param Container the container in which we'll look to find methods.
4519///
4520/// \param WantInstance whether to add instance methods (only); if false, this
4521/// routine will add factory methods (only).
4522///
4523/// \param CurContext the context in which we're performing the lookup that
4524/// finds methods.
4525///
Douglas Gregorcf544262010-11-17 21:36:08 +00004526/// \param AllowSameLength Whether we allow a method to be added to the list
4527/// when it has the same number of parameters as we have selector identifiers.
4528///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004529/// \param Results the structure into which we'll add results.
4530static void AddObjCMethods(ObjCContainerDecl *Container,
4531 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004532 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004533 IdentifierInfo **SelIdents,
4534 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004535 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004536 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004537 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004538 ResultBuilder &Results,
4539 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004540 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004541 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4542 MEnd = Container->meth_end();
4543 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004544 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4545 // Check whether the selector identifiers we've been given are a
4546 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004547 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4548 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004549 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004550
Douglas Gregord36adf52010-09-16 16:06:31 +00004551 if (!Selectors.insert((*M)->getSelector()))
4552 continue;
4553
Douglas Gregord3c68542009-11-19 01:08:35 +00004554 Result R = Result(*M, 0);
4555 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004556 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004557 if (!InOriginalClass)
4558 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004559 Results.MaybeAddResult(R, CurContext);
4560 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004561 }
4562
Douglas Gregore396c7b2010-09-16 15:34:59 +00004563 // Visit the protocols of protocols.
4564 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004565 if (Protocol->hasDefinition()) {
4566 const ObjCList<ObjCProtocolDecl> &Protocols
4567 = Protocol->getReferencedProtocols();
4568 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4569 E = Protocols.end();
4570 I != E; ++I)
4571 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4572 NumSelIdents, CurContext, Selectors, AllowSameLength,
4573 Results, false);
4574 }
Douglas Gregore396c7b2010-09-16 15:34:59 +00004575 }
4576
Douglas Gregor36ecb042009-11-17 23:22:23 +00004577 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00004578 if (!IFace || !IFace->hasDefinition())
Douglas Gregor36ecb042009-11-17 23:22:23 +00004579 return;
4580
4581 // Add methods in protocols.
4582 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4583 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4584 E = Protocols.end();
4585 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004586 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004587 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004588
4589 // Add methods in categories.
4590 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4591 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004592 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004593 NumSelIdents, CurContext, Selectors, AllowSameLength,
4594 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004595
4596 // Add a categories protocol methods.
4597 const ObjCList<ObjCProtocolDecl> &Protocols
4598 = CatDecl->getReferencedProtocols();
4599 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4600 E = Protocols.end();
4601 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004602 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004603 NumSelIdents, CurContext, Selectors, AllowSameLength,
4604 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004605
4606 // Add methods in category implementations.
4607 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004608 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004609 NumSelIdents, CurContext, Selectors, AllowSameLength,
4610 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004611 }
4612
4613 // Add methods in superclass.
4614 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004615 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004616 SelIdents, NumSelIdents, CurContext, Selectors,
4617 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004618
4619 // Add methods in our implementation, if any.
4620 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004621 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004622 NumSelIdents, CurContext, Selectors, AllowSameLength,
4623 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004624}
4625
4626
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004627void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004628 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004629
4630 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004631 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004632 if (!Class) {
4633 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004634 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004635 Class = Category->getClassInterface();
4636
4637 if (!Class)
4638 return;
4639 }
4640
4641 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004642 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4643 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004644 Results.EnterNewScope();
4645
Douglas Gregord36adf52010-09-16 16:06:31 +00004646 VisitedSelectorSet Selectors;
4647 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004648 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004649 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004650 HandleCodeCompleteResults(this, CodeCompleter,
4651 CodeCompletionContext::CCC_Other,
4652 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004653}
4654
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004655void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004656 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004657
4658 // Try to find the interface where setters might live.
4659 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004660 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004661 if (!Class) {
4662 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004663 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004664 Class = Category->getClassInterface();
4665
4666 if (!Class)
4667 return;
4668 }
4669
4670 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004671 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4672 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004673 Results.EnterNewScope();
4674
Douglas Gregord36adf52010-09-16 16:06:31 +00004675 VisitedSelectorSet Selectors;
4676 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004677 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004678
4679 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004680 HandleCodeCompleteResults(this, CodeCompleter,
4681 CodeCompletionContext::CCC_Other,
4682 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004683}
4684
Douglas Gregorafc45782011-02-15 22:19:42 +00004685void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4686 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004687 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004688 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4689 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004690 Results.EnterNewScope();
4691
4692 // Add context-sensitive, Objective-C parameter-passing keywords.
4693 bool AddedInOut = false;
4694 if ((DS.getObjCDeclQualifier() &
4695 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4696 Results.AddResult("in");
4697 Results.AddResult("inout");
4698 AddedInOut = true;
4699 }
4700 if ((DS.getObjCDeclQualifier() &
4701 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4702 Results.AddResult("out");
4703 if (!AddedInOut)
4704 Results.AddResult("inout");
4705 }
4706 if ((DS.getObjCDeclQualifier() &
4707 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4708 ObjCDeclSpec::DQ_Oneway)) == 0) {
4709 Results.AddResult("bycopy");
4710 Results.AddResult("byref");
4711 Results.AddResult("oneway");
4712 }
4713
Douglas Gregorafc45782011-02-15 22:19:42 +00004714 // If we're completing the return type of an Objective-C method and the
4715 // identifier IBAction refers to a macro, provide a completion item for
4716 // an action, e.g.,
4717 // IBAction)<#selector#>:(id)sender
4718 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4719 Context.Idents.get("IBAction").hasMacroDefinition()) {
4720 typedef CodeCompletionString::Chunk Chunk;
4721 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4722 CXAvailability_Available);
4723 Builder.AddTypedTextChunk("IBAction");
4724 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4725 Builder.AddPlaceholderChunk("selector");
4726 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4727 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4728 Builder.AddTextChunk("id");
4729 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4730 Builder.AddTextChunk("sender");
4731 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4732 }
4733
Douglas Gregord32b0222010-08-24 01:06:58 +00004734 // Add various builtin type names and specifiers.
4735 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4736 Results.ExitScope();
4737
4738 // Add the various type names
4739 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4740 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4741 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4742 CodeCompleter->includeGlobals());
4743
4744 if (CodeCompleter->includeMacros())
4745 AddMacroResults(PP, Results);
4746
4747 HandleCodeCompleteResults(this, CodeCompleter,
4748 CodeCompletionContext::CCC_Type,
4749 Results.data(), Results.size());
4750}
4751
Douglas Gregor22f56992010-04-06 19:22:33 +00004752/// \brief When we have an expression with type "id", we may assume
4753/// that it has some more-specific class type based on knowledge of
4754/// common uses of Objective-C. This routine returns that class type,
4755/// or NULL if no better result could be determined.
4756static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004757 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004758 if (!Msg)
4759 return 0;
4760
4761 Selector Sel = Msg->getSelector();
4762 if (Sel.isNull())
4763 return 0;
4764
4765 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4766 if (!Id)
4767 return 0;
4768
4769 ObjCMethodDecl *Method = Msg->getMethodDecl();
4770 if (!Method)
4771 return 0;
4772
4773 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004774 ObjCInterfaceDecl *IFace = 0;
4775 switch (Msg->getReceiverKind()) {
4776 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004777 if (const ObjCObjectType *ObjType
4778 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4779 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004780 break;
4781
4782 case ObjCMessageExpr::Instance: {
4783 QualType T = Msg->getInstanceReceiver()->getType();
4784 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4785 IFace = Ptr->getInterfaceDecl();
4786 break;
4787 }
4788
4789 case ObjCMessageExpr::SuperInstance:
4790 case ObjCMessageExpr::SuperClass:
4791 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004792 }
4793
4794 if (!IFace)
4795 return 0;
4796
4797 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4798 if (Method->isInstanceMethod())
4799 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4800 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004801 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004802 .Case("autorelease", IFace)
4803 .Case("copy", IFace)
4804 .Case("copyWithZone", IFace)
4805 .Case("mutableCopy", IFace)
4806 .Case("mutableCopyWithZone", IFace)
4807 .Case("awakeFromCoder", IFace)
4808 .Case("replacementObjectFromCoder", IFace)
4809 .Case("class", IFace)
4810 .Case("classForCoder", IFace)
4811 .Case("superclass", Super)
4812 .Default(0);
4813
4814 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4815 .Case("new", IFace)
4816 .Case("alloc", IFace)
4817 .Case("allocWithZone", IFace)
4818 .Case("class", IFace)
4819 .Case("superclass", Super)
4820 .Default(0);
4821}
4822
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004823// Add a special completion for a message send to "super", which fills in the
4824// most likely case of forwarding all of our arguments to the superclass
4825// function.
4826///
4827/// \param S The semantic analysis object.
4828///
4829/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4830/// the "super" keyword. Otherwise, we just need to provide the arguments.
4831///
4832/// \param SelIdents The identifiers in the selector that have already been
4833/// provided as arguments for a send to "super".
4834///
4835/// \param NumSelIdents The number of identifiers in \p SelIdents.
4836///
4837/// \param Results The set of results to augment.
4838///
4839/// \returns the Objective-C method declaration that would be invoked by
4840/// this "super" completion. If NULL, no completion was added.
4841static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4842 IdentifierInfo **SelIdents,
4843 unsigned NumSelIdents,
4844 ResultBuilder &Results) {
4845 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4846 if (!CurMethod)
4847 return 0;
4848
4849 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4850 if (!Class)
4851 return 0;
4852
4853 // Try to find a superclass method with the same selector.
4854 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004855 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4856 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004857 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4858 CurMethod->isInstanceMethod());
4859
Douglas Gregor78bcd912011-02-16 00:51:18 +00004860 // Check in categories or class extensions.
4861 if (!SuperMethod) {
4862 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4863 Category = Category->getNextClassCategory())
4864 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4865 CurMethod->isInstanceMethod())))
4866 break;
4867 }
4868 }
4869
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004870 if (!SuperMethod)
4871 return 0;
4872
4873 // Check whether the superclass method has the same signature.
4874 if (CurMethod->param_size() != SuperMethod->param_size() ||
4875 CurMethod->isVariadic() != SuperMethod->isVariadic())
4876 return 0;
4877
4878 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4879 CurPEnd = CurMethod->param_end(),
4880 SuperP = SuperMethod->param_begin();
4881 CurP != CurPEnd; ++CurP, ++SuperP) {
4882 // Make sure the parameter types are compatible.
4883 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4884 (*SuperP)->getType()))
4885 return 0;
4886
4887 // Make sure we have a parameter name to forward!
4888 if (!(*CurP)->getIdentifier())
4889 return 0;
4890 }
4891
4892 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004893 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004894
4895 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004896 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4897 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004898
4899 // If we need the "super" keyword, add it (plus some spacing).
4900 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004901 Builder.AddTypedTextChunk("super");
4902 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004903 }
4904
4905 Selector Sel = CurMethod->getSelector();
4906 if (Sel.isUnarySelector()) {
4907 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004908 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004909 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004910 else
Douglas Gregordae68752011-02-01 22:57:45 +00004911 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004912 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004913 } else {
4914 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4915 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4916 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004917 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004918
4919 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004920 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004921 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004922 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004923 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004924 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004925 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004926 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004927 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004928 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004929 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004930 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004931 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004932 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004933 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004934 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004935 }
4936 }
4937 }
4938
Douglas Gregor218937c2011-02-01 19:23:04 +00004939 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004940 SuperMethod->isInstanceMethod()
4941 ? CXCursor_ObjCInstanceMethodDecl
4942 : CXCursor_ObjCClassMethodDecl));
4943 return SuperMethod;
4944}
4945
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004946void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004947 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004948 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4949 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004950 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004951
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004952 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4953 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004954 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4955 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004956
4957 // If we are in an Objective-C method inside a class that has a superclass,
4958 // add "super" as an option.
4959 if (ObjCMethodDecl *Method = getCurMethodDecl())
4960 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004961 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004962 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004963
4964 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4965 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004966
4967 Results.ExitScope();
4968
4969 if (CodeCompleter->includeMacros())
4970 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004971 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004972 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004973
4974}
4975
Douglas Gregor2725ca82010-04-21 19:57:20 +00004976void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4977 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004978 unsigned NumSelIdents,
4979 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004980 ObjCInterfaceDecl *CDecl = 0;
4981 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4982 // Figure out which interface we're in.
4983 CDecl = CurMethod->getClassInterface();
4984 if (!CDecl)
4985 return;
4986
4987 // Find the superclass of this class.
4988 CDecl = CDecl->getSuperClass();
4989 if (!CDecl)
4990 return;
4991
4992 if (CurMethod->isInstanceMethod()) {
4993 // We are inside an instance method, which means that the message
4994 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004995 // current object.
4996 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004997 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004998 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004999 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005000 }
5001
5002 // Fall through to send to the superclass in CDecl.
5003 } else {
5004 // "super" may be the name of a type or variable. Figure out which
5005 // it is.
5006 IdentifierInfo *Super = &Context.Idents.get("super");
5007 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5008 LookupOrdinaryName);
5009 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5010 // "super" names an interface. Use it.
5011 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005012 if (const ObjCObjectType *Iface
5013 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5014 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005015 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5016 // "super" names an unresolved type; we can't be more specific.
5017 } else {
5018 // Assume that "super" names some kind of value and parse that way.
5019 CXXScopeSpec SS;
5020 UnqualifiedId id;
5021 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005022 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005023 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005024 SelIdents, NumSelIdents,
5025 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005026 }
5027
5028 // Fall through
5029 }
5030
John McCallb3d87482010-08-24 05:47:05 +00005031 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005032 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005033 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005034 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005035 NumSelIdents, AtArgumentExpression,
5036 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005037}
5038
Douglas Gregorb9d77572010-09-21 00:03:25 +00005039/// \brief Given a set of code-completion results for the argument of a message
5040/// send, determine the preferred type (if any) for that argument expression.
5041static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5042 unsigned NumSelIdents) {
5043 typedef CodeCompletionResult Result;
5044 ASTContext &Context = Results.getSema().Context;
5045
5046 QualType PreferredType;
5047 unsigned BestPriority = CCP_Unlikely * 2;
5048 Result *ResultsData = Results.data();
5049 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5050 Result &R = ResultsData[I];
5051 if (R.Kind == Result::RK_Declaration &&
5052 isa<ObjCMethodDecl>(R.Declaration)) {
5053 if (R.Priority <= BestPriority) {
5054 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5055 if (NumSelIdents <= Method->param_size()) {
5056 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5057 ->getType();
5058 if (R.Priority < BestPriority || PreferredType.isNull()) {
5059 BestPriority = R.Priority;
5060 PreferredType = MyPreferredType;
5061 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5062 MyPreferredType)) {
5063 PreferredType = QualType();
5064 }
5065 }
5066 }
5067 }
5068 }
5069
5070 return PreferredType;
5071}
5072
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005073static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5074 ParsedType Receiver,
5075 IdentifierInfo **SelIdents,
5076 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005077 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005078 bool IsSuper,
5079 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005080 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005081 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005082
Douglas Gregor24a069f2009-11-17 17:59:40 +00005083 // If the given name refers to an interface type, retrieve the
5084 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005085 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005086 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005087 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005088 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5089 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005090 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005091
Douglas Gregor36ecb042009-11-17 23:22:23 +00005092 // Add all of the factory methods in this Objective-C class, its protocols,
5093 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005094 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005095
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005096 // If this is a send-to-super, try to add the special "super" send
5097 // completion.
5098 if (IsSuper) {
5099 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005100 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5101 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005102 Results.Ignore(SuperMethod);
5103 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005104
Douglas Gregor265f7492010-08-27 15:29:55 +00005105 // If we're inside an Objective-C method definition, prefer its selector to
5106 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005107 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005108 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005109
Douglas Gregord36adf52010-09-16 16:06:31 +00005110 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005111 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005112 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005113 SemaRef.CurContext, Selectors, AtArgumentExpression,
5114 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005115 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005116 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005117
Douglas Gregor719770d2010-04-06 17:30:22 +00005118 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005119 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005120 if (SemaRef.ExternalSource) {
5121 for (uint32_t I = 0,
5122 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005123 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005124 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5125 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005126 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005127
5128 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005129 }
5130 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005131
5132 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5133 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005134 M != MEnd; ++M) {
5135 for (ObjCMethodList *MethList = &M->second.second;
5136 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005137 MethList = MethList->Next) {
5138 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5139 NumSelIdents))
5140 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005141
Douglas Gregor13438f92010-04-06 16:40:00 +00005142 Result R(MethList->Method, 0);
5143 R.StartParameter = NumSelIdents;
5144 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005145 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005146 }
5147 }
5148 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005149
5150 Results.ExitScope();
5151}
Douglas Gregor13438f92010-04-06 16:40:00 +00005152
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005153void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5154 IdentifierInfo **SelIdents,
5155 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005156 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005157 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005158
5159 QualType T = this->GetTypeFromParser(Receiver);
5160
Douglas Gregor218937c2011-02-01 19:23:04 +00005161 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005162 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005163 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005164
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005165 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5166 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005167
5168 // If we're actually at the argument expression (rather than prior to the
5169 // selector), we're actually performing code completion for an expression.
5170 // Determine whether we have a single, best method. If so, we can
5171 // code-complete the expression using the corresponding parameter type as
5172 // our preferred type, improving completion results.
5173 if (AtArgumentExpression) {
5174 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005175 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005176 if (PreferredType.isNull())
5177 CodeCompleteOrdinaryName(S, PCC_Expression);
5178 else
5179 CodeCompleteExpression(S, PreferredType);
5180 return;
5181 }
5182
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005183 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005184 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005185 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005186}
5187
Richard Trieuf81e5a92011-09-09 02:00:50 +00005188void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005189 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005190 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005191 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005192 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005193 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005194
5195 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005196
Douglas Gregor36ecb042009-11-17 23:22:23 +00005197 // If necessary, apply function/array conversion to the receiver.
5198 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005199 if (RecExpr) {
5200 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5201 if (Conv.isInvalid()) // conversion failed. bail.
5202 return;
5203 RecExpr = Conv.take();
5204 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005205 QualType ReceiverType = RecExpr? RecExpr->getType()
5206 : Super? Context.getObjCObjectPointerType(
5207 Context.getObjCInterfaceType(Super))
5208 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005209
Douglas Gregorda892642010-11-08 21:12:30 +00005210 // If we're messaging an expression with type "id" or "Class", check
5211 // whether we know something special about the receiver that allows
5212 // us to assume a more-specific receiver type.
5213 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5214 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5215 if (ReceiverType->isObjCClassType())
5216 return CodeCompleteObjCClassMessage(S,
5217 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5218 SelIdents, NumSelIdents,
5219 AtArgumentExpression, Super);
5220
5221 ReceiverType = Context.getObjCObjectPointerType(
5222 Context.getObjCInterfaceType(IFace));
5223 }
5224
Douglas Gregor36ecb042009-11-17 23:22:23 +00005225 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005226 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005227 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005228 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005229
Douglas Gregor36ecb042009-11-17 23:22:23 +00005230 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005231
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005232 // If this is a send-to-super, try to add the special "super" send
5233 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005234 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005235 if (ObjCMethodDecl *SuperMethod
5236 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5237 Results))
5238 Results.Ignore(SuperMethod);
5239 }
5240
Douglas Gregor265f7492010-08-27 15:29:55 +00005241 // If we're inside an Objective-C method definition, prefer its selector to
5242 // others.
5243 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5244 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005245
Douglas Gregord36adf52010-09-16 16:06:31 +00005246 // Keep track of the selectors we've already added.
5247 VisitedSelectorSet Selectors;
5248
Douglas Gregorf74a4192009-11-18 00:06:18 +00005249 // Handle messages to Class. This really isn't a message to an instance
5250 // method, so we treat it the same way we would treat a message send to a
5251 // class method.
5252 if (ReceiverType->isObjCClassType() ||
5253 ReceiverType->isObjCQualifiedClassType()) {
5254 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5255 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005256 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005257 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005258 }
5259 }
5260 // Handle messages to a qualified ID ("id<foo>").
5261 else if (const ObjCObjectPointerType *QualID
5262 = ReceiverType->getAsObjCQualifiedIdType()) {
5263 // Search protocols for instance methods.
5264 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5265 E = QualID->qual_end();
5266 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005267 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005268 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005269 }
5270 // Handle messages to a pointer to interface type.
5271 else if (const ObjCObjectPointerType *IFacePtr
5272 = ReceiverType->getAsObjCInterfacePointerType()) {
5273 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005274 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005275 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5276 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005277
5278 // Search protocols for instance methods.
5279 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5280 E = IFacePtr->qual_end();
5281 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005282 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005283 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005284 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005285 // Handle messages to "id".
5286 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005287 // We're messaging "id", so provide all instance methods we know
5288 // about as code-completion results.
5289
5290 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005291 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005292 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005293 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5294 I != N; ++I) {
5295 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005296 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005297 continue;
5298
Sebastian Redldb9d2142010-08-02 23:18:59 +00005299 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005300 }
5301 }
5302
Sebastian Redldb9d2142010-08-02 23:18:59 +00005303 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5304 MEnd = MethodPool.end();
5305 M != MEnd; ++M) {
5306 for (ObjCMethodList *MethList = &M->second.first;
5307 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005308 MethList = MethList->Next) {
5309 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5310 NumSelIdents))
5311 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005312
5313 if (!Selectors.insert(MethList->Method->getSelector()))
5314 continue;
5315
Douglas Gregor13438f92010-04-06 16:40:00 +00005316 Result R(MethList->Method, 0);
5317 R.StartParameter = NumSelIdents;
5318 R.AllParametersAreInformative = false;
5319 Results.MaybeAddResult(R, CurContext);
5320 }
5321 }
5322 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005323 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005324
5325
5326 // If we're actually at the argument expression (rather than prior to the
5327 // selector), we're actually performing code completion for an expression.
5328 // Determine whether we have a single, best method. If so, we can
5329 // code-complete the expression using the corresponding parameter type as
5330 // our preferred type, improving completion results.
5331 if (AtArgumentExpression) {
5332 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5333 NumSelIdents);
5334 if (PreferredType.isNull())
5335 CodeCompleteOrdinaryName(S, PCC_Expression);
5336 else
5337 CodeCompleteExpression(S, PreferredType);
5338 return;
5339 }
5340
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005341 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005342 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005343 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005344}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005345
Douglas Gregorfb629412010-08-23 21:17:50 +00005346void Sema::CodeCompleteObjCForCollection(Scope *S,
5347 DeclGroupPtrTy IterationVar) {
5348 CodeCompleteExpressionData Data;
5349 Data.ObjCCollection = true;
5350
5351 if (IterationVar.getAsOpaquePtr()) {
5352 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5353 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5354 if (*I)
5355 Data.IgnoreDecls.push_back(*I);
5356 }
5357 }
5358
5359 CodeCompleteExpression(S, Data);
5360}
5361
Douglas Gregor458433d2010-08-26 15:07:07 +00005362void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5363 unsigned NumSelIdents) {
5364 // If we have an external source, load the entire class method
5365 // pool from the AST file.
5366 if (ExternalSource) {
5367 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5368 I != N; ++I) {
5369 Selector Sel = ExternalSource->GetExternalSelector(I);
5370 if (Sel.isNull() || MethodPool.count(Sel))
5371 continue;
5372
5373 ReadMethodPool(Sel);
5374 }
5375 }
5376
Douglas Gregor218937c2011-02-01 19:23:04 +00005377 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5378 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005379 Results.EnterNewScope();
5380 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5381 MEnd = MethodPool.end();
5382 M != MEnd; ++M) {
5383
5384 Selector Sel = M->first;
5385 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5386 continue;
5387
Douglas Gregor218937c2011-02-01 19:23:04 +00005388 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005389 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005390 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005391 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005392 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005393 continue;
5394 }
5395
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005396 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005397 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005398 if (I == NumSelIdents) {
5399 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005400 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005401 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005402 Accumulator.clear();
5403 }
5404 }
5405
Benjamin Kramera0651c52011-07-26 16:59:25 +00005406 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005407 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005408 }
Douglas Gregordae68752011-02-01 22:57:45 +00005409 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005410 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005411 }
5412 Results.ExitScope();
5413
5414 HandleCodeCompleteResults(this, CodeCompleter,
5415 CodeCompletionContext::CCC_SelectorName,
5416 Results.data(), Results.size());
5417}
5418
Douglas Gregor55385fe2009-11-18 04:19:12 +00005419/// \brief Add all of the protocol declarations that we find in the given
5420/// (translation unit) context.
5421static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005422 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005423 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005424 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005425
5426 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5427 DEnd = Ctx->decls_end();
5428 D != DEnd; ++D) {
5429 // Record any protocols we find.
5430 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005431 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregor608300b2010-01-14 16:14:35 +00005432 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005433 }
5434}
5435
5436void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5437 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5439 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005440
Douglas Gregor70c23352010-12-09 21:44:02 +00005441 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5442 Results.EnterNewScope();
5443
5444 // Tell the result set to ignore all of the protocols we have
5445 // already seen.
5446 // FIXME: This doesn't work when caching code-completion results.
5447 for (unsigned I = 0; I != NumProtocols; ++I)
5448 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5449 Protocols[I].second))
5450 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005451
Douglas Gregor70c23352010-12-09 21:44:02 +00005452 // Add all protocols.
5453 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5454 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005455
Douglas Gregor70c23352010-12-09 21:44:02 +00005456 Results.ExitScope();
5457 }
5458
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005459 HandleCodeCompleteResults(this, CodeCompleter,
5460 CodeCompletionContext::CCC_ObjCProtocolName,
5461 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005462}
5463
5464void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005465 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5466 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005467
Douglas Gregor70c23352010-12-09 21:44:02 +00005468 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5469 Results.EnterNewScope();
5470
5471 // Add all protocols.
5472 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5473 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005474
Douglas Gregor70c23352010-12-09 21:44:02 +00005475 Results.ExitScope();
5476 }
5477
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005478 HandleCodeCompleteResults(this, CodeCompleter,
5479 CodeCompletionContext::CCC_ObjCProtocolName,
5480 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005481}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005482
5483/// \brief Add all of the Objective-C interface declarations that we find in
5484/// the given (translation unit) context.
5485static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5486 bool OnlyForwardDeclarations,
5487 bool OnlyUnimplemented,
5488 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005489 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005490
5491 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5492 DEnd = Ctx->decls_end();
5493 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005494 // Record any interfaces we find.
5495 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregor7723fec2011-12-15 20:29:51 +00005496 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005497 (!OnlyUnimplemented || !Class->getImplementation()))
5498 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005499 }
5500}
5501
5502void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005503 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5504 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005505 Results.EnterNewScope();
5506
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005507 if (CodeCompleter->includeGlobals()) {
5508 // Add all classes.
5509 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5510 false, Results);
5511 }
5512
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005513 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005514
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005515 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005516 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005517 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005518}
5519
Douglas Gregorc83c6872010-04-15 22:33:43 +00005520void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5521 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005522 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005523 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005524 Results.EnterNewScope();
5525
5526 // Make sure that we ignore the class we're currently defining.
5527 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005528 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005529 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005530 Results.Ignore(CurClass);
5531
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005532 if (CodeCompleter->includeGlobals()) {
5533 // Add all classes.
5534 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5535 false, Results);
5536 }
5537
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005538 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005539
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005540 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005541 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005542 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005543}
5544
5545void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005546 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5547 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005548 Results.EnterNewScope();
5549
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005550 if (CodeCompleter->includeGlobals()) {
5551 // Add all unimplemented classes.
5552 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5553 true, Results);
5554 }
5555
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005556 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005557
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005558 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005559 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005560 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005561}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005562
5563void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005564 IdentifierInfo *ClassName,
5565 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005566 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005567
Douglas Gregor218937c2011-02-01 19:23:04 +00005568 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005569 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005570
5571 // Ignore any categories we find that have already been implemented by this
5572 // interface.
5573 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5574 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005575 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005576 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5577 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5578 Category = Category->getNextClassCategory())
5579 CategoryNames.insert(Category->getIdentifier());
5580
5581 // Add all of the categories we know about.
5582 Results.EnterNewScope();
5583 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5584 for (DeclContext::decl_iterator D = TU->decls_begin(),
5585 DEnd = TU->decls_end();
5586 D != DEnd; ++D)
5587 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5588 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005589 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005590 Results.ExitScope();
5591
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005592 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005593 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005594 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005595}
5596
5597void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005598 IdentifierInfo *ClassName,
5599 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005600 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005601
5602 // Find the corresponding interface. If we couldn't find the interface, the
5603 // program itself is ill-formed. However, we'll try to be helpful still by
5604 // providing the list of all of the categories we know about.
5605 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005606 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005607 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5608 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005609 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005610
Douglas Gregor218937c2011-02-01 19:23:04 +00005611 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005612 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005613
5614 // Add all of the categories that have have corresponding interface
5615 // declarations in this class and any of its superclasses, except for
5616 // already-implemented categories in the class itself.
5617 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5618 Results.EnterNewScope();
5619 bool IgnoreImplemented = true;
5620 while (Class) {
5621 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5622 Category = Category->getNextClassCategory())
5623 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5624 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005625 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005626
5627 Class = Class->getSuperClass();
5628 IgnoreImplemented = false;
5629 }
5630 Results.ExitScope();
5631
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005632 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005633 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005634 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005635}
Douglas Gregor322328b2009-11-18 22:32:06 +00005636
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005637void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005638 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005639 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5640 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005641
5642 // Figure out where this @synthesize lives.
5643 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005644 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005645 if (!Container ||
5646 (!isa<ObjCImplementationDecl>(Container) &&
5647 !isa<ObjCCategoryImplDecl>(Container)))
5648 return;
5649
5650 // Ignore any properties that have already been implemented.
5651 for (DeclContext::decl_iterator D = Container->decls_begin(),
5652 DEnd = Container->decls_end();
5653 D != DEnd; ++D)
5654 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5655 Results.Ignore(PropertyImpl->getPropertyDecl());
5656
5657 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005658 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005659 Results.EnterNewScope();
5660 if (ObjCImplementationDecl *ClassImpl
5661 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005662 AddObjCProperties(ClassImpl->getClassInterface(), false,
5663 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005664 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005665 else
5666 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005667 false, /*AllowNullaryMethods=*/false, CurContext,
5668 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005669 Results.ExitScope();
5670
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005671 HandleCodeCompleteResults(this, CodeCompleter,
5672 CodeCompletionContext::CCC_Other,
5673 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005674}
5675
5676void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005677 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005678 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005679 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5680 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005681
5682 // Figure out where this @synthesize lives.
5683 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005684 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005685 if (!Container ||
5686 (!isa<ObjCImplementationDecl>(Container) &&
5687 !isa<ObjCCategoryImplDecl>(Container)))
5688 return;
5689
5690 // Figure out which interface we're looking into.
5691 ObjCInterfaceDecl *Class = 0;
5692 if (ObjCImplementationDecl *ClassImpl
5693 = dyn_cast<ObjCImplementationDecl>(Container))
5694 Class = ClassImpl->getClassInterface();
5695 else
5696 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5697 ->getClassInterface();
5698
Douglas Gregore8426052011-04-18 14:40:46 +00005699 // Determine the type of the property we're synthesizing.
5700 QualType PropertyType = Context.getObjCIdType();
5701 if (Class) {
5702 if (ObjCPropertyDecl *Property
5703 = Class->FindPropertyDeclaration(PropertyName)) {
5704 PropertyType
5705 = Property->getType().getNonReferenceType().getUnqualifiedType();
5706
5707 // Give preference to ivars
5708 Results.setPreferredType(PropertyType);
5709 }
5710 }
5711
Douglas Gregor322328b2009-11-18 22:32:06 +00005712 // Add all of the instance variables in this class and its superclasses.
5713 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005714 bool SawSimilarlyNamedIvar = false;
5715 std::string NameWithPrefix;
5716 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005717 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005718 std::string NameWithSuffix = PropertyName->getName().str();
5719 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005720 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005721 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5722 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005723 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5724
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005725 // Determine whether we've seen an ivar with a name similar to the
5726 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005727 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005728 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005729 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005730 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005731
5732 // Reduce the priority of this result by one, to give it a slight
5733 // advantage over other results whose names don't match so closely.
5734 if (Results.size() &&
5735 Results.data()[Results.size() - 1].Kind
5736 == CodeCompletionResult::RK_Declaration &&
5737 Results.data()[Results.size() - 1].Declaration == Ivar)
5738 Results.data()[Results.size() - 1].Priority--;
5739 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005740 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005741 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005742
5743 if (!SawSimilarlyNamedIvar) {
5744 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005745 // an ivar of the appropriate type.
5746 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005747 typedef CodeCompletionResult Result;
5748 CodeCompletionAllocator &Allocator = Results.getAllocator();
5749 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5750
Douglas Gregor8987b232011-09-27 23:30:47 +00005751 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005752 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005753 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005754 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5755 Results.AddResult(Result(Builder.TakeString(), Priority,
5756 CXCursor_ObjCIvarDecl));
5757 }
5758
Douglas Gregor322328b2009-11-18 22:32:06 +00005759 Results.ExitScope();
5760
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005761 HandleCodeCompleteResults(this, CodeCompleter,
5762 CodeCompletionContext::CCC_Other,
5763 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005764}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005765
Douglas Gregor408be5a2010-08-25 01:08:01 +00005766// Mapping from selectors to the methods that implement that selector, along
5767// with the "in original class" flag.
5768typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5769 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005770
5771/// \brief Find all of the methods that reside in the given container
5772/// (and its superclasses, protocols, etc.) that meet the given
5773/// criteria. Insert those methods into the map of known methods,
5774/// indexed by selector so they can be easily found.
5775static void FindImplementableMethods(ASTContext &Context,
5776 ObjCContainerDecl *Container,
5777 bool WantInstanceMethods,
5778 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005779 KnownMethodsMap &KnownMethods,
5780 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005781 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5782 // Recurse into protocols.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00005783 if (!IFace->hasDefinition())
5784 return;
5785
Douglas Gregore8f5a172010-04-07 00:21:17 +00005786 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)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005826 if (Protocol->hasDefinition()) {
5827 // Recurse into protocols.
5828 const ObjCList<ObjCProtocolDecl> &Protocols
5829 = Protocol->getReferencedProtocols();
5830 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5831 E = Protocols.end();
5832 I != E; ++I)
5833 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5834 KnownMethods, false);
5835 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005836 }
5837
5838 // Add methods in this container. This operation occurs last because
5839 // we want the methods from this container to override any methods
5840 // we've previously seen with the same selector.
5841 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5842 MEnd = Container->meth_end();
5843 M != MEnd; ++M) {
5844 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5845 if (!ReturnType.isNull() &&
5846 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5847 continue;
5848
Douglas Gregor408be5a2010-08-25 01:08:01 +00005849 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005850 }
5851 }
5852}
5853
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005854/// \brief Add the parenthesized return or parameter type chunk to a code
5855/// completion string.
5856static void AddObjCPassingTypeChunk(QualType Type,
5857 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005858 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005859 CodeCompletionBuilder &Builder) {
5860 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005861 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005862 Builder.getAllocator()));
5863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5864}
5865
5866/// \brief Determine whether the given class is or inherits from a class by
5867/// the given name.
5868static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005869 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005870 if (!Class)
5871 return false;
5872
5873 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5874 return true;
5875
5876 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5877}
5878
5879/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5880/// Key-Value Observing (KVO).
5881static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5882 bool IsInstanceMethod,
5883 QualType ReturnType,
5884 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005885 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005886 ResultBuilder &Results) {
5887 IdentifierInfo *PropName = Property->getIdentifier();
5888 if (!PropName || PropName->getLength() == 0)
5889 return;
5890
Douglas Gregor8987b232011-09-27 23:30:47 +00005891 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5892
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005893 // Builder that will create each code completion.
5894 typedef CodeCompletionResult Result;
5895 CodeCompletionAllocator &Allocator = Results.getAllocator();
5896 CodeCompletionBuilder Builder(Allocator);
5897
5898 // The selector table.
5899 SelectorTable &Selectors = Context.Selectors;
5900
5901 // The property name, copied into the code completion allocation region
5902 // on demand.
5903 struct KeyHolder {
5904 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005905 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005906 const char *CopiedKey;
5907
Chris Lattner5f9e2722011-07-23 10:55:15 +00005908 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005909 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5910
5911 operator const char *() {
5912 if (CopiedKey)
5913 return CopiedKey;
5914
5915 return CopiedKey = Allocator.CopyString(Key);
5916 }
5917 } Key(Allocator, PropName->getName());
5918
5919 // The uppercased name of the property name.
5920 std::string UpperKey = PropName->getName();
5921 if (!UpperKey.empty())
5922 UpperKey[0] = toupper(UpperKey[0]);
5923
5924 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5925 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5926 Property->getType());
5927 bool ReturnTypeMatchesVoid
5928 = ReturnType.isNull() || ReturnType->isVoidType();
5929
5930 // Add the normal accessor -(type)key.
5931 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005932 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005933 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5934 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005935 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005936
5937 Builder.AddTypedTextChunk(Key);
5938 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5939 CXCursor_ObjCInstanceMethodDecl));
5940 }
5941
5942 // If we have an integral or boolean property (or the user has provided
5943 // an integral or boolean return type), add the accessor -(type)isKey.
5944 if (IsInstanceMethod &&
5945 ((!ReturnType.isNull() &&
5946 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5947 (ReturnType.isNull() &&
5948 (Property->getType()->isIntegerType() ||
5949 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005950 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005951 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005952 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005953 if (ReturnType.isNull()) {
5954 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5955 Builder.AddTextChunk("BOOL");
5956 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5957 }
5958
5959 Builder.AddTypedTextChunk(
5960 Allocator.CopyString(SelectorId->getName()));
5961 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5962 CXCursor_ObjCInstanceMethodDecl));
5963 }
5964 }
5965
5966 // Add the normal mutator.
5967 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5968 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005969 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005970 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005971 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005972 if (ReturnType.isNull()) {
5973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5974 Builder.AddTextChunk("void");
5975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5976 }
5977
5978 Builder.AddTypedTextChunk(
5979 Allocator.CopyString(SelectorId->getName()));
5980 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005981 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005982 Builder.AddTextChunk(Key);
5983 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5984 CXCursor_ObjCInstanceMethodDecl));
5985 }
5986 }
5987
5988 // Indexed and unordered accessors
5989 unsigned IndexedGetterPriority = CCP_CodePattern;
5990 unsigned IndexedSetterPriority = CCP_CodePattern;
5991 unsigned UnorderedGetterPriority = CCP_CodePattern;
5992 unsigned UnorderedSetterPriority = CCP_CodePattern;
5993 if (const ObjCObjectPointerType *ObjCPointer
5994 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5995 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5996 // If this interface type is not provably derived from a known
5997 // collection, penalize the corresponding completions.
5998 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5999 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6000 if (!InheritsFromClassNamed(IFace, "NSArray"))
6001 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6002 }
6003
6004 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6005 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6006 if (!InheritsFromClassNamed(IFace, "NSSet"))
6007 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6008 }
6009 }
6010 } else {
6011 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6012 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6013 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6014 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6015 }
6016
6017 // Add -(NSUInteger)countOf<key>
6018 if (IsInstanceMethod &&
6019 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006020 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006021 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006022 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006023 if (ReturnType.isNull()) {
6024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6025 Builder.AddTextChunk("NSUInteger");
6026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6027 }
6028
6029 Builder.AddTypedTextChunk(
6030 Allocator.CopyString(SelectorId->getName()));
6031 Results.AddResult(Result(Builder.TakeString(),
6032 std::min(IndexedGetterPriority,
6033 UnorderedGetterPriority),
6034 CXCursor_ObjCInstanceMethodDecl));
6035 }
6036 }
6037
6038 // Indexed getters
6039 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6040 if (IsInstanceMethod &&
6041 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006042 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006043 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006044 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006045 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006046 if (ReturnType.isNull()) {
6047 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6048 Builder.AddTextChunk("id");
6049 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6050 }
6051
6052 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6053 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6054 Builder.AddTextChunk("NSUInteger");
6055 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6056 Builder.AddTextChunk("index");
6057 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6058 CXCursor_ObjCInstanceMethodDecl));
6059 }
6060 }
6061
6062 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6063 if (IsInstanceMethod &&
6064 (ReturnType.isNull() ||
6065 (ReturnType->isObjCObjectPointerType() &&
6066 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6067 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6068 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006069 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006070 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006071 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006072 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006073 if (ReturnType.isNull()) {
6074 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6075 Builder.AddTextChunk("NSArray *");
6076 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6077 }
6078
6079 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6080 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6081 Builder.AddTextChunk("NSIndexSet *");
6082 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6083 Builder.AddTextChunk("indexes");
6084 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6085 CXCursor_ObjCInstanceMethodDecl));
6086 }
6087 }
6088
6089 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6090 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006091 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006092 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006093 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006094 &Context.Idents.get("range")
6095 };
6096
Douglas Gregore74c25c2011-05-04 23:50:46 +00006097 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006098 if (ReturnType.isNull()) {
6099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6100 Builder.AddTextChunk("void");
6101 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6102 }
6103
6104 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6105 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6106 Builder.AddPlaceholderChunk("object-type");
6107 Builder.AddTextChunk(" **");
6108 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6109 Builder.AddTextChunk("buffer");
6110 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6111 Builder.AddTypedTextChunk("range:");
6112 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6113 Builder.AddTextChunk("NSRange");
6114 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6115 Builder.AddTextChunk("inRange");
6116 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6117 CXCursor_ObjCInstanceMethodDecl));
6118 }
6119 }
6120
6121 // Mutable indexed accessors
6122
6123 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6124 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006125 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006126 IdentifierInfo *SelectorIds[2] = {
6127 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006128 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006129 };
6130
Douglas Gregore74c25c2011-05-04 23:50:46 +00006131 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006132 if (ReturnType.isNull()) {
6133 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6134 Builder.AddTextChunk("void");
6135 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6136 }
6137
6138 Builder.AddTypedTextChunk("insertObject:");
6139 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6140 Builder.AddPlaceholderChunk("object-type");
6141 Builder.AddTextChunk(" *");
6142 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6143 Builder.AddTextChunk("object");
6144 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6145 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6146 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6147 Builder.AddPlaceholderChunk("NSUInteger");
6148 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6149 Builder.AddTextChunk("index");
6150 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6151 CXCursor_ObjCInstanceMethodDecl));
6152 }
6153 }
6154
6155 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6156 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006157 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006158 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006159 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006160 &Context.Idents.get("atIndexes")
6161 };
6162
Douglas Gregore74c25c2011-05-04 23:50:46 +00006163 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006164 if (ReturnType.isNull()) {
6165 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6166 Builder.AddTextChunk("void");
6167 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6168 }
6169
6170 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6171 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6172 Builder.AddTextChunk("NSArray *");
6173 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6174 Builder.AddTextChunk("array");
6175 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6176 Builder.AddTypedTextChunk("atIndexes:");
6177 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6178 Builder.AddPlaceholderChunk("NSIndexSet *");
6179 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6180 Builder.AddTextChunk("indexes");
6181 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6182 CXCursor_ObjCInstanceMethodDecl));
6183 }
6184 }
6185
6186 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6187 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006188 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006189 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006190 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006191 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006192 if (ReturnType.isNull()) {
6193 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6194 Builder.AddTextChunk("void");
6195 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6196 }
6197
6198 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6199 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6200 Builder.AddTextChunk("NSUInteger");
6201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6202 Builder.AddTextChunk("index");
6203 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6204 CXCursor_ObjCInstanceMethodDecl));
6205 }
6206 }
6207
6208 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6209 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006210 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006211 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006212 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006213 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006214 if (ReturnType.isNull()) {
6215 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6216 Builder.AddTextChunk("void");
6217 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6218 }
6219
6220 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6221 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6222 Builder.AddTextChunk("NSIndexSet *");
6223 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6224 Builder.AddTextChunk("indexes");
6225 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6226 CXCursor_ObjCInstanceMethodDecl));
6227 }
6228 }
6229
6230 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6231 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006232 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006233 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006234 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006235 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006236 &Context.Idents.get("withObject")
6237 };
6238
Douglas Gregore74c25c2011-05-04 23:50:46 +00006239 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006240 if (ReturnType.isNull()) {
6241 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6242 Builder.AddTextChunk("void");
6243 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6244 }
6245
6246 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6247 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6248 Builder.AddPlaceholderChunk("NSUInteger");
6249 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6250 Builder.AddTextChunk("index");
6251 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6252 Builder.AddTypedTextChunk("withObject:");
6253 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6254 Builder.AddTextChunk("id");
6255 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6256 Builder.AddTextChunk("object");
6257 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6258 CXCursor_ObjCInstanceMethodDecl));
6259 }
6260 }
6261
6262 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6263 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006264 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006265 = (Twine("replace") + UpperKey + "AtIndexes").str();
6266 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006267 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006268 &Context.Idents.get(SelectorName1),
6269 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006270 };
6271
Douglas Gregore74c25c2011-05-04 23:50:46 +00006272 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006273 if (ReturnType.isNull()) {
6274 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6275 Builder.AddTextChunk("void");
6276 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6277 }
6278
6279 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6280 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6281 Builder.AddPlaceholderChunk("NSIndexSet *");
6282 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6283 Builder.AddTextChunk("indexes");
6284 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6285 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6286 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6287 Builder.AddTextChunk("NSArray *");
6288 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6289 Builder.AddTextChunk("array");
6290 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6291 CXCursor_ObjCInstanceMethodDecl));
6292 }
6293 }
6294
6295 // Unordered getters
6296 // - (NSEnumerator *)enumeratorOfKey
6297 if (IsInstanceMethod &&
6298 (ReturnType.isNull() ||
6299 (ReturnType->isObjCObjectPointerType() &&
6300 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6301 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6302 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006303 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006304 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006305 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006306 if (ReturnType.isNull()) {
6307 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6308 Builder.AddTextChunk("NSEnumerator *");
6309 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6310 }
6311
6312 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6313 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6314 CXCursor_ObjCInstanceMethodDecl));
6315 }
6316 }
6317
6318 // - (type *)memberOfKey:(type *)object
6319 if (IsInstanceMethod &&
6320 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006321 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006322 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006323 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006324 if (ReturnType.isNull()) {
6325 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6326 Builder.AddPlaceholderChunk("object-type");
6327 Builder.AddTextChunk(" *");
6328 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6329 }
6330
6331 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6333 if (ReturnType.isNull()) {
6334 Builder.AddPlaceholderChunk("object-type");
6335 Builder.AddTextChunk(" *");
6336 } else {
6337 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006338 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006339 Builder.getAllocator()));
6340 }
6341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6342 Builder.AddTextChunk("object");
6343 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6344 CXCursor_ObjCInstanceMethodDecl));
6345 }
6346 }
6347
6348 // Mutable unordered accessors
6349 // - (void)addKeyObject:(type *)object
6350 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006351 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006352 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006353 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006354 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006355 if (ReturnType.isNull()) {
6356 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6357 Builder.AddTextChunk("void");
6358 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6359 }
6360
6361 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6362 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6363 Builder.AddPlaceholderChunk("object-type");
6364 Builder.AddTextChunk(" *");
6365 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6366 Builder.AddTextChunk("object");
6367 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6368 CXCursor_ObjCInstanceMethodDecl));
6369 }
6370 }
6371
6372 // - (void)addKey:(NSSet *)objects
6373 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006374 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006375 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006376 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006377 if (ReturnType.isNull()) {
6378 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6379 Builder.AddTextChunk("void");
6380 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6381 }
6382
6383 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6384 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6385 Builder.AddTextChunk("NSSet *");
6386 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6387 Builder.AddTextChunk("objects");
6388 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6389 CXCursor_ObjCInstanceMethodDecl));
6390 }
6391 }
6392
6393 // - (void)removeKeyObject:(type *)object
6394 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006395 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006396 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006397 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006398 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006399 if (ReturnType.isNull()) {
6400 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6401 Builder.AddTextChunk("void");
6402 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6403 }
6404
6405 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6406 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6407 Builder.AddPlaceholderChunk("object-type");
6408 Builder.AddTextChunk(" *");
6409 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6410 Builder.AddTextChunk("object");
6411 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6412 CXCursor_ObjCInstanceMethodDecl));
6413 }
6414 }
6415
6416 // - (void)removeKey:(NSSet *)objects
6417 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006418 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006419 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006420 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006421 if (ReturnType.isNull()) {
6422 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6423 Builder.AddTextChunk("void");
6424 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6425 }
6426
6427 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6428 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6429 Builder.AddTextChunk("NSSet *");
6430 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6431 Builder.AddTextChunk("objects");
6432 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6433 CXCursor_ObjCInstanceMethodDecl));
6434 }
6435 }
6436
6437 // - (void)intersectKey:(NSSet *)objects
6438 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006439 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006440 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006441 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006442 if (ReturnType.isNull()) {
6443 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6444 Builder.AddTextChunk("void");
6445 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6446 }
6447
6448 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6449 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6450 Builder.AddTextChunk("NSSet *");
6451 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6452 Builder.AddTextChunk("objects");
6453 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6454 CXCursor_ObjCInstanceMethodDecl));
6455 }
6456 }
6457
6458 // Key-Value Observing
6459 // + (NSSet *)keyPathsForValuesAffectingKey
6460 if (!IsInstanceMethod &&
6461 (ReturnType.isNull() ||
6462 (ReturnType->isObjCObjectPointerType() &&
6463 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6464 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6465 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006466 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006467 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006468 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006469 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006470 if (ReturnType.isNull()) {
6471 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6472 Builder.AddTextChunk("NSSet *");
6473 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6474 }
6475
6476 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6477 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006478 CXCursor_ObjCClassMethodDecl));
6479 }
6480 }
6481
6482 // + (BOOL)automaticallyNotifiesObserversForKey
6483 if (!IsInstanceMethod &&
6484 (ReturnType.isNull() ||
6485 ReturnType->isIntegerType() ||
6486 ReturnType->isBooleanType())) {
6487 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006488 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006489 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6490 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6491 if (ReturnType.isNull()) {
6492 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6493 Builder.AddTextChunk("BOOL");
6494 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6495 }
6496
6497 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6498 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6499 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006500 }
6501 }
6502}
6503
Douglas Gregore8f5a172010-04-07 00:21:17 +00006504void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6505 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006506 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006507 // Determine the return type of the method we're declaring, if
6508 // provided.
6509 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006510 Decl *IDecl = 0;
6511 if (CurContext->isObjCContainer()) {
6512 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6513 IDecl = cast<Decl>(OCD);
6514 }
Douglas Gregorea766182010-10-18 18:21:28 +00006515 // Determine where we should start searching for methods.
6516 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006517 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006518 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006519 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6520 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006521 IsInImplementation = true;
6522 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006523 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006525 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006526 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006527 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006528 }
6529
6530 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006531 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006532 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006533 }
6534
Douglas Gregorea766182010-10-18 18:21:28 +00006535 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006536 HandleCodeCompleteResults(this, CodeCompleter,
6537 CodeCompletionContext::CCC_Other,
6538 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006539 return;
6540 }
6541
6542 // Find all of the methods that we could declare/implement here.
6543 KnownMethodsMap KnownMethods;
6544 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006545 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006546
Douglas Gregore8f5a172010-04-07 00:21:17 +00006547 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006548 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006549 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6550 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006551 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006552 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006553 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6554 MEnd = KnownMethods.end();
6555 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006556 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006557 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006558
6559 // If the result type was not already provided, add it to the
6560 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006561 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006562 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6563 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006564
6565 Selector Sel = Method->getSelector();
6566
6567 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006568 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006569 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006570
6571 // Add parameters to the pattern.
6572 unsigned I = 0;
6573 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6574 PEnd = Method->param_end();
6575 P != PEnd; (void)++P, ++I) {
6576 // Add the part of the selector name.
6577 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006578 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006579 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006580 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6581 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006582 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006583 } else
6584 break;
6585
6586 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006587 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6588 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006589
6590 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006591 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006592 }
6593
6594 if (Method->isVariadic()) {
6595 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006596 Builder.AddChunk(CodeCompletionString::CK_Comma);
6597 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006598 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006599
Douglas Gregor447107d2010-05-28 00:57:46 +00006600 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006601 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006602 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6603 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6604 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006605 if (!Method->getResultType()->isVoidType()) {
6606 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006607 Builder.AddTextChunk("return");
6608 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6609 Builder.AddPlaceholderChunk("expression");
6610 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006611 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006612 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006613
Douglas Gregor218937c2011-02-01 19:23:04 +00006614 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6615 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006616 }
6617
Douglas Gregor408be5a2010-08-25 01:08:01 +00006618 unsigned Priority = CCP_CodePattern;
6619 if (!M->second.second)
6620 Priority += CCD_InBaseClass;
6621
Douglas Gregor218937c2011-02-01 19:23:04 +00006622 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006623 Method->isInstanceMethod()
6624 ? CXCursor_ObjCInstanceMethodDecl
6625 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006626 }
6627
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006628 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6629 // the properties in this class and its categories.
6630 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006631 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006632 Containers.push_back(SearchDecl);
6633
Douglas Gregore74c25c2011-05-04 23:50:46 +00006634 VisitedSelectorSet KnownSelectors;
6635 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6636 MEnd = KnownMethods.end();
6637 M != MEnd; ++M)
6638 KnownSelectors.insert(M->first);
6639
6640
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006641 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6642 if (!IFace)
6643 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6644 IFace = Category->getClassInterface();
6645
6646 if (IFace) {
6647 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6648 Category = Category->getNextClassCategory())
6649 Containers.push_back(Category);
6650 }
6651
6652 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6653 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6654 PEnd = Containers[I]->prop_end();
6655 P != PEnd; ++P) {
6656 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006657 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006658 }
6659 }
6660 }
6661
Douglas Gregore8f5a172010-04-07 00:21:17 +00006662 Results.ExitScope();
6663
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006664 HandleCodeCompleteResults(this, CodeCompleter,
6665 CodeCompletionContext::CCC_Other,
6666 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006667}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006668
6669void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6670 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006671 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006672 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006673 IdentifierInfo **SelIdents,
6674 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006675 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006676 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006677 if (ExternalSource) {
6678 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6679 I != N; ++I) {
6680 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006681 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006682 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006683
6684 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006685 }
6686 }
6687
6688 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006689 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006690 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6691 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006692
6693 if (ReturnTy)
6694 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006695
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006696 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006697 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6698 MEnd = MethodPool.end();
6699 M != MEnd; ++M) {
6700 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6701 &M->second.second;
6702 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006703 MethList = MethList->Next) {
6704 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6705 NumSelIdents))
6706 continue;
6707
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006708 if (AtParameterName) {
6709 // Suggest parameter names we've seen before.
6710 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6711 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6712 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006713 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006714 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006715 Param->getIdentifier()->getName()));
6716 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006717 }
6718 }
6719
6720 continue;
6721 }
6722
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006723 Result R(MethList->Method, 0);
6724 R.StartParameter = NumSelIdents;
6725 R.AllParametersAreInformative = false;
6726 R.DeclaringEntity = true;
6727 Results.MaybeAddResult(R, CurContext);
6728 }
6729 }
6730
6731 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006732 HandleCodeCompleteResults(this, CodeCompleter,
6733 CodeCompletionContext::CCC_Other,
6734 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006735}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006736
Douglas Gregorf29c5232010-08-24 22:20:20 +00006737void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006738 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006739 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006740 Results.EnterNewScope();
6741
6742 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006743 CodeCompletionBuilder Builder(Results.getAllocator());
6744 Builder.AddTypedTextChunk("if");
6745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6746 Builder.AddPlaceholderChunk("condition");
6747 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006748
6749 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006750 Builder.AddTypedTextChunk("ifdef");
6751 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6752 Builder.AddPlaceholderChunk("macro");
6753 Results.AddResult(Builder.TakeString());
6754
Douglas Gregorf44e8542010-08-24 19:08:16 +00006755 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006756 Builder.AddTypedTextChunk("ifndef");
6757 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6758 Builder.AddPlaceholderChunk("macro");
6759 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006760
6761 if (InConditional) {
6762 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006763 Builder.AddTypedTextChunk("elif");
6764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6765 Builder.AddPlaceholderChunk("condition");
6766 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006767
6768 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006769 Builder.AddTypedTextChunk("else");
6770 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006771
6772 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006773 Builder.AddTypedTextChunk("endif");
6774 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006775 }
6776
6777 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006778 Builder.AddTypedTextChunk("include");
6779 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6780 Builder.AddTextChunk("\"");
6781 Builder.AddPlaceholderChunk("header");
6782 Builder.AddTextChunk("\"");
6783 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006784
6785 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006786 Builder.AddTypedTextChunk("include");
6787 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6788 Builder.AddTextChunk("<");
6789 Builder.AddPlaceholderChunk("header");
6790 Builder.AddTextChunk(">");
6791 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006792
6793 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006794 Builder.AddTypedTextChunk("define");
6795 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6796 Builder.AddPlaceholderChunk("macro");
6797 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006798
6799 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006800 Builder.AddTypedTextChunk("define");
6801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6802 Builder.AddPlaceholderChunk("macro");
6803 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6804 Builder.AddPlaceholderChunk("args");
6805 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6806 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006807
6808 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006809 Builder.AddTypedTextChunk("undef");
6810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6811 Builder.AddPlaceholderChunk("macro");
6812 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006813
6814 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006815 Builder.AddTypedTextChunk("line");
6816 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6817 Builder.AddPlaceholderChunk("number");
6818 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006819
6820 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006821 Builder.AddTypedTextChunk("line");
6822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6823 Builder.AddPlaceholderChunk("number");
6824 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6825 Builder.AddTextChunk("\"");
6826 Builder.AddPlaceholderChunk("filename");
6827 Builder.AddTextChunk("\"");
6828 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006829
6830 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006831 Builder.AddTypedTextChunk("error");
6832 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6833 Builder.AddPlaceholderChunk("message");
6834 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006835
6836 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006837 Builder.AddTypedTextChunk("pragma");
6838 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6839 Builder.AddPlaceholderChunk("arguments");
6840 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006841
6842 if (getLangOptions().ObjC1) {
6843 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006844 Builder.AddTypedTextChunk("import");
6845 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6846 Builder.AddTextChunk("\"");
6847 Builder.AddPlaceholderChunk("header");
6848 Builder.AddTextChunk("\"");
6849 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006850
6851 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006852 Builder.AddTypedTextChunk("import");
6853 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6854 Builder.AddTextChunk("<");
6855 Builder.AddPlaceholderChunk("header");
6856 Builder.AddTextChunk(">");
6857 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006858 }
6859
6860 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006861 Builder.AddTypedTextChunk("include_next");
6862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6863 Builder.AddTextChunk("\"");
6864 Builder.AddPlaceholderChunk("header");
6865 Builder.AddTextChunk("\"");
6866 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006867
6868 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006869 Builder.AddTypedTextChunk("include_next");
6870 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6871 Builder.AddTextChunk("<");
6872 Builder.AddPlaceholderChunk("header");
6873 Builder.AddTextChunk(">");
6874 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006875
6876 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006877 Builder.AddTypedTextChunk("warning");
6878 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6879 Builder.AddPlaceholderChunk("message");
6880 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006881
6882 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6883 // completions for them. And __include_macros is a Clang-internal extension
6884 // that we don't want to encourage anyone to use.
6885
6886 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6887 Results.ExitScope();
6888
Douglas Gregorf44e8542010-08-24 19:08:16 +00006889 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006890 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006891 Results.data(), Results.size());
6892}
6893
6894void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006895 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006896 S->getFnParent()? Sema::PCC_RecoveryInFunction
6897 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006898}
6899
Douglas Gregorf29c5232010-08-24 22:20:20 +00006900void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006902 IsDefinition? CodeCompletionContext::CCC_MacroName
6903 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006904 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6905 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006906 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006907 Results.EnterNewScope();
6908 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6909 MEnd = PP.macro_end();
6910 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006911 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006912 M->first->getName()));
6913 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006914 }
6915 Results.ExitScope();
6916 } else if (IsDefinition) {
6917 // FIXME: Can we detect when the user just wrote an include guard above?
6918 }
6919
Douglas Gregor52779fb2010-09-23 23:01:17 +00006920 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006921 Results.data(), Results.size());
6922}
6923
Douglas Gregorf29c5232010-08-24 22:20:20 +00006924void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006925 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006926 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006927
6928 if (!CodeCompleter || CodeCompleter->includeMacros())
6929 AddMacroResults(PP, Results);
6930
6931 // defined (<macro>)
6932 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006933 CodeCompletionBuilder Builder(Results.getAllocator());
6934 Builder.AddTypedTextChunk("defined");
6935 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6936 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6937 Builder.AddPlaceholderChunk("macro");
6938 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6939 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006940 Results.ExitScope();
6941
6942 HandleCodeCompleteResults(this, CodeCompleter,
6943 CodeCompletionContext::CCC_PreprocessorExpression,
6944 Results.data(), Results.size());
6945}
6946
6947void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6948 IdentifierInfo *Macro,
6949 MacroInfo *MacroInfo,
6950 unsigned Argument) {
6951 // FIXME: In the future, we could provide "overload" results, much like we
6952 // do for function calls.
6953
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006954 // Now just ignore this. There will be another code-completion callback
6955 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006956}
6957
Douglas Gregor55817af2010-08-25 17:04:25 +00006958void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006959 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006960 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006961 0, 0);
6962}
6963
Douglas Gregordae68752011-02-01 22:57:45 +00006964void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006965 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006966 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006967 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6968 CodeCompletionDeclConsumer Consumer(Builder,
6969 Context.getTranslationUnitDecl());
6970 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6971 Consumer);
6972 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006973
6974 if (!CodeCompleter || CodeCompleter->includeMacros())
6975 AddMacroResults(PP, Builder);
6976
6977 Results.clear();
6978 Results.insert(Results.end(),
6979 Builder.data(), Builder.data() + Builder.size());
6980}