blob: 69b38593fbfd76233f45d0fd2174ca29d68b5d55 [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
65
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
437 llvm::SmallVector<DeclContext *, 4> TargetParents;
438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
993 if (isa<ObjCPropertyDecl>(ND) &&
994 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
995 return true;
996 }
997
Douglas Gregor791215b2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// ordinary name lookup but is not a type name.
1003bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1004 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1005 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 return false;
1007
1008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 else if (SemaRef.getLangOptions().ObjC1) {
1012 if (isa<ObjCIvarDecl>(ND))
1013 return true;
1014 if (isa<ObjCPropertyDecl>(ND) &&
1015 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
1016 return true;
1017 }
1018
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001019 return ND->getIdentifierNamespace() & IDNS;
1020}
1021
Douglas Gregorf9578432010-07-28 21:50:18 +00001022bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1023 if (!IsOrdinaryNonTypeName(ND))
1024 return 0;
1025
1026 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1027 if (VD->getType()->isIntegralOrEnumerationType())
1028 return true;
1029
1030 return false;
1031}
1032
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001033/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001034/// ordinary name lookup.
1035bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001036 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1037
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038 unsigned IDNS = Decl::IDNS_Ordinary;
1039 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001040 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001041
1042 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001043 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1044 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001045}
1046
Douglas Gregor86d9a522009-09-21 16:56:56 +00001047/// \brief Determines whether the given declaration is suitable as the
1048/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1049bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1050 // Allow us to find class templates, too.
1051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1052 ND = ClassTemplate->getTemplatedDecl();
1053
1054 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1055}
1056
1057/// \brief Determines whether the given declaration is an enumeration.
1058bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1059 return isa<EnumDecl>(ND);
1060}
1061
1062/// \brief Determines whether the given declaration is a class or struct.
1063bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1064 // Allow us to find class templates, too.
1065 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1066 ND = ClassTemplate->getTemplatedDecl();
1067
1068 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001069 return RD->getTagKind() == TTK_Class ||
1070 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001071
1072 return false;
1073}
1074
1075/// \brief Determines whether the given declaration is a union.
1076bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1077 // Allow us to find class templates, too.
1078 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1079 ND = ClassTemplate->getTemplatedDecl();
1080
1081 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001082 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083
1084 return false;
1085}
1086
1087/// \brief Determines whether the given declaration is a namespace.
1088bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND);
1090}
1091
1092/// \brief Determines whether the given declaration is a namespace or
1093/// namespace alias.
1094bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1095 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1096}
1097
Douglas Gregor76282942009-12-11 17:31:05 +00001098/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001099bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001100 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1101 ND = Using->getTargetDecl();
1102
1103 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104}
1105
Douglas Gregor76282942009-12-11 17:31:05 +00001106/// \brief Determines which members of a class should be visible via
1107/// "." or "->". Only value declarations, nested name specifiers, and
1108/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001110 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1111 ND = Using->getTargetDecl();
1112
Douglas Gregorce821962009-12-11 18:14:22 +00001113 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1114 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001115}
1116
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001117static bool isObjCReceiverType(ASTContext &C, QualType T) {
1118 T = C.getCanonicalType(T);
1119 switch (T->getTypeClass()) {
1120 case Type::ObjCObject:
1121 case Type::ObjCInterface:
1122 case Type::ObjCObjectPointer:
1123 return true;
1124
1125 case Type::Builtin:
1126 switch (cast<BuiltinType>(T)->getKind()) {
1127 case BuiltinType::ObjCId:
1128 case BuiltinType::ObjCClass:
1129 case BuiltinType::ObjCSel:
1130 return true;
1131
1132 default:
1133 break;
1134 }
1135 return false;
1136
1137 default:
1138 break;
1139 }
1140
1141 if (!C.getLangOptions().CPlusPlus)
1142 return false;
1143
1144 // FIXME: We could perform more analysis here to determine whether a
1145 // particular class type has any conversions to Objective-C types. For now,
1146 // just accept all class types.
1147 return T->isDependentType() || T->isRecordType();
1148}
1149
1150bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1151 QualType T = getDeclUsageType(SemaRef.Context, ND);
1152 if (T.isNull())
1153 return false;
1154
1155 T = SemaRef.Context.getBaseElementType(T);
1156 return isObjCReceiverType(SemaRef.Context, T);
1157}
1158
Douglas Gregorfb629412010-08-23 21:17:50 +00001159bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1160 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1161 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1162 return false;
1163
1164 QualType T = getDeclUsageType(SemaRef.Context, ND);
1165 if (T.isNull())
1166 return false;
1167
1168 T = SemaRef.Context.getBaseElementType(T);
1169 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1170 T->isObjCIdType() ||
1171 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1172}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001173
Douglas Gregor52779fb2010-09-23 23:01:17 +00001174bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1175 return false;
1176}
1177
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001178/// \rief Determines whether the given declaration is an Objective-C
1179/// instance variable.
1180bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1181 return isa<ObjCIvarDecl>(ND);
1182}
1183
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001184namespace {
1185 /// \brief Visible declaration consumer that adds a code-completion result
1186 /// for each visible declaration.
1187 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1188 ResultBuilder &Results;
1189 DeclContext *CurContext;
1190
1191 public:
1192 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1193 : Results(Results), CurContext(CurContext) { }
1194
Douglas Gregor0cc84042010-01-14 15:47:35 +00001195 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1196 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001378static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001379 Scope *S,
1380 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001382 CodeCompletionBuilder Builder(Results.getAllocator());
1383
John McCall0a2c5e22010-08-25 06:19:51 +00001384 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001385 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001386 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001388 if (Results.includeCodePatterns()) {
1389 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001390 Builder.AddTypedTextChunk("namespace");
1391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1392 Builder.AddPlaceholderChunk("identifier");
1393 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Builder.AddPlaceholderChunk("declarations");
1395 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1397 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001398 }
1399
Douglas Gregor01dfea02010-01-10 23:08:15 +00001400 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001401 Builder.AddTypedTextChunk("namespace");
1402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1403 Builder.AddPlaceholderChunk("name");
1404 Builder.AddChunk(CodeCompletionString::CK_Equal);
1405 Builder.AddPlaceholderChunk("namespace");
1406 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001407
1408 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001409 Builder.AddTypedTextChunk("using");
1410 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1411 Builder.AddTextChunk("namespace");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("identifier");
1414 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001415
1416 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001417 Builder.AddTypedTextChunk("asm");
1418 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1419 Builder.AddPlaceholderChunk("string-literal");
1420 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1421 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001423 if (Results.includeCodePatterns()) {
1424 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001425 Builder.AddTypedTextChunk("template");
1426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1427 Builder.AddPlaceholderChunk("declaration");
1428 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001429 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001431
1432 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001433 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001434
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001436 // Fall through
1437
John McCallf312b1e2010-08-26 23:41:50 +00001438 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001439 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001440 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001441 Builder.AddTypedTextChunk("using");
1442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1443 Builder.AddPlaceholderChunk("qualifier");
1444 Builder.AddTextChunk("::");
1445 Builder.AddPlaceholderChunk("name");
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001448 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001450 Builder.AddTypedTextChunk("using");
1451 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1452 Builder.AddTextChunk("typename");
1453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1454 Builder.AddPlaceholderChunk("qualifier");
1455 Builder.AddTextChunk("::");
1456 Builder.AddPlaceholderChunk("name");
1457 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458 }
1459
John McCallf312b1e2010-08-26 23:41:50 +00001460 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001461 AddTypedefResult(Results);
1462
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001464 Builder.AddTypedTextChunk("public");
1465 Builder.AddChunk(CodeCompletionString::CK_Colon);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467
1468 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("protected");
1470 Builder.AddChunk(CodeCompletionString::CK_Colon);
1471 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001472
1473 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("private");
1475 Builder.AddChunk(CodeCompletionString::CK_Colon);
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001477 }
1478 }
1479 // Fall through
1480
John McCallf312b1e2010-08-26 23:41:50 +00001481 case Sema::PCC_Template:
1482 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001483 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("template");
1486 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1487 Builder.AddPlaceholderChunk("parameters");
1488 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1489 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001490 }
1491
Douglas Gregorbca403c2010-01-13 23:51:12 +00001492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001494 break;
1495
John McCallf312b1e2010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001497 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1498 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1499 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001500 break;
1501
John McCallf312b1e2010-08-26 23:41:50 +00001502 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1504 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1505 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001506 break;
1507
John McCallf312b1e2010-08-26 23:41:50 +00001508 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001509 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001510 break;
1511
John McCallf312b1e2010-08-26 23:41:50 +00001512 case Sema::PCC_RecoveryInFunction:
1513 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001514 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001515
Douglas Gregorec3310a2011-04-12 02:47:21 +00001516 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1517 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("try");
1519 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1520 Builder.AddPlaceholderChunk("statements");
1521 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1522 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1523 Builder.AddTextChunk("catch");
1524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1525 Builder.AddPlaceholderChunk("declaration");
1526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1527 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1528 Builder.AddPlaceholderChunk("statements");
1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1531 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001533 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001534 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001535
Douglas Gregord8e8a582010-05-25 21:41:55 +00001536 if (Results.includeCodePatterns()) {
1537 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("if");
1539 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001540 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001541 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001542 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddPlaceholderChunk("expression");
1544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1545 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1546 Builder.AddPlaceholderChunk("statements");
1547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1548 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1549 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001550
Douglas Gregord8e8a582010-05-25 21:41:55 +00001551 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001552 Builder.AddTypedTextChunk("switch");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001554 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001556 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001557 Builder.AddPlaceholderChunk("expression");
1558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1559 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563 }
1564
Douglas Gregor01dfea02010-01-10 23:08:15 +00001565 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001566 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001568 Builder.AddTypedTextChunk("case");
1569 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1570 Builder.AddPlaceholderChunk("expression");
1571 Builder.AddChunk(CodeCompletionString::CK_Colon);
1572 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573
1574 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("default");
1576 Builder.AddChunk(CodeCompletionString::CK_Colon);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 }
1579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("while");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001594
1595 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("do");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1598 Builder.AddPlaceholderChunk("statements");
1599 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1600 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1601 Builder.AddTextChunk("while");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1603 Builder.AddPlaceholderChunk("expression");
1604 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001608 Builder.AddTypedTextChunk("for");
1609 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001610 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001611 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddPlaceholderChunk("init-expression");
1614 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1615 Builder.AddPlaceholderChunk("condition");
1616 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1617 Builder.AddPlaceholderChunk("inc-expression");
1618 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1619 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1620 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1621 Builder.AddPlaceholderChunk("statements");
1622 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1623 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001625 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
1627 if (S->getContinueParent()) {
1628 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("continue");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631 }
1632
1633 if (S->getBreakParent()) {
1634 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("break");
1636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001637 }
1638
1639 // "return expression ;" or "return ;", depending on whether we
1640 // know the function is void or not.
1641 bool isVoid = false;
1642 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1643 isVoid = Function->getResultType()->isVoidType();
1644 else if (ObjCMethodDecl *Method
1645 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1646 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001647 else if (SemaRef.getCurBlock() &&
1648 !SemaRef.getCurBlock()->ReturnType.isNull())
1649 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001650 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001651 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001654 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("goto");
1659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1660 Builder.AddPlaceholderChunk("label");
1661 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001662
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001663 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001664 Builder.AddTypedTextChunk("using");
1665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1666 Builder.AddTextChunk("namespace");
1667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1668 Builder.AddPlaceholderChunk("identifier");
1669 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670 }
1671
1672 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001673 case Sema::PCC_ForInit:
1674 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001675 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001676 // Fall through: conditions and statements can have expressions.
1677
Douglas Gregor02688102010-09-14 23:59:36 +00001678 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001679 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1680 CCC == Sema::PCC_ParenthesizedExpression) {
1681 // (__bridge <type>)<expression>
1682 Builder.AddTypedTextChunk("__bridge");
1683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1684 Builder.AddPlaceholderChunk("type");
1685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1686 Builder.AddPlaceholderChunk("expression");
1687 Results.AddResult(Result(Builder.TakeString()));
1688
1689 // (__bridge_transfer <Objective-C type>)<expression>
1690 Builder.AddTypedTextChunk("__bridge_transfer");
1691 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1692 Builder.AddPlaceholderChunk("Objective-C type");
1693 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1694 Builder.AddPlaceholderChunk("expression");
1695 Results.AddResult(Result(Builder.TakeString()));
1696
1697 // (__bridge_retained <CF type>)<expression>
1698 Builder.AddTypedTextChunk("__bridge_retained");
1699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1700 Builder.AddPlaceholderChunk("CF type");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddPlaceholderChunk("expression");
1703 Results.AddResult(Result(Builder.TakeString()));
1704 }
1705 // Fall through
1706
John McCallf312b1e2010-08-26 23:41:50 +00001707 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708 if (SemaRef.getLangOptions().CPlusPlus) {
1709 // 'this', if we're in a non-static member function.
1710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1711 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001712 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001713
1714 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001715 Results.AddResult(Result("true"));
1716 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717
Douglas Gregorec3310a2011-04-12 02:47:21 +00001718 if (SemaRef.getLangOptions().RTTI) {
1719 // dynamic_cast < type-id > ( expression )
1720 Builder.AddTypedTextChunk("dynamic_cast");
1721 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1722 Builder.AddPlaceholderChunk("type");
1723 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1724 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1725 Builder.AddPlaceholderChunk("expression");
1726 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1727 Results.AddResult(Result(Builder.TakeString()));
1728 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001729
1730 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001731 Builder.AddTypedTextChunk("static_cast");
1732 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1733 Builder.AddPlaceholderChunk("type");
1734 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1736 Builder.AddPlaceholderChunk("expression");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001739
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001740 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("reinterpret_cast");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1743 Builder.AddPlaceholderChunk("type");
1744 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001750 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001751 Builder.AddTypedTextChunk("const_cast");
1752 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1753 Builder.AddPlaceholderChunk("type");
1754 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1756 Builder.AddPlaceholderChunk("expression");
1757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1758 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001759
Douglas Gregorec3310a2011-04-12 02:47:21 +00001760 if (SemaRef.getLangOptions().RTTI) {
1761 // typeid ( expression-or-type )
1762 Builder.AddTypedTextChunk("typeid");
1763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1764 Builder.AddPlaceholderChunk("expression-or-type");
1765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1766 Results.AddResult(Result(Builder.TakeString()));
1767 }
1768
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001769 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001770 Builder.AddTypedTextChunk("new");
1771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1772 Builder.AddPlaceholderChunk("type");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1774 Builder.AddPlaceholderChunk("expressions");
1775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001777
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001778 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001779 Builder.AddTypedTextChunk("new");
1780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1781 Builder.AddPlaceholderChunk("type");
1782 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1783 Builder.AddPlaceholderChunk("size");
1784 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1786 Builder.AddPlaceholderChunk("expressions");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001789
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001790 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("delete");
1792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1793 Builder.AddPlaceholderChunk("expression");
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("delete");
1798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1799 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1800 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("expression");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001804
Douglas Gregorec3310a2011-04-12 02:47:21 +00001805 if (SemaRef.getLangOptions().CXXExceptions) {
1806 // throw expression
1807 Builder.AddTypedTextChunk("throw");
1808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1809 Builder.AddPlaceholderChunk("expression");
1810 Results.AddResult(Result(Builder.TakeString()));
1811 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001812
1813 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001814 }
1815
1816 if (SemaRef.getLangOptions().ObjC1) {
1817 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001818 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1819 // The interface can be NULL.
1820 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1821 if (ID->getSuperClass())
1822 Results.AddResult(Result("super"));
1823 }
1824
Douglas Gregorbca403c2010-01-13 23:51:12 +00001825 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001826 }
1827
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001828 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001829 Builder.AddTypedTextChunk("sizeof");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expression-or-type");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834 break;
1835 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001836
John McCallf312b1e2010-08-26 23:41:50 +00001837 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001838 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001839 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001840 }
1841
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001842 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1843 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001844
John McCallf312b1e2010-08-26 23:41:50 +00001845 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001846 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001847}
1848
Douglas Gregora63f6de2011-02-01 21:15:40 +00001849/// \brief Retrieve the string representation of the given type as a string
1850/// that has the appropriate lifetime for code completion.
1851///
1852/// This routine provides a fast path where we provide constant strings for
1853/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001854static const char *GetCompletionTypeString(QualType T,
1855 ASTContext &Context,
1856 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001857 PrintingPolicy Policy(Context.PrintingPolicy);
1858 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00001859 Policy.SuppressStrongLifetime = true;
1860
Douglas Gregora63f6de2011-02-01 21:15:40 +00001861 if (!T.getLocalQualifiers()) {
1862 // Built-in type names are constant strings.
1863 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1864 return BT->getName(Context.getLangOptions());
1865
1866 // Anonymous tag types are constant strings.
1867 if (const TagType *TagT = dyn_cast<TagType>(T))
1868 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001869 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001870 switch (Tag->getTagKind()) {
1871 case TTK_Struct: return "struct <anonymous>";
1872 case TTK_Class: return "class <anonymous>";
1873 case TTK_Union: return "union <anonymous>";
1874 case TTK_Enum: return "enum <anonymous>";
1875 }
1876 }
1877 }
1878
1879 // Slow path: format the type as a string.
1880 std::string Result;
1881 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001882 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001883}
1884
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001885/// \brief If the given declaration has an associated type, add it as a result
1886/// type chunk.
1887static void AddResultTypeChunk(ASTContext &Context,
1888 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001889 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001890 if (!ND)
1891 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001892
1893 // Skip constructors and conversion functions, which have their return types
1894 // built into their names.
1895 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1896 return;
1897
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001898 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001899 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001900 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1901 T = Function->getResultType();
1902 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1903 T = Method->getResultType();
1904 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1905 T = FunTmpl->getTemplatedDecl()->getResultType();
1906 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1907 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1908 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1909 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001910 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001911 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001912 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001913 T = Property->getType();
1914
1915 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1916 return;
1917
Douglas Gregora63f6de2011-02-01 21:15:40 +00001918 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1919 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001920}
1921
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001922static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001923 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001924 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1925 if (Sentinel->getSentinel() == 0) {
1926 if (Context.getLangOptions().ObjC1 &&
1927 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001928 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001929 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001930 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001931 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001932 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001933 }
1934}
1935
Douglas Gregor83482d12010-08-24 16:15:59 +00001936static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001937 ParmVarDecl *Param,
1938 bool SuppressName = false) {
John McCallf85e1932011-06-15 23:02:42 +00001939 PrintingPolicy Policy(Context.PrintingPolicy);
1940 Policy.AnonymousTagLocations = false;
1941 Policy.SuppressStrongLifetime = true;
1942
Douglas Gregor83482d12010-08-24 16:15:59 +00001943 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1944 if (Param->getType()->isDependentType() ||
1945 !Param->getType()->isBlockPointerType()) {
1946 // The argument for a dependent or non-block parameter is a placeholder
1947 // containing that parameter's type.
1948 std::string Result;
1949
Douglas Gregoraba48082010-08-29 19:47:46 +00001950 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001951 Result = Param->getIdentifier()->getName();
1952
John McCallf85e1932011-06-15 23:02:42 +00001953 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001954
1955 if (ObjCMethodParam) {
1956 Result = "(" + Result;
1957 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001958 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001959 Result += Param->getIdentifier()->getName();
1960 }
1961 return Result;
1962 }
1963
1964 // The argument for a block pointer parameter is a block literal with
1965 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001966 FunctionTypeLoc *Block = 0;
1967 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001968 TypeLoc TL;
1969 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1970 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1971 while (true) {
1972 // Look through typedefs.
1973 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1974 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001975 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001976 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1977 continue;
1978 }
1979 }
1980
1981 // Look through qualified types
1982 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1983 TL = QualifiedTL->getUnqualifiedLoc();
1984 continue;
1985 }
1986
1987 // Try to get the function prototype behind the block pointer type,
1988 // then we're done.
1989 if (BlockPointerTypeLoc *BlockPtr
1990 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00001991 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00001992 Block = dyn_cast<FunctionTypeLoc>(&TL);
1993 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00001994 }
1995 break;
1996 }
1997 }
1998
1999 if (!Block) {
2000 // We were unable to find a FunctionProtoTypeLoc with parameter names
2001 // for the block; just use the parameter type as a placeholder.
2002 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002003 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002004
2005 if (ObjCMethodParam) {
2006 Result = "(" + Result;
2007 Result += ")";
2008 if (Param->getIdentifier())
2009 Result += Param->getIdentifier()->getName();
2010 }
2011
2012 return Result;
2013 }
2014
2015 // We have the function prototype behind the block pointer type, as it was
2016 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002017 std::string Result;
2018 QualType ResultType = Block->getTypePtr()->getResultType();
2019 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002020 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002021
2022 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002023 if (!BlockProto || Block->getNumArgs() == 0) {
2024 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002025 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002026 else
2027 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002028 } else {
2029 Result += "(";
2030 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2031 if (I)
2032 Result += ", ";
2033 Result += FormatFunctionParameter(Context, Block->getArg(I));
2034
Douglas Gregor830072c2011-02-15 22:37:09 +00002035 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002036 Result += ", ...";
2037 }
2038 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002039 }
Douglas Gregor38276252010-09-08 22:47:51 +00002040
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002041 if (Param->getIdentifier())
2042 Result += Param->getIdentifier()->getName();
2043
Douglas Gregor83482d12010-08-24 16:15:59 +00002044 return Result;
2045}
2046
Douglas Gregor86d9a522009-09-21 16:56:56 +00002047/// \brief Add function parameter chunks to the given code completion string.
2048static void AddFunctionParameterChunks(ASTContext &Context,
2049 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002050 CodeCompletionBuilder &Result,
2051 unsigned Start = 0,
2052 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002053 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002054 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002055
Douglas Gregor218937c2011-02-01 19:23:04 +00002056 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002057 ParmVarDecl *Param = Function->getParamDecl(P);
2058
Douglas Gregor218937c2011-02-01 19:23:04 +00002059 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002060 // When we see an optional default argument, put that argument and
2061 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002062 CodeCompletionBuilder Opt(Result.getAllocator());
2063 if (!FirstParameter)
2064 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2065 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2066 Result.AddOptionalChunk(Opt.TakeString());
2067 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002068 }
2069
Douglas Gregor218937c2011-02-01 19:23:04 +00002070 if (FirstParameter)
2071 FirstParameter = false;
2072 else
2073 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2074
2075 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002076
2077 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002078 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2079
Douglas Gregore17794f2010-08-31 05:13:43 +00002080 if (Function->isVariadic() && P == N - 1)
2081 PlaceholderStr += ", ...";
2082
Douglas Gregor86d9a522009-09-21 16:56:56 +00002083 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002084 Result.AddPlaceholderChunk(
2085 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002086 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002087
2088 if (const FunctionProtoType *Proto
2089 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002090 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002091 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002092 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002093
Douglas Gregor218937c2011-02-01 19:23:04 +00002094 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002095 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002096}
2097
2098/// \brief Add template parameter chunks to the given code completion string.
2099static void AddTemplateParameterChunks(ASTContext &Context,
2100 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002101 CodeCompletionBuilder &Result,
2102 unsigned MaxParameters = 0,
2103 unsigned Start = 0,
2104 bool InDefaultArg = false) {
John McCallf85e1932011-06-15 23:02:42 +00002105 PrintingPolicy Policy(Context.PrintingPolicy);
2106 Policy.AnonymousTagLocations = false;
2107
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002108 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002109 bool FirstParameter = true;
2110
2111 TemplateParameterList *Params = Template->getTemplateParameters();
2112 TemplateParameterList::iterator PEnd = Params->end();
2113 if (MaxParameters)
2114 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002115 for (TemplateParameterList::iterator P = Params->begin() + Start;
2116 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002117 bool HasDefaultArg = false;
2118 std::string PlaceholderStr;
2119 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2120 if (TTP->wasDeclaredWithTypename())
2121 PlaceholderStr = "typename";
2122 else
2123 PlaceholderStr = "class";
2124
2125 if (TTP->getIdentifier()) {
2126 PlaceholderStr += ' ';
2127 PlaceholderStr += TTP->getIdentifier()->getName();
2128 }
2129
2130 HasDefaultArg = TTP->hasDefaultArgument();
2131 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002132 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002133 if (NTTP->getIdentifier())
2134 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002135 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002136 HasDefaultArg = NTTP->hasDefaultArgument();
2137 } else {
2138 assert(isa<TemplateTemplateParmDecl>(*P));
2139 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2140
2141 // Since putting the template argument list into the placeholder would
2142 // be very, very long, we just use an abbreviation.
2143 PlaceholderStr = "template<...> class";
2144 if (TTP->getIdentifier()) {
2145 PlaceholderStr += ' ';
2146 PlaceholderStr += TTP->getIdentifier()->getName();
2147 }
2148
2149 HasDefaultArg = TTP->hasDefaultArgument();
2150 }
2151
Douglas Gregor218937c2011-02-01 19:23:04 +00002152 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002153 // When we see an optional default argument, put that argument and
2154 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002155 CodeCompletionBuilder Opt(Result.getAllocator());
2156 if (!FirstParameter)
2157 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2158 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2159 P - Params->begin(), true);
2160 Result.AddOptionalChunk(Opt.TakeString());
2161 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002162 }
2163
Douglas Gregor218937c2011-02-01 19:23:04 +00002164 InDefaultArg = false;
2165
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166 if (FirstParameter)
2167 FirstParameter = false;
2168 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002169 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002170
2171 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002172 Result.AddPlaceholderChunk(
2173 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002174 }
2175}
2176
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002177/// \brief Add a qualifier to the given code-completion string, if the
2178/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002179static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002180AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002181 NestedNameSpecifier *Qualifier,
2182 bool QualifierIsInformative,
2183 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002184 if (!Qualifier)
2185 return;
2186
2187 std::string PrintedNNS;
2188 {
2189 llvm::raw_string_ostream OS(PrintedNNS);
2190 Qualifier->print(OS, Context.PrintingPolicy);
2191 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002192 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002193 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002194 else
Douglas Gregordae68752011-02-01 22:57:45 +00002195 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002196}
2197
Douglas Gregor218937c2011-02-01 19:23:04 +00002198static void
2199AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2200 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002201 const FunctionProtoType *Proto
2202 = Function->getType()->getAs<FunctionProtoType>();
2203 if (!Proto || !Proto->getTypeQuals())
2204 return;
2205
Douglas Gregora63f6de2011-02-01 21:15:40 +00002206 // FIXME: Add ref-qualifier!
2207
2208 // Handle single qualifiers without copying
2209 if (Proto->getTypeQuals() == Qualifiers::Const) {
2210 Result.AddInformativeChunk(" const");
2211 return;
2212 }
2213
2214 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2215 Result.AddInformativeChunk(" volatile");
2216 return;
2217 }
2218
2219 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2220 Result.AddInformativeChunk(" restrict");
2221 return;
2222 }
2223
2224 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002225 std::string QualsStr;
2226 if (Proto->getTypeQuals() & Qualifiers::Const)
2227 QualsStr += " const";
2228 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2229 QualsStr += " volatile";
2230 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2231 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002232 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002233}
2234
Douglas Gregor6f942b22010-09-21 16:06:22 +00002235/// \brief Add the name of the given declaration
2236static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002237 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002238 typedef CodeCompletionString::Chunk Chunk;
2239
2240 DeclarationName Name = ND->getDeclName();
2241 if (!Name)
2242 return;
2243
2244 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002245 case DeclarationName::CXXOperatorName: {
2246 const char *OperatorName = 0;
2247 switch (Name.getCXXOverloadedOperator()) {
2248 case OO_None:
2249 case OO_Conditional:
2250 case NUM_OVERLOADED_OPERATORS:
2251 OperatorName = "operator";
2252 break;
2253
2254#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2255 case OO_##Name: OperatorName = "operator" Spelling; break;
2256#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2257#include "clang/Basic/OperatorKinds.def"
2258
2259 case OO_New: OperatorName = "operator new"; break;
2260 case OO_Delete: OperatorName = "operator delete"; break;
2261 case OO_Array_New: OperatorName = "operator new[]"; break;
2262 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2263 case OO_Call: OperatorName = "operator()"; break;
2264 case OO_Subscript: OperatorName = "operator[]"; break;
2265 }
2266 Result.AddTypedTextChunk(OperatorName);
2267 break;
2268 }
2269
Douglas Gregor6f942b22010-09-21 16:06:22 +00002270 case DeclarationName::Identifier:
2271 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002272 case DeclarationName::CXXDestructorName:
2273 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002274 Result.AddTypedTextChunk(
2275 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002276 break;
2277
2278 case DeclarationName::CXXUsingDirective:
2279 case DeclarationName::ObjCZeroArgSelector:
2280 case DeclarationName::ObjCOneArgSelector:
2281 case DeclarationName::ObjCMultiArgSelector:
2282 break;
2283
2284 case DeclarationName::CXXConstructorName: {
2285 CXXRecordDecl *Record = 0;
2286 QualType Ty = Name.getCXXNameType();
2287 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2288 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2289 else if (const InjectedClassNameType *InjectedTy
2290 = Ty->getAs<InjectedClassNameType>())
2291 Record = InjectedTy->getDecl();
2292 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002293 Result.AddTypedTextChunk(
2294 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002295 break;
2296 }
2297
Douglas Gregordae68752011-02-01 22:57:45 +00002298 Result.AddTypedTextChunk(
2299 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002300 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002301 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002302 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002303 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002304 }
2305 break;
2306 }
2307 }
2308}
2309
Douglas Gregor86d9a522009-09-21 16:56:56 +00002310/// \brief If possible, create a new code completion string for the given
2311/// result.
2312///
2313/// \returns Either a new, heap-allocated code completion string describing
2314/// how to use this result, or NULL to indicate that the string or name of the
2315/// result is all that is needed.
2316CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002317CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002318 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002319 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002320 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002321
John McCallf85e1932011-06-15 23:02:42 +00002322 PrintingPolicy Policy(S.Context.PrintingPolicy);
2323 Policy.AnonymousTagLocations = false;
2324 Policy.SuppressStrongLifetime = true;
2325
Douglas Gregor218937c2011-02-01 19:23:04 +00002326 if (Kind == RK_Pattern) {
2327 Pattern->Priority = Priority;
2328 Pattern->Availability = Availability;
2329 return Pattern;
2330 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002331
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002332 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002333 Result.AddTypedTextChunk(Keyword);
2334 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002335 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002336
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002337 if (Kind == RK_Macro) {
2338 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002339 assert(MI && "Not a macro?");
2340
Douglas Gregordae68752011-02-01 22:57:45 +00002341 Result.AddTypedTextChunk(
2342 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002343
2344 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002345 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002346
2347 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002349 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2350 A != AEnd; ++A) {
2351 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002352 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002353
2354 if (!MI->isVariadic() || A != AEnd - 1) {
2355 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002356 Result.AddPlaceholderChunk(
2357 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002358 continue;
2359 }
2360
2361 // Variadic argument; cope with the different between GNU and C99
2362 // variadic macros, providing a single placeholder for the rest of the
2363 // arguments.
2364 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002365 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002366 else {
2367 std::string Arg = (*A)->getName();
2368 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002369 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002370 }
2371 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002372 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2373 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002374 }
2375
Douglas Gregord8e8a582010-05-25 21:41:55 +00002376 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002377 NamedDecl *ND = Declaration;
2378
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002379 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002382 Result.AddTextChunk("::");
2383 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002384 }
2385
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002386 AddResultTypeChunk(S.Context, ND, Result);
2387
Douglas Gregor86d9a522009-09-21 16:56:56 +00002388 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002389 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2390 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002391 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002392 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002393 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002394 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002395 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002396 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002397 }
2398
2399 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002400 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2401 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002402 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002403 AddTypedNameChunk(S.Context, Function, Result);
2404
Douglas Gregor86d9a522009-09-21 16:56:56 +00002405 // Figure out which template parameters are deduced (or have default
2406 // arguments).
2407 llvm::SmallVector<bool, 16> Deduced;
2408 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2409 unsigned LastDeducibleArgument;
2410 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2411 --LastDeducibleArgument) {
2412 if (!Deduced[LastDeducibleArgument - 1]) {
2413 // C++0x: Figure out if the template argument has a default. If so,
2414 // the user doesn't need to type this argument.
2415 // FIXME: We need to abstract template parameters better!
2416 bool HasDefaultArg = false;
2417 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002418 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002419 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2420 HasDefaultArg = TTP->hasDefaultArgument();
2421 else if (NonTypeTemplateParmDecl *NTTP
2422 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2423 HasDefaultArg = NTTP->hasDefaultArgument();
2424 else {
2425 assert(isa<TemplateTemplateParmDecl>(Param));
2426 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002427 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002428 }
2429
2430 if (!HasDefaultArg)
2431 break;
2432 }
2433 }
2434
2435 if (LastDeducibleArgument) {
2436 // Some of the function template arguments cannot be deduced from a
2437 // function call, so we introduce an explicit template argument list
2438 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002439 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002440 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2441 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002442 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002443 }
2444
2445 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002446 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002448 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002449 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002450 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002451 }
2452
2453 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002454 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2455 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002456 Result.AddTypedTextChunk(
2457 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002458 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002459 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002460 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2461 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002462 }
2463
Douglas Gregor9630eb62009-11-17 16:44:22 +00002464 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002465 Selector Sel = Method->getSelector();
2466 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002467 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002468 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002469 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002470 }
2471
Douglas Gregor813d8342011-02-18 22:29:55 +00002472 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002473 SelName += ':';
2474 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002475 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002476 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002477 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002478
2479 // If there is only one parameter, and we're past it, add an empty
2480 // typed-text chunk since there is nothing to type.
2481 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002482 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002483 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002484 unsigned Idx = 0;
2485 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2486 PEnd = Method->param_end();
2487 P != PEnd; (void)++P, ++Idx) {
2488 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002489 std::string Keyword;
2490 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002491 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002492 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2493 Keyword += II->getName().str();
2494 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002495 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002496 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002497 else
Douglas Gregordae68752011-02-01 22:57:45 +00002498 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002499 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002500
2501 // If we're before the starting parameter, skip the placeholder.
2502 if (Idx < StartParameter)
2503 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002504
2505 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002506
2507 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002508 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002509 else {
John McCallf85e1932011-06-15 23:02:42 +00002510 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002511 Arg = "(" + Arg + ")";
2512 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002513 if (DeclaringEntity || AllParametersAreInformative)
2514 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002515 }
2516
Douglas Gregore17794f2010-08-31 05:13:43 +00002517 if (Method->isVariadic() && (P + 1) == PEnd)
2518 Arg += ", ...";
2519
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002520 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002521 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002522 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002523 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002524 else
Douglas Gregordae68752011-02-01 22:57:45 +00002525 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002526 }
2527
Douglas Gregor2a17af02009-12-23 00:21:46 +00002528 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002529 if (Method->param_size() == 0) {
2530 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002531 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002532 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002533 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002534 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002535 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002536 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002537
2538 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002539 }
2540
Douglas Gregor218937c2011-02-01 19:23:04 +00002541 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002542 }
2543
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002544 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002545 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2546 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002547
Douglas Gregordae68752011-02-01 22:57:45 +00002548 Result.AddTypedTextChunk(
2549 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002550 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002551}
2552
Douglas Gregor86d802e2009-09-23 00:34:09 +00002553CodeCompletionString *
2554CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2555 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002556 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002557 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002558 typedef CodeCompletionString::Chunk Chunk;
John McCallf85e1932011-06-15 23:02:42 +00002559 PrintingPolicy Policy(S.Context.PrintingPolicy);
2560 Policy.AnonymousTagLocations = false;
2561 Policy.SuppressStrongLifetime = true;
2562
Douglas Gregor218937c2011-02-01 19:23:04 +00002563 // FIXME: Set priority, availability appropriately.
2564 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002565 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002566 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002567 const FunctionProtoType *Proto
2568 = dyn_cast<FunctionProtoType>(getFunctionType());
2569 if (!FDecl && !Proto) {
2570 // Function without a prototype. Just give the return type and a
2571 // highlighted ellipsis.
2572 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002573 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2574 S.Context,
2575 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2577 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2578 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2579 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002580 }
2581
2582 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002583 Result.AddTextChunk(
2584 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002585 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002586 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002587 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002588 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002589
Douglas Gregor218937c2011-02-01 19:23:04 +00002590 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002591 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2592 for (unsigned I = 0; I != NumParams; ++I) {
2593 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002594 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002595
2596 std::string ArgString;
2597 QualType ArgType;
2598
2599 if (FDecl) {
2600 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2601 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2602 } else {
2603 ArgType = Proto->getArgType(I);
2604 }
2605
John McCallf85e1932011-06-15 23:02:42 +00002606 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002607
2608 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002609 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002610 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002611 else
Douglas Gregordae68752011-02-01 22:57:45 +00002612 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002613 }
2614
2615 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002616 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002617 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002618 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002619 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002620 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002621 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002622 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002623
Douglas Gregor218937c2011-02-01 19:23:04 +00002624 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002625}
2626
Douglas Gregor1827e102010-08-16 16:18:59 +00002627unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002628 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002629 bool PreferredTypeIsPointer) {
2630 unsigned Priority = CCP_Macro;
2631
Douglas Gregorb05496d2010-09-20 21:11:48 +00002632 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2633 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2634 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002635 Priority = CCP_Constant;
2636 if (PreferredTypeIsPointer)
2637 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002638 }
2639 // Treat "YES", "NO", "true", and "false" as constants.
2640 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2641 MacroName.equals("true") || MacroName.equals("false"))
2642 Priority = CCP_Constant;
2643 // Treat "bool" as a type.
2644 else if (MacroName.equals("bool"))
2645 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2646
Douglas Gregor1827e102010-08-16 16:18:59 +00002647
2648 return Priority;
2649}
2650
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002651CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2652 if (!D)
2653 return CXCursor_UnexposedDecl;
2654
2655 switch (D->getKind()) {
2656 case Decl::Enum: return CXCursor_EnumDecl;
2657 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2658 case Decl::Field: return CXCursor_FieldDecl;
2659 case Decl::Function:
2660 return CXCursor_FunctionDecl;
2661 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2662 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2663 case Decl::ObjCClass:
2664 // FIXME
2665 return CXCursor_UnexposedDecl;
2666 case Decl::ObjCForwardProtocol:
2667 // FIXME
2668 return CXCursor_UnexposedDecl;
2669 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2670 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2671 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2672 case Decl::ObjCMethod:
2673 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2674 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2675 case Decl::CXXMethod: return CXCursor_CXXMethod;
2676 case Decl::CXXConstructor: return CXCursor_Constructor;
2677 case Decl::CXXDestructor: return CXCursor_Destructor;
2678 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2679 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2680 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2681 case Decl::ParmVar: return CXCursor_ParmDecl;
2682 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002683 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002684 case Decl::Var: return CXCursor_VarDecl;
2685 case Decl::Namespace: return CXCursor_Namespace;
2686 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2687 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2688 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2689 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2690 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2691 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2692 case Decl::ClassTemplatePartialSpecialization:
2693 return CXCursor_ClassTemplatePartialSpecialization;
2694 case Decl::UsingDirective: return CXCursor_UsingDirective;
2695
2696 case Decl::Using:
2697 case Decl::UnresolvedUsingValue:
2698 case Decl::UnresolvedUsingTypename:
2699 return CXCursor_UsingDeclaration;
2700
Douglas Gregor352697a2011-06-03 23:08:58 +00002701 case Decl::ObjCPropertyImpl:
2702 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2703 case ObjCPropertyImplDecl::Dynamic:
2704 return CXCursor_ObjCDynamicDecl;
2705
2706 case ObjCPropertyImplDecl::Synthesize:
2707 return CXCursor_ObjCSynthesizeDecl;
2708 }
2709 break;
2710
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002711 default:
2712 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2713 switch (TD->getTagKind()) {
2714 case TTK_Struct: return CXCursor_StructDecl;
2715 case TTK_Class: return CXCursor_ClassDecl;
2716 case TTK_Union: return CXCursor_UnionDecl;
2717 case TTK_Enum: return CXCursor_EnumDecl;
2718 }
2719 }
2720 }
2721
2722 return CXCursor_UnexposedDecl;
2723}
2724
Douglas Gregor590c7d52010-07-08 20:55:51 +00002725static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2726 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002727 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002728
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002729 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002730
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002731 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2732 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002733 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002734 Results.AddResult(Result(M->first,
2735 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002736 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002737 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002738 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002739
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002740 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002741
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002742}
2743
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002744static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2745 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002746 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002747
2748 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002749
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002750 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2751 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2752 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2753 Results.AddResult(Result("__func__", CCP_Constant));
2754 Results.ExitScope();
2755}
2756
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002757static void HandleCodeCompleteResults(Sema *S,
2758 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002759 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002760 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002761 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002762 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002763 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002764}
2765
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002766static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2767 Sema::ParserCompletionContext PCC) {
2768 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002769 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002770 return CodeCompletionContext::CCC_TopLevel;
2771
John McCallf312b1e2010-08-26 23:41:50 +00002772 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002773 return CodeCompletionContext::CCC_ClassStructUnion;
2774
John McCallf312b1e2010-08-26 23:41:50 +00002775 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002776 return CodeCompletionContext::CCC_ObjCInterface;
2777
John McCallf312b1e2010-08-26 23:41:50 +00002778 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002779 return CodeCompletionContext::CCC_ObjCImplementation;
2780
John McCallf312b1e2010-08-26 23:41:50 +00002781 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002782 return CodeCompletionContext::CCC_ObjCIvarList;
2783
John McCallf312b1e2010-08-26 23:41:50 +00002784 case Sema::PCC_Template:
2785 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002786 if (S.CurContext->isFileContext())
2787 return CodeCompletionContext::CCC_TopLevel;
2788 else if (S.CurContext->isRecord())
2789 return CodeCompletionContext::CCC_ClassStructUnion;
2790 else
2791 return CodeCompletionContext::CCC_Other;
2792
John McCallf312b1e2010-08-26 23:41:50 +00002793 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002794 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002795
John McCallf312b1e2010-08-26 23:41:50 +00002796 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002797 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2798 S.getLangOptions().ObjC1)
2799 return CodeCompletionContext::CCC_ParenthesizedExpression;
2800 else
2801 return CodeCompletionContext::CCC_Expression;
2802
2803 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002804 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 return CodeCompletionContext::CCC_Expression;
2806
John McCallf312b1e2010-08-26 23:41:50 +00002807 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002808 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002809
John McCallf312b1e2010-08-26 23:41:50 +00002810 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002811 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002812
2813 case Sema::PCC_ParenthesizedExpression:
2814 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002815
2816 case Sema::PCC_LocalDeclarationSpecifiers:
2817 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002818 }
2819
2820 return CodeCompletionContext::CCC_Other;
2821}
2822
Douglas Gregorf6961522010-08-27 21:18:54 +00002823/// \brief If we're in a C++ virtual member function, add completion results
2824/// that invoke the functions we override, since it's common to invoke the
2825/// overridden function as well as adding new functionality.
2826///
2827/// \param S The semantic analysis object for which we are generating results.
2828///
2829/// \param InContext This context in which the nested-name-specifier preceding
2830/// the code-completion point
2831static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2832 ResultBuilder &Results) {
2833 // Look through blocks.
2834 DeclContext *CurContext = S.CurContext;
2835 while (isa<BlockDecl>(CurContext))
2836 CurContext = CurContext->getParent();
2837
2838
2839 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2840 if (!Method || !Method->isVirtual())
2841 return;
2842
2843 // We need to have names for all of the parameters, if we're going to
2844 // generate a forwarding call.
2845 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2846 PEnd = Method->param_end();
2847 P != PEnd;
2848 ++P) {
2849 if (!(*P)->getDeclName())
2850 return;
2851 }
2852
2853 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2854 MEnd = Method->end_overridden_methods();
2855 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002856 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002857 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2858 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2859 continue;
2860
2861 // If we need a nested-name-specifier, add one now.
2862 if (!InContext) {
2863 NestedNameSpecifier *NNS
2864 = getRequiredQualification(S.Context, CurContext,
2865 Overridden->getDeclContext());
2866 if (NNS) {
2867 std::string Str;
2868 llvm::raw_string_ostream OS(Str);
2869 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002870 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002871 }
2872 } else if (!InContext->Equals(Overridden->getDeclContext()))
2873 continue;
2874
Douglas Gregordae68752011-02-01 22:57:45 +00002875 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002876 Overridden->getNameAsString()));
2877 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002878 bool FirstParam = true;
2879 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2880 PEnd = Method->param_end();
2881 P != PEnd; ++P) {
2882 if (FirstParam)
2883 FirstParam = false;
2884 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002885 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002886
Douglas Gregordae68752011-02-01 22:57:45 +00002887 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002888 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002889 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2891 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002892 CCP_SuperCompletion,
2893 CXCursor_CXXMethod));
2894 Results.Ignore(Overridden);
2895 }
2896}
2897
Douglas Gregor01dfea02010-01-10 23:08:15 +00002898void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002899 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002900 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002902 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002903 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002904
Douglas Gregor01dfea02010-01-10 23:08:15 +00002905 // Determine how to filter results, e.g., so that the names of
2906 // values (functions, enumerators, function templates, etc.) are
2907 // only allowed where we can have an expression.
2908 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002909 case PCC_Namespace:
2910 case PCC_Class:
2911 case PCC_ObjCInterface:
2912 case PCC_ObjCImplementation:
2913 case PCC_ObjCInstanceVariableList:
2914 case PCC_Template:
2915 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002916 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002917 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002918 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2919 break;
2920
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002921 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002922 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002923 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002924 case PCC_ForInit:
2925 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002926 if (WantTypesInContext(CompletionContext, getLangOptions()))
2927 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2928 else
2929 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002930
2931 if (getLangOptions().CPlusPlus)
2932 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002933 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002934
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002935 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002936 // Unfiltered
2937 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002938 }
2939
Douglas Gregor3cdee122010-08-26 16:36:48 +00002940 // If we are in a C++ non-static member function, check the qualifiers on
2941 // the member function to filter/prioritize the results list.
2942 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2943 if (CurMethod->isInstance())
2944 Results.setObjectTypeQualifiers(
2945 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2946
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002947 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002948 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2949 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002950
Douglas Gregorbca403c2010-01-13 23:51:12 +00002951 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002952 Results.ExitScope();
2953
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002954 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002955 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002956 case PCC_Expression:
2957 case PCC_Statement:
2958 case PCC_RecoveryInFunction:
2959 if (S->getFnParent())
2960 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2961 break;
2962
2963 case PCC_Namespace:
2964 case PCC_Class:
2965 case PCC_ObjCInterface:
2966 case PCC_ObjCImplementation:
2967 case PCC_ObjCInstanceVariableList:
2968 case PCC_Template:
2969 case PCC_MemberTemplate:
2970 case PCC_ForInit:
2971 case PCC_Condition:
2972 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002973 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002974 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002975 }
2976
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002977 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002978 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002979
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002980 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002981 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002982}
2983
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002984static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2985 ParsedType Receiver,
2986 IdentifierInfo **SelIdents,
2987 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002988 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002989 bool IsSuper,
2990 ResultBuilder &Results);
2991
2992void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2993 bool AllowNonIdentifiers,
2994 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002995 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002997 AllowNestedNameSpecifiers
2998 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2999 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003000 Results.EnterNewScope();
3001
3002 // Type qualifiers can come after names.
3003 Results.AddResult(Result("const"));
3004 Results.AddResult(Result("volatile"));
3005 if (getLangOptions().C99)
3006 Results.AddResult(Result("restrict"));
3007
3008 if (getLangOptions().CPlusPlus) {
3009 if (AllowNonIdentifiers) {
3010 Results.AddResult(Result("operator"));
3011 }
3012
3013 // Add nested-name-specifiers.
3014 if (AllowNestedNameSpecifiers) {
3015 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003016 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003017 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3018 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3019 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003020 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003021 }
3022 }
3023 Results.ExitScope();
3024
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003025 // If we're in a context where we might have an expression (rather than a
3026 // declaration), and what we've seen so far is an Objective-C type that could
3027 // be a receiver of a class message, this may be a class message send with
3028 // the initial opening bracket '[' missing. Add appropriate completions.
3029 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3030 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3031 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3032 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3033 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3034 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3035 DS.getTypeQualifiers() == 0 &&
3036 S &&
3037 (S->getFlags() & Scope::DeclScope) != 0 &&
3038 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3039 Scope::FunctionPrototypeScope |
3040 Scope::AtCatchScope)) == 0) {
3041 ParsedType T = DS.getRepAsType();
3042 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003043 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003044 }
3045
Douglas Gregor4497dd42010-08-24 04:59:56 +00003046 // Note that we intentionally suppress macro results here, since we do not
3047 // encourage using macros to produce the names of entities.
3048
Douglas Gregor52779fb2010-09-23 23:01:17 +00003049 HandleCodeCompleteResults(this, CodeCompleter,
3050 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003051 Results.data(), Results.size());
3052}
3053
Douglas Gregorfb629412010-08-23 21:17:50 +00003054struct Sema::CodeCompleteExpressionData {
3055 CodeCompleteExpressionData(QualType PreferredType = QualType())
3056 : PreferredType(PreferredType), IntegralConstantExpression(false),
3057 ObjCCollection(false) { }
3058
3059 QualType PreferredType;
3060 bool IntegralConstantExpression;
3061 bool ObjCCollection;
3062 llvm::SmallVector<Decl *, 4> IgnoreDecls;
3063};
3064
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003065/// \brief Perform code-completion in an expression context when we know what
3066/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003067///
3068/// \param IntegralConstantExpression Only permit integral constant
3069/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003070void Sema::CodeCompleteExpression(Scope *S,
3071 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003072 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003073 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3074 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003075 if (Data.ObjCCollection)
3076 Results.setFilter(&ResultBuilder::IsObjCCollection);
3077 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003078 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003079 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003080 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3081 else
3082 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003083
3084 if (!Data.PreferredType.isNull())
3085 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3086
3087 // Ignore any declarations that we were told that we don't care about.
3088 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3089 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003090
3091 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003092 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3093 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003094
3095 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003096 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003097 Results.ExitScope();
3098
Douglas Gregor590c7d52010-07-08 20:55:51 +00003099 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003100 if (!Data.PreferredType.isNull())
3101 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3102 || Data.PreferredType->isMemberPointerType()
3103 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003104
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003105 if (S->getFnParent() &&
3106 !Data.ObjCCollection &&
3107 !Data.IntegralConstantExpression)
3108 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3109
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003110 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003111 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003112 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003113 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3114 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003115 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003116}
3117
Douglas Gregorac5fd842010-09-18 01:28:11 +00003118void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3119 if (E.isInvalid())
3120 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3121 else if (getLangOptions().ObjC1)
3122 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003123}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003124
Douglas Gregor73449212010-12-09 23:01:55 +00003125/// \brief The set of properties that have already been added, referenced by
3126/// property name.
3127typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3128
Douglas Gregor95ac6552009-11-18 01:29:26 +00003129static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003130 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003131 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003132 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003133 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003134 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003135 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003136
3137 // Add properties in this container.
3138 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3139 PEnd = Container->prop_end();
3140 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003141 ++P) {
3142 if (AddedProperties.insert(P->getIdentifier()))
3143 Results.MaybeAddResult(Result(*P, 0), CurContext);
3144 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003145
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003146 // Add nullary methods
3147 if (AllowNullaryMethods) {
3148 ASTContext &Context = Container->getASTContext();
3149 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3150 MEnd = Container->meth_end();
3151 M != MEnd; ++M) {
3152 if (M->getSelector().isUnarySelector())
3153 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3154 if (AddedProperties.insert(Name)) {
3155 CodeCompletionBuilder Builder(Results.getAllocator());
3156 AddResultTypeChunk(Context, *M, Builder);
3157 Builder.AddTypedTextChunk(
3158 Results.getAllocator().CopyString(Name->getName()));
3159
3160 CXAvailabilityKind Availability = CXAvailability_Available;
3161 switch (M->getAvailability()) {
3162 case AR_Available:
3163 case AR_NotYetIntroduced:
3164 Availability = CXAvailability_Available;
3165 break;
3166
3167 case AR_Deprecated:
3168 Availability = CXAvailability_Deprecated;
3169 break;
3170
3171 case AR_Unavailable:
3172 Availability = CXAvailability_NotAvailable;
3173 break;
3174 }
3175
3176 Results.MaybeAddResult(Result(Builder.TakeString(),
3177 CCP_MemberDeclaration + CCD_MethodAsProperty,
3178 M->isInstanceMethod()
3179 ? CXCursor_ObjCInstanceMethodDecl
3180 : CXCursor_ObjCClassMethodDecl,
3181 Availability),
3182 CurContext);
3183 }
3184 }
3185 }
3186
3187
Douglas Gregor95ac6552009-11-18 01:29:26 +00003188 // Add properties in referenced protocols.
3189 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3190 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3191 PEnd = Protocol->protocol_end();
3192 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003193 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3194 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003195 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003196 if (AllowCategories) {
3197 // Look through categories.
3198 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3199 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003200 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3201 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003202 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003203
3204 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003205 for (ObjCInterfaceDecl::all_protocol_iterator
3206 I = IFace->all_referenced_protocol_begin(),
3207 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003208 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3209 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003210
3211 // Look in the superclass.
3212 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003213 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3214 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003215 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003216 } else if (const ObjCCategoryDecl *Category
3217 = dyn_cast<ObjCCategoryDecl>(Container)) {
3218 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003219 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3220 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003221 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003222 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3223 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003224 }
3225}
3226
Douglas Gregor81b747b2009-09-17 21:32:03 +00003227void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3228 SourceLocation OpLoc,
3229 bool IsArrow) {
3230 if (!BaseE || !CodeCompleter)
3231 return;
3232
John McCall0a2c5e22010-08-25 06:19:51 +00003233 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003234
Douglas Gregor81b747b2009-09-17 21:32:03 +00003235 Expr *Base = static_cast<Expr *>(BaseE);
3236 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003237
3238 if (IsArrow) {
3239 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3240 BaseType = Ptr->getPointeeType();
3241 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003242 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003243 else
3244 return;
3245 }
3246
Douglas Gregor218937c2011-02-01 19:23:04 +00003247 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003248 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3249 BaseType),
3250 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003251 Results.EnterNewScope();
3252 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003253 // Indicate that we are performing a member access, and the cv-qualifiers
3254 // for the base object type.
3255 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3256
Douglas Gregor95ac6552009-11-18 01:29:26 +00003257 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003258 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003259 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003260 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3261 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003262
Douglas Gregor95ac6552009-11-18 01:29:26 +00003263 if (getLangOptions().CPlusPlus) {
3264 if (!Results.empty()) {
3265 // The "template" keyword can follow "->" or "." in the grammar.
3266 // However, we only want to suggest the template keyword if something
3267 // is dependent.
3268 bool IsDependent = BaseType->isDependentType();
3269 if (!IsDependent) {
3270 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3271 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3272 IsDependent = Ctx->isDependentContext();
3273 break;
3274 }
3275 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003276
Douglas Gregor95ac6552009-11-18 01:29:26 +00003277 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003278 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003279 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003280 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003281 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3282 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003283 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003284
3285 // Add property results based on our interface.
3286 const ObjCObjectPointerType *ObjCPtr
3287 = BaseType->getAsObjCInterfacePointerType();
3288 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003289 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3290 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003291 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003292
3293 // Add properties from the protocols in a qualified interface.
3294 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3295 E = ObjCPtr->qual_end();
3296 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003297 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3298 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003299 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003300 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003301 // Objective-C instance variable access.
3302 ObjCInterfaceDecl *Class = 0;
3303 if (const ObjCObjectPointerType *ObjCPtr
3304 = BaseType->getAs<ObjCObjectPointerType>())
3305 Class = ObjCPtr->getInterfaceDecl();
3306 else
John McCallc12c5bb2010-05-15 11:32:37 +00003307 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003308
3309 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003310 if (Class) {
3311 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3312 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003313 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3314 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003315 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003316 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003317
3318 // FIXME: How do we cope with isa?
3319
3320 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003321
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003322 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003323 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003324 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003325 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003326}
3327
Douglas Gregor374929f2009-09-18 15:37:17 +00003328void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3329 if (!CodeCompleter)
3330 return;
3331
John McCall0a2c5e22010-08-25 06:19:51 +00003332 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003333 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003334 enum CodeCompletionContext::Kind ContextKind
3335 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003336 switch ((DeclSpec::TST)TagSpec) {
3337 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003338 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003339 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003340 break;
3341
3342 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003343 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003344 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003345 break;
3346
3347 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003348 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003349 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003350 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003351 break;
3352
3353 default:
3354 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3355 return;
3356 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003357
Douglas Gregor218937c2011-02-01 19:23:04 +00003358 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003359 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003360
3361 // First pass: look for tags.
3362 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003363 LookupVisibleDecls(S, LookupTagName, Consumer,
3364 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003365
Douglas Gregor8071e422010-08-15 06:18:01 +00003366 if (CodeCompleter->includeGlobals()) {
3367 // Second pass: look for nested name specifiers.
3368 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3369 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3370 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003371
Douglas Gregor52779fb2010-09-23 23:01:17 +00003372 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003373 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003374}
3375
Douglas Gregor1a480c42010-08-27 17:35:51 +00003376void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003377 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3378 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003379 Results.EnterNewScope();
3380 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3381 Results.AddResult("const");
3382 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3383 Results.AddResult("volatile");
3384 if (getLangOptions().C99 &&
3385 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3386 Results.AddResult("restrict");
3387 Results.ExitScope();
3388 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003389 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003390 Results.data(), Results.size());
3391}
3392
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003393void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003394 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003395 return;
3396
John McCall781472f2010-08-25 08:40:02 +00003397 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003398 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003399 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3400 Data.IntegralConstantExpression = true;
3401 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003402 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003403 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003404
3405 // Code-complete the cases of a switch statement over an enumeration type
3406 // by providing the list of
3407 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3408
3409 // Determine which enumerators we have already seen in the switch statement.
3410 // FIXME: Ideally, we would also be able to look *past* the code-completion
3411 // token, in case we are code-completing in the middle of the switch and not
3412 // at the end. However, we aren't able to do so at the moment.
3413 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003414 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003415 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3416 SC = SC->getNextSwitchCase()) {
3417 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3418 if (!Case)
3419 continue;
3420
3421 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3422 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3423 if (EnumConstantDecl *Enumerator
3424 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3425 // We look into the AST of the case statement to determine which
3426 // enumerator was named. Alternatively, we could compute the value of
3427 // the integral constant expression, then compare it against the
3428 // values of each enumerator. However, value-based approach would not
3429 // work as well with C++ templates where enumerators declared within a
3430 // template are type- and value-dependent.
3431 EnumeratorsSeen.insert(Enumerator);
3432
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003433 // If this is a qualified-id, keep track of the nested-name-specifier
3434 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003435 //
3436 // switch (TagD.getKind()) {
3437 // case TagDecl::TK_enum:
3438 // break;
3439 // case XXX
3440 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003441 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003442 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3443 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003444 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003445 }
3446 }
3447
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003448 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3449 // If there are no prior enumerators in C++, check whether we have to
3450 // qualify the names of the enumerators that we suggest, because they
3451 // may not be visible in this scope.
3452 Qualifier = getRequiredQualification(Context, CurContext,
3453 Enum->getDeclContext());
3454
3455 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3456 }
3457
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003458 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003459 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3460 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003461 Results.EnterNewScope();
3462 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3463 EEnd = Enum->enumerator_end();
3464 E != EEnd; ++E) {
3465 if (EnumeratorsSeen.count(*E))
3466 continue;
3467
Douglas Gregor5c722c702011-02-18 23:30:37 +00003468 CodeCompletionResult R(*E, Qualifier);
3469 R.Priority = CCP_EnumInCase;
3470 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003471 }
3472 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003473
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003474 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003475 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003476 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor5c722c702011-02-18 23:30:37 +00003477 CodeCompletionContext::CCC_OtherWithMacros,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003478 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003479}
3480
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003481namespace {
3482 struct IsBetterOverloadCandidate {
3483 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003484 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003485
3486 public:
John McCall5769d612010-02-08 23:07:23 +00003487 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3488 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003489
3490 bool
3491 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003492 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003493 }
3494 };
3495}
3496
Douglas Gregord28dcd72010-05-30 06:10:08 +00003497static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3498 if (NumArgs && !Args)
3499 return true;
3500
3501 for (unsigned I = 0; I != NumArgs; ++I)
3502 if (!Args[I])
3503 return true;
3504
3505 return false;
3506}
3507
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003508void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3509 ExprTy **ArgsIn, unsigned NumArgs) {
3510 if (!CodeCompleter)
3511 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003512
3513 // When we're code-completing for a call, we fall back to ordinary
3514 // name code-completion whenever we can't produce specific
3515 // results. We may want to revisit this strategy in the future,
3516 // e.g., by merging the two kinds of results.
3517
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003518 Expr *Fn = (Expr *)FnIn;
3519 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003520
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003521 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003522 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003523 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003524 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003525 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003526 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003527
John McCall3b4294e2009-12-16 12:17:52 +00003528 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003529 SourceLocation Loc = Fn->getExprLoc();
3530 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003531
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003532 // FIXME: What if we're calling something that isn't a function declaration?
3533 // FIXME: What if we're calling a pseudo-destructor?
3534 // FIXME: What if we're calling a member function?
3535
Douglas Gregorc0265402010-01-21 15:46:19 +00003536 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3537 llvm::SmallVector<ResultCandidate, 8> Results;
3538
John McCall3b4294e2009-12-16 12:17:52 +00003539 Expr *NakedFn = Fn->IgnoreParenCasts();
3540 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3541 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3542 /*PartialOverloading=*/ true);
3543 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3544 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003545 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003546 if (!getLangOptions().CPlusPlus ||
3547 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003548 Results.push_back(ResultCandidate(FDecl));
3549 else
John McCall86820f52010-01-26 01:37:31 +00003550 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003551 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3552 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003553 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003554 }
John McCall3b4294e2009-12-16 12:17:52 +00003555 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003556
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003557 QualType ParamType;
3558
Douglas Gregorc0265402010-01-21 15:46:19 +00003559 if (!CandidateSet.empty()) {
3560 // Sort the overload candidate set by placing the best overloads first.
3561 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003562 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003563
Douglas Gregorc0265402010-01-21 15:46:19 +00003564 // Add the remaining viable overload candidates as code-completion reslults.
3565 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3566 CandEnd = CandidateSet.end();
3567 Cand != CandEnd; ++Cand) {
3568 if (Cand->Viable)
3569 Results.push_back(ResultCandidate(Cand->Function));
3570 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003571
3572 // From the viable candidates, try to determine the type of this parameter.
3573 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3574 if (const FunctionType *FType = Results[I].getFunctionType())
3575 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3576 if (NumArgs < Proto->getNumArgs()) {
3577 if (ParamType.isNull())
3578 ParamType = Proto->getArgType(NumArgs);
3579 else if (!Context.hasSameUnqualifiedType(
3580 ParamType.getNonReferenceType(),
3581 Proto->getArgType(NumArgs).getNonReferenceType())) {
3582 ParamType = QualType();
3583 break;
3584 }
3585 }
3586 }
3587 } else {
3588 // Try to determine the parameter type from the type of the expression
3589 // being called.
3590 QualType FunctionType = Fn->getType();
3591 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3592 FunctionType = Ptr->getPointeeType();
3593 else if (const BlockPointerType *BlockPtr
3594 = FunctionType->getAs<BlockPointerType>())
3595 FunctionType = BlockPtr->getPointeeType();
3596 else if (const MemberPointerType *MemPtr
3597 = FunctionType->getAs<MemberPointerType>())
3598 FunctionType = MemPtr->getPointeeType();
3599
3600 if (const FunctionProtoType *Proto
3601 = FunctionType->getAs<FunctionProtoType>()) {
3602 if (NumArgs < Proto->getNumArgs())
3603 ParamType = Proto->getArgType(NumArgs);
3604 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003605 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003606
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003607 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003608 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003609 else
3610 CodeCompleteExpression(S, ParamType);
3611
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003612 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003613 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3614 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003615}
3616
John McCalld226f652010-08-21 09:40:31 +00003617void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3618 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003619 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003620 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003621 return;
3622 }
3623
3624 CodeCompleteExpression(S, VD->getType());
3625}
3626
3627void Sema::CodeCompleteReturn(Scope *S) {
3628 QualType ResultType;
3629 if (isa<BlockDecl>(CurContext)) {
3630 if (BlockScopeInfo *BSI = getCurBlock())
3631 ResultType = BSI->ReturnType;
3632 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3633 ResultType = Function->getResultType();
3634 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3635 ResultType = Method->getResultType();
3636
3637 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003638 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003639 else
3640 CodeCompleteExpression(S, ResultType);
3641}
3642
3643void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3644 if (LHS)
3645 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3646 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003647 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003648}
3649
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003650void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003651 bool EnteringContext) {
3652 if (!SS.getScopeRep() || !CodeCompleter)
3653 return;
3654
Douglas Gregor86d9a522009-09-21 16:56:56 +00003655 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3656 if (!Ctx)
3657 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003658
3659 // Try to instantiate any non-dependent declaration contexts before
3660 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003661 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003662 return;
3663
Douglas Gregor218937c2011-02-01 19:23:04 +00003664 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3665 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003666 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003667
Douglas Gregor86d9a522009-09-21 16:56:56 +00003668 // The "template" keyword can follow "::" in the grammar, but only
3669 // put it into the grammar if the nested-name-specifier is dependent.
3670 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3671 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003672 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003673
3674 // Add calls to overridden virtual functions, if there are any.
3675 //
3676 // FIXME: This isn't wonderful, because we don't know whether we're actually
3677 // in a context that permits expressions. This is a general issue with
3678 // qualified-id completions.
3679 if (!EnteringContext)
3680 MaybeAddOverrideCalls(*this, Ctx, Results);
3681 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003682
Douglas Gregorf6961522010-08-27 21:18:54 +00003683 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3684 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3685
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003686 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003687 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003688 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003689}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003690
3691void Sema::CodeCompleteUsing(Scope *S) {
3692 if (!CodeCompleter)
3693 return;
3694
Douglas Gregor218937c2011-02-01 19:23:04 +00003695 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003696 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3697 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003698 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003699
3700 // If we aren't in class scope, we could see the "namespace" keyword.
3701 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003702 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003703
3704 // After "using", we can see anything that would start a
3705 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003706 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003707 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3708 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003709 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003710
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003711 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003712 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003713 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003714}
3715
3716void Sema::CodeCompleteUsingDirective(Scope *S) {
3717 if (!CodeCompleter)
3718 return;
3719
Douglas Gregor86d9a522009-09-21 16:56:56 +00003720 // After "using namespace", we expect to see a namespace name or namespace
3721 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003722 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3723 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003724 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003725 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003726 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003727 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3728 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003729 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003730 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003731 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003732 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003733}
3734
3735void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3736 if (!CodeCompleter)
3737 return;
3738
Douglas Gregor86d9a522009-09-21 16:56:56 +00003739 DeclContext *Ctx = (DeclContext *)S->getEntity();
3740 if (!S->getParent())
3741 Ctx = Context.getTranslationUnitDecl();
3742
Douglas Gregor52779fb2010-09-23 23:01:17 +00003743 bool SuppressedGlobalResults
3744 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3745
Douglas Gregor218937c2011-02-01 19:23:04 +00003746 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003747 SuppressedGlobalResults
3748 ? CodeCompletionContext::CCC_Namespace
3749 : CodeCompletionContext::CCC_Other,
3750 &ResultBuilder::IsNamespace);
3751
3752 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003753 // We only want to see those namespaces that have already been defined
3754 // within this scope, because its likely that the user is creating an
3755 // extended namespace declaration. Keep track of the most recent
3756 // definition of each namespace.
3757 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3758 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3759 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3760 NS != NSEnd; ++NS)
3761 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3762
3763 // Add the most recent definition (or extended definition) of each
3764 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003765 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003766 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3767 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3768 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003769 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003770 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003771 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003772 }
3773
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003774 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003775 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003776 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003777}
3778
3779void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3780 if (!CodeCompleter)
3781 return;
3782
Douglas Gregor86d9a522009-09-21 16:56:56 +00003783 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003784 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3785 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003786 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003787 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003788 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3789 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003790 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003791 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003792 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003793}
3794
Douglas Gregored8d3222009-09-18 20:05:18 +00003795void Sema::CodeCompleteOperatorName(Scope *S) {
3796 if (!CodeCompleter)
3797 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003798
John McCall0a2c5e22010-08-25 06:19:51 +00003799 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003800 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3801 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003802 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003803 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003804
Douglas Gregor86d9a522009-09-21 16:56:56 +00003805 // Add the names of overloadable operators.
3806#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3807 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003808 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003809#include "clang/Basic/OperatorKinds.def"
3810
3811 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003812 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003813 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003814 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3815 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003816
3817 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003818 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003819 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003820
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003821 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003822 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003823 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003824}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003825
Douglas Gregor0133f522010-08-28 00:00:50 +00003826void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003827 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003828 unsigned NumInitializers) {
John McCallf85e1932011-06-15 23:02:42 +00003829 PrintingPolicy Policy(Context.PrintingPolicy);
3830 Policy.AnonymousTagLocations = false;
3831 Policy.SuppressStrongLifetime = true;
3832
Douglas Gregor0133f522010-08-28 00:00:50 +00003833 CXXConstructorDecl *Constructor
3834 = static_cast<CXXConstructorDecl *>(ConstructorD);
3835 if (!Constructor)
3836 return;
3837
Douglas Gregor218937c2011-02-01 19:23:04 +00003838 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003839 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003840 Results.EnterNewScope();
3841
3842 // Fill in any already-initialized fields or base classes.
3843 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3844 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3845 for (unsigned I = 0; I != NumInitializers; ++I) {
3846 if (Initializers[I]->isBaseInitializer())
3847 InitializedBases.insert(
3848 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3849 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003850 InitializedFields.insert(cast<FieldDecl>(
3851 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003852 }
3853
3854 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003855 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003856 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003857 CXXRecordDecl *ClassDecl = Constructor->getParent();
3858 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3859 BaseEnd = ClassDecl->bases_end();
3860 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003861 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3862 SawLastInitializer
3863 = NumInitializers > 0 &&
3864 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3865 Context.hasSameUnqualifiedType(Base->getType(),
3866 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003867 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003868 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003869
Douglas Gregor218937c2011-02-01 19:23:04 +00003870 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003871 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003872 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3874 Builder.AddPlaceholderChunk("args");
3875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3876 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003877 SawLastInitializer? CCP_NextInitializer
3878 : CCP_MemberDeclaration));
3879 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003880 }
3881
3882 // Add completions for virtual base classes.
3883 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3884 BaseEnd = ClassDecl->vbases_end();
3885 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003886 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3887 SawLastInitializer
3888 = NumInitializers > 0 &&
3889 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3890 Context.hasSameUnqualifiedType(Base->getType(),
3891 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003892 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003893 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003894
Douglas Gregor218937c2011-02-01 19:23:04 +00003895 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003896 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003897 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003898 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3899 Builder.AddPlaceholderChunk("args");
3900 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3901 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003902 SawLastInitializer? CCP_NextInitializer
3903 : CCP_MemberDeclaration));
3904 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003905 }
3906
3907 // Add completions for members.
3908 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3909 FieldEnd = ClassDecl->field_end();
3910 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003911 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3912 SawLastInitializer
3913 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003914 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3915 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003916 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003917 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003918
3919 if (!Field->getDeclName())
3920 continue;
3921
Douglas Gregordae68752011-02-01 22:57:45 +00003922 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003923 Field->getIdentifier()->getName()));
3924 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3925 Builder.AddPlaceholderChunk("args");
3926 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3927 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003928 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003929 : CCP_MemberDeclaration,
3930 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003931 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003932 }
3933 Results.ExitScope();
3934
Douglas Gregor52779fb2010-09-23 23:01:17 +00003935 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003936 Results.data(), Results.size());
3937}
3938
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003939// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3940// true or false.
3941#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003942static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003943 ResultBuilder &Results,
3944 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003945 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003946 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003947 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003948
Douglas Gregor218937c2011-02-01 19:23:04 +00003949 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003950 if (LangOpts.ObjC2) {
3951 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003952 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3953 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3954 Builder.AddPlaceholderChunk("property");
3955 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003956
3957 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00003958 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3959 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3960 Builder.AddPlaceholderChunk("property");
3961 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003962 }
3963}
3964
Douglas Gregorbca403c2010-01-13 23:51:12 +00003965static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003966 ResultBuilder &Results,
3967 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003968 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003969
3970 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003971 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003972
3973 if (LangOpts.ObjC2) {
3974 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003975 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003976
3977 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003978 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003979
3980 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003981 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003982 }
3983}
3984
Douglas Gregorbca403c2010-01-13 23:51:12 +00003985static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003986 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003987 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003988
3989 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00003990 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3991 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3992 Builder.AddPlaceholderChunk("name");
3993 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003994
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003995 if (Results.includeCodePatterns()) {
3996 // @interface name
3997 // FIXME: Could introduce the whole pattern, including superclasses and
3998 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00003999 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4000 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4001 Builder.AddPlaceholderChunk("class");
4002 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004003
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004004 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004005 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4006 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4007 Builder.AddPlaceholderChunk("protocol");
4008 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004009
4010 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004011 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4012 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4013 Builder.AddPlaceholderChunk("class");
4014 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004015 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004016
4017 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004018 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4019 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4020 Builder.AddPlaceholderChunk("alias");
4021 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4022 Builder.AddPlaceholderChunk("class");
4023 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004024}
4025
John McCalld226f652010-08-21 09:40:31 +00004026void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00004027 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00004028 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004029 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4030 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004031 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004032 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004033 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004034 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004035 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004036 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004037 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004038 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004039 HandleCodeCompleteResults(this, CodeCompleter,
4040 CodeCompletionContext::CCC_Other,
4041 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004042}
4043
Douglas Gregorbca403c2010-01-13 23:51:12 +00004044static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004045 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004046 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004047
4048 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004049 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4050 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4051 Builder.AddPlaceholderChunk("type-name");
4052 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4053 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004054
4055 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004056 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4057 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4058 Builder.AddPlaceholderChunk("protocol-name");
4059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4060 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004061
4062 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004063 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4064 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4065 Builder.AddPlaceholderChunk("selector");
4066 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4067 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004068}
4069
Douglas Gregorbca403c2010-01-13 23:51:12 +00004070static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004071 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004072 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004073
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004074 if (Results.includeCodePatterns()) {
4075 // @try { statements } @catch ( declaration ) { statements } @finally
4076 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004077 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4078 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4079 Builder.AddPlaceholderChunk("statements");
4080 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4081 Builder.AddTextChunk("@catch");
4082 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4083 Builder.AddPlaceholderChunk("parameter");
4084 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4085 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4086 Builder.AddPlaceholderChunk("statements");
4087 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4088 Builder.AddTextChunk("@finally");
4089 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4090 Builder.AddPlaceholderChunk("statements");
4091 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4092 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004093 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004094
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004095 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004096 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4097 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4098 Builder.AddPlaceholderChunk("expression");
4099 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004100
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004101 if (Results.includeCodePatterns()) {
4102 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004103 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4104 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4105 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4106 Builder.AddPlaceholderChunk("expression");
4107 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4108 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4109 Builder.AddPlaceholderChunk("statements");
4110 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4111 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004112 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004113}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004114
Douglas Gregorbca403c2010-01-13 23:51:12 +00004115static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004116 ResultBuilder &Results,
4117 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004118 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004119 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4120 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4121 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004122 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004123 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004124}
4125
4126void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004127 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4128 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004129 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004130 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004131 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004132 HandleCodeCompleteResults(this, CodeCompleter,
4133 CodeCompletionContext::CCC_Other,
4134 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004135}
4136
4137void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004138 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4139 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004140 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004141 AddObjCStatementResults(Results, false);
4142 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004143 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004144 HandleCodeCompleteResults(this, CodeCompleter,
4145 CodeCompletionContext::CCC_Other,
4146 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004147}
4148
4149void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004150 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4151 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004152 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004153 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004154 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004155 HandleCodeCompleteResults(this, CodeCompleter,
4156 CodeCompletionContext::CCC_Other,
4157 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004158}
4159
Douglas Gregor988358f2009-11-19 00:14:45 +00004160/// \brief Determine whether the addition of the given flag to an Objective-C
4161/// property's attributes will cause a conflict.
4162static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4163 // Check if we've already added this flag.
4164 if (Attributes & NewFlag)
4165 return true;
4166
4167 Attributes |= NewFlag;
4168
4169 // Check for collisions with "readonly".
4170 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4171 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4172 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004173 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004174 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004175 ObjCDeclSpec::DQ_PR_retain |
4176 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004177 return true;
4178
John McCallf85e1932011-06-15 23:02:42 +00004179 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004180 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004181 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004182 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004183 ObjCDeclSpec::DQ_PR_retain|
4184 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004185 if (AssignCopyRetMask &&
4186 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004187 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004188 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004189 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4190 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004191 return true;
4192
4193 return false;
4194}
4195
Douglas Gregora93b1082009-11-18 23:08:07 +00004196void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004197 if (!CodeCompleter)
4198 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004199
Steve Naroffece8e712009-10-08 21:55:05 +00004200 unsigned Attributes = ODS.getPropertyAttributes();
4201
John McCall0a2c5e22010-08-25 06:19:51 +00004202 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004203 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4204 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004205 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004206 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004207 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004208 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004209 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004210 if (!ObjCPropertyFlagConflicts(Attributes,
4211 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4212 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004213 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004214 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004215 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004216 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004217 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4218 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004219 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004220 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004221 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004222 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004223 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4224 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004225 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004226 CodeCompletionBuilder Setter(Results.getAllocator());
4227 Setter.AddTypedTextChunk("setter");
4228 Setter.AddTextChunk(" = ");
4229 Setter.AddPlaceholderChunk("method");
4230 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004231 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004232 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004233 CodeCompletionBuilder Getter(Results.getAllocator());
4234 Getter.AddTypedTextChunk("getter");
4235 Getter.AddTextChunk(" = ");
4236 Getter.AddPlaceholderChunk("method");
4237 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004238 }
Steve Naroffece8e712009-10-08 21:55:05 +00004239 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004240 HandleCodeCompleteResults(this, CodeCompleter,
4241 CodeCompletionContext::CCC_Other,
4242 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004243}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004244
Douglas Gregor4ad96852009-11-19 07:41:15 +00004245/// \brief Descripts the kind of Objective-C method that we want to find
4246/// via code completion.
4247enum ObjCMethodKind {
4248 MK_Any, //< Any kind of method, provided it means other specified criteria.
4249 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4250 MK_OneArgSelector //< One-argument selector.
4251};
4252
Douglas Gregor458433d2010-08-26 15:07:07 +00004253static bool isAcceptableObjCSelector(Selector Sel,
4254 ObjCMethodKind WantKind,
4255 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004256 unsigned NumSelIdents,
4257 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004258 if (NumSelIdents > Sel.getNumArgs())
4259 return false;
4260
4261 switch (WantKind) {
4262 case MK_Any: break;
4263 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4264 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4265 }
4266
Douglas Gregorcf544262010-11-17 21:36:08 +00004267 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4268 return false;
4269
Douglas Gregor458433d2010-08-26 15:07:07 +00004270 for (unsigned I = 0; I != NumSelIdents; ++I)
4271 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4272 return false;
4273
4274 return true;
4275}
4276
Douglas Gregor4ad96852009-11-19 07:41:15 +00004277static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4278 ObjCMethodKind WantKind,
4279 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004280 unsigned NumSelIdents,
4281 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004282 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004283 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004284}
Douglas Gregord36adf52010-09-16 16:06:31 +00004285
4286namespace {
4287 /// \brief A set of selectors, which is used to avoid introducing multiple
4288 /// completions with the same selector into the result set.
4289 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4290}
4291
Douglas Gregor36ecb042009-11-17 23:22:23 +00004292/// \brief Add all of the Objective-C methods in the given Objective-C
4293/// container to the set of results.
4294///
4295/// The container will be a class, protocol, category, or implementation of
4296/// any of the above. This mether will recurse to include methods from
4297/// the superclasses of classes along with their categories, protocols, and
4298/// implementations.
4299///
4300/// \param Container the container in which we'll look to find methods.
4301///
4302/// \param WantInstance whether to add instance methods (only); if false, this
4303/// routine will add factory methods (only).
4304///
4305/// \param CurContext the context in which we're performing the lookup that
4306/// finds methods.
4307///
Douglas Gregorcf544262010-11-17 21:36:08 +00004308/// \param AllowSameLength Whether we allow a method to be added to the list
4309/// when it has the same number of parameters as we have selector identifiers.
4310///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004311/// \param Results the structure into which we'll add results.
4312static void AddObjCMethods(ObjCContainerDecl *Container,
4313 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004314 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004315 IdentifierInfo **SelIdents,
4316 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004317 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004318 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004319 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004320 ResultBuilder &Results,
4321 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004322 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004323 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4324 MEnd = Container->meth_end();
4325 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004326 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4327 // Check whether the selector identifiers we've been given are a
4328 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004329 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4330 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004331 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004332
Douglas Gregord36adf52010-09-16 16:06:31 +00004333 if (!Selectors.insert((*M)->getSelector()))
4334 continue;
4335
Douglas Gregord3c68542009-11-19 01:08:35 +00004336 Result R = Result(*M, 0);
4337 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004338 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004339 if (!InOriginalClass)
4340 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004341 Results.MaybeAddResult(R, CurContext);
4342 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004343 }
4344
Douglas Gregore396c7b2010-09-16 15:34:59 +00004345 // Visit the protocols of protocols.
4346 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4347 const ObjCList<ObjCProtocolDecl> &Protocols
4348 = Protocol->getReferencedProtocols();
4349 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4350 E = Protocols.end();
4351 I != E; ++I)
4352 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004353 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004354 }
4355
Douglas Gregor36ecb042009-11-17 23:22:23 +00004356 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4357 if (!IFace)
4358 return;
4359
4360 // Add methods in protocols.
4361 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4362 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4363 E = Protocols.end();
4364 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004365 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004366 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004367
4368 // Add methods in categories.
4369 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4370 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004371 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004372 NumSelIdents, CurContext, Selectors, AllowSameLength,
4373 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004374
4375 // Add a categories protocol methods.
4376 const ObjCList<ObjCProtocolDecl> &Protocols
4377 = CatDecl->getReferencedProtocols();
4378 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4379 E = Protocols.end();
4380 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004381 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004382 NumSelIdents, CurContext, Selectors, AllowSameLength,
4383 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004384
4385 // Add methods in category implementations.
4386 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004387 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004388 NumSelIdents, CurContext, Selectors, AllowSameLength,
4389 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004390 }
4391
4392 // Add methods in superclass.
4393 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004394 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004395 SelIdents, NumSelIdents, CurContext, Selectors,
4396 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004397
4398 // Add methods in our implementation, if any.
4399 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004400 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004401 NumSelIdents, CurContext, Selectors, AllowSameLength,
4402 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004403}
4404
4405
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004406void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004407 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004408
4409 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004410 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004411 if (!Class) {
4412 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004413 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004414 Class = Category->getClassInterface();
4415
4416 if (!Class)
4417 return;
4418 }
4419
4420 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004421 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4422 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004423 Results.EnterNewScope();
4424
Douglas Gregord36adf52010-09-16 16:06:31 +00004425 VisitedSelectorSet Selectors;
4426 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004427 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004428 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004429 HandleCodeCompleteResults(this, CodeCompleter,
4430 CodeCompletionContext::CCC_Other,
4431 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004432}
4433
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004434void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004435 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004436
4437 // Try to find the interface where setters might live.
4438 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004439 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004440 if (!Class) {
4441 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004442 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004443 Class = Category->getClassInterface();
4444
4445 if (!Class)
4446 return;
4447 }
4448
4449 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004450 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4451 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004452 Results.EnterNewScope();
4453
Douglas Gregord36adf52010-09-16 16:06:31 +00004454 VisitedSelectorSet Selectors;
4455 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004456 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004457
4458 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004459 HandleCodeCompleteResults(this, CodeCompleter,
4460 CodeCompletionContext::CCC_Other,
4461 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004462}
4463
Douglas Gregorafc45782011-02-15 22:19:42 +00004464void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4465 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004466 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004467 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4468 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004469 Results.EnterNewScope();
4470
4471 // Add context-sensitive, Objective-C parameter-passing keywords.
4472 bool AddedInOut = false;
4473 if ((DS.getObjCDeclQualifier() &
4474 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4475 Results.AddResult("in");
4476 Results.AddResult("inout");
4477 AddedInOut = true;
4478 }
4479 if ((DS.getObjCDeclQualifier() &
4480 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4481 Results.AddResult("out");
4482 if (!AddedInOut)
4483 Results.AddResult("inout");
4484 }
4485 if ((DS.getObjCDeclQualifier() &
4486 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4487 ObjCDeclSpec::DQ_Oneway)) == 0) {
4488 Results.AddResult("bycopy");
4489 Results.AddResult("byref");
4490 Results.AddResult("oneway");
4491 }
4492
Douglas Gregorafc45782011-02-15 22:19:42 +00004493 // If we're completing the return type of an Objective-C method and the
4494 // identifier IBAction refers to a macro, provide a completion item for
4495 // an action, e.g.,
4496 // IBAction)<#selector#>:(id)sender
4497 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4498 Context.Idents.get("IBAction").hasMacroDefinition()) {
4499 typedef CodeCompletionString::Chunk Chunk;
4500 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4501 CXAvailability_Available);
4502 Builder.AddTypedTextChunk("IBAction");
4503 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4504 Builder.AddPlaceholderChunk("selector");
4505 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4506 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4507 Builder.AddTextChunk("id");
4508 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4509 Builder.AddTextChunk("sender");
4510 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4511 }
4512
Douglas Gregord32b0222010-08-24 01:06:58 +00004513 // Add various builtin type names and specifiers.
4514 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4515 Results.ExitScope();
4516
4517 // Add the various type names
4518 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4519 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4520 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4521 CodeCompleter->includeGlobals());
4522
4523 if (CodeCompleter->includeMacros())
4524 AddMacroResults(PP, Results);
4525
4526 HandleCodeCompleteResults(this, CodeCompleter,
4527 CodeCompletionContext::CCC_Type,
4528 Results.data(), Results.size());
4529}
4530
Douglas Gregor22f56992010-04-06 19:22:33 +00004531/// \brief When we have an expression with type "id", we may assume
4532/// that it has some more-specific class type based on knowledge of
4533/// common uses of Objective-C. This routine returns that class type,
4534/// or NULL if no better result could be determined.
4535static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004536 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004537 if (!Msg)
4538 return 0;
4539
4540 Selector Sel = Msg->getSelector();
4541 if (Sel.isNull())
4542 return 0;
4543
4544 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4545 if (!Id)
4546 return 0;
4547
4548 ObjCMethodDecl *Method = Msg->getMethodDecl();
4549 if (!Method)
4550 return 0;
4551
4552 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004553 ObjCInterfaceDecl *IFace = 0;
4554 switch (Msg->getReceiverKind()) {
4555 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004556 if (const ObjCObjectType *ObjType
4557 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4558 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004559 break;
4560
4561 case ObjCMessageExpr::Instance: {
4562 QualType T = Msg->getInstanceReceiver()->getType();
4563 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4564 IFace = Ptr->getInterfaceDecl();
4565 break;
4566 }
4567
4568 case ObjCMessageExpr::SuperInstance:
4569 case ObjCMessageExpr::SuperClass:
4570 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004571 }
4572
4573 if (!IFace)
4574 return 0;
4575
4576 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4577 if (Method->isInstanceMethod())
4578 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4579 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004580 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004581 .Case("autorelease", IFace)
4582 .Case("copy", IFace)
4583 .Case("copyWithZone", IFace)
4584 .Case("mutableCopy", IFace)
4585 .Case("mutableCopyWithZone", IFace)
4586 .Case("awakeFromCoder", IFace)
4587 .Case("replacementObjectFromCoder", IFace)
4588 .Case("class", IFace)
4589 .Case("classForCoder", IFace)
4590 .Case("superclass", Super)
4591 .Default(0);
4592
4593 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4594 .Case("new", IFace)
4595 .Case("alloc", IFace)
4596 .Case("allocWithZone", IFace)
4597 .Case("class", IFace)
4598 .Case("superclass", Super)
4599 .Default(0);
4600}
4601
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004602// Add a special completion for a message send to "super", which fills in the
4603// most likely case of forwarding all of our arguments to the superclass
4604// function.
4605///
4606/// \param S The semantic analysis object.
4607///
4608/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4609/// the "super" keyword. Otherwise, we just need to provide the arguments.
4610///
4611/// \param SelIdents The identifiers in the selector that have already been
4612/// provided as arguments for a send to "super".
4613///
4614/// \param NumSelIdents The number of identifiers in \p SelIdents.
4615///
4616/// \param Results The set of results to augment.
4617///
4618/// \returns the Objective-C method declaration that would be invoked by
4619/// this "super" completion. If NULL, no completion was added.
4620static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4621 IdentifierInfo **SelIdents,
4622 unsigned NumSelIdents,
4623 ResultBuilder &Results) {
4624 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4625 if (!CurMethod)
4626 return 0;
4627
4628 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4629 if (!Class)
4630 return 0;
4631
4632 // Try to find a superclass method with the same selector.
4633 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004634 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4635 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004636 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4637 CurMethod->isInstanceMethod());
4638
Douglas Gregor78bcd912011-02-16 00:51:18 +00004639 // Check in categories or class extensions.
4640 if (!SuperMethod) {
4641 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4642 Category = Category->getNextClassCategory())
4643 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4644 CurMethod->isInstanceMethod())))
4645 break;
4646 }
4647 }
4648
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004649 if (!SuperMethod)
4650 return 0;
4651
4652 // Check whether the superclass method has the same signature.
4653 if (CurMethod->param_size() != SuperMethod->param_size() ||
4654 CurMethod->isVariadic() != SuperMethod->isVariadic())
4655 return 0;
4656
4657 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4658 CurPEnd = CurMethod->param_end(),
4659 SuperP = SuperMethod->param_begin();
4660 CurP != CurPEnd; ++CurP, ++SuperP) {
4661 // Make sure the parameter types are compatible.
4662 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4663 (*SuperP)->getType()))
4664 return 0;
4665
4666 // Make sure we have a parameter name to forward!
4667 if (!(*CurP)->getIdentifier())
4668 return 0;
4669 }
4670
4671 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004672 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004673
4674 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004675 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004676
4677 // If we need the "super" keyword, add it (plus some spacing).
4678 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004679 Builder.AddTypedTextChunk("super");
4680 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004681 }
4682
4683 Selector Sel = CurMethod->getSelector();
4684 if (Sel.isUnarySelector()) {
4685 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004686 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004687 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004688 else
Douglas Gregordae68752011-02-01 22:57:45 +00004689 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004690 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004691 } else {
4692 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4693 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4694 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004695 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004696
4697 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004698 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004699 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004700 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004701 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004702 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004703 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004704 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004705 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004706 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004707 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004708 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004709 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004710 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004711 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004712 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004713 }
4714 }
4715 }
4716
Douglas Gregor218937c2011-02-01 19:23:04 +00004717 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004718 SuperMethod->isInstanceMethod()
4719 ? CXCursor_ObjCInstanceMethodDecl
4720 : CXCursor_ObjCClassMethodDecl));
4721 return SuperMethod;
4722}
4723
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004724void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004725 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004726 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4727 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004728 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004729
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004730 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4731 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004732 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4733 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004734
4735 // If we are in an Objective-C method inside a class that has a superclass,
4736 // add "super" as an option.
4737 if (ObjCMethodDecl *Method = getCurMethodDecl())
4738 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004739 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004740 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004741
4742 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4743 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004744
4745 Results.ExitScope();
4746
4747 if (CodeCompleter->includeMacros())
4748 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004749 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004750 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004751
4752}
4753
Douglas Gregor2725ca82010-04-21 19:57:20 +00004754void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4755 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004756 unsigned NumSelIdents,
4757 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004758 ObjCInterfaceDecl *CDecl = 0;
4759 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4760 // Figure out which interface we're in.
4761 CDecl = CurMethod->getClassInterface();
4762 if (!CDecl)
4763 return;
4764
4765 // Find the superclass of this class.
4766 CDecl = CDecl->getSuperClass();
4767 if (!CDecl)
4768 return;
4769
4770 if (CurMethod->isInstanceMethod()) {
4771 // We are inside an instance method, which means that the message
4772 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004773 // current object.
4774 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004775 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004776 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004777 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004778 }
4779
4780 // Fall through to send to the superclass in CDecl.
4781 } else {
4782 // "super" may be the name of a type or variable. Figure out which
4783 // it is.
4784 IdentifierInfo *Super = &Context.Idents.get("super");
4785 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4786 LookupOrdinaryName);
4787 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4788 // "super" names an interface. Use it.
4789 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004790 if (const ObjCObjectType *Iface
4791 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4792 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004793 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4794 // "super" names an unresolved type; we can't be more specific.
4795 } else {
4796 // Assume that "super" names some kind of value and parse that way.
4797 CXXScopeSpec SS;
4798 UnqualifiedId id;
4799 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004800 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004801 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004802 SelIdents, NumSelIdents,
4803 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004804 }
4805
4806 // Fall through
4807 }
4808
John McCallb3d87482010-08-24 05:47:05 +00004809 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004810 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004811 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004812 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004813 NumSelIdents, AtArgumentExpression,
4814 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004815}
4816
Douglas Gregorb9d77572010-09-21 00:03:25 +00004817/// \brief Given a set of code-completion results for the argument of a message
4818/// send, determine the preferred type (if any) for that argument expression.
4819static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4820 unsigned NumSelIdents) {
4821 typedef CodeCompletionResult Result;
4822 ASTContext &Context = Results.getSema().Context;
4823
4824 QualType PreferredType;
4825 unsigned BestPriority = CCP_Unlikely * 2;
4826 Result *ResultsData = Results.data();
4827 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4828 Result &R = ResultsData[I];
4829 if (R.Kind == Result::RK_Declaration &&
4830 isa<ObjCMethodDecl>(R.Declaration)) {
4831 if (R.Priority <= BestPriority) {
4832 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4833 if (NumSelIdents <= Method->param_size()) {
4834 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4835 ->getType();
4836 if (R.Priority < BestPriority || PreferredType.isNull()) {
4837 BestPriority = R.Priority;
4838 PreferredType = MyPreferredType;
4839 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4840 MyPreferredType)) {
4841 PreferredType = QualType();
4842 }
4843 }
4844 }
4845 }
4846 }
4847
4848 return PreferredType;
4849}
4850
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004851static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4852 ParsedType Receiver,
4853 IdentifierInfo **SelIdents,
4854 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004855 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004856 bool IsSuper,
4857 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004858 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004859 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004860
Douglas Gregor24a069f2009-11-17 17:59:40 +00004861 // If the given name refers to an interface type, retrieve the
4862 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004863 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004864 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004865 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004866 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4867 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004868 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004869
Douglas Gregor36ecb042009-11-17 23:22:23 +00004870 // Add all of the factory methods in this Objective-C class, its protocols,
4871 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004872 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004873
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004874 // If this is a send-to-super, try to add the special "super" send
4875 // completion.
4876 if (IsSuper) {
4877 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004878 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4879 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004880 Results.Ignore(SuperMethod);
4881 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004882
Douglas Gregor265f7492010-08-27 15:29:55 +00004883 // If we're inside an Objective-C method definition, prefer its selector to
4884 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004885 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004886 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004887
Douglas Gregord36adf52010-09-16 16:06:31 +00004888 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004889 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004890 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004891 SemaRef.CurContext, Selectors, AtArgumentExpression,
4892 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004893 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004894 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004895
Douglas Gregor719770d2010-04-06 17:30:22 +00004896 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004897 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004898 if (SemaRef.ExternalSource) {
4899 for (uint32_t I = 0,
4900 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004901 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004902 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4903 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004904 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004905
4906 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004907 }
4908 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004909
4910 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4911 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004912 M != MEnd; ++M) {
4913 for (ObjCMethodList *MethList = &M->second.second;
4914 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004915 MethList = MethList->Next) {
4916 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4917 NumSelIdents))
4918 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004919
Douglas Gregor13438f92010-04-06 16:40:00 +00004920 Result R(MethList->Method, 0);
4921 R.StartParameter = NumSelIdents;
4922 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004923 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004924 }
4925 }
4926 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004927
4928 Results.ExitScope();
4929}
Douglas Gregor13438f92010-04-06 16:40:00 +00004930
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004931void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4932 IdentifierInfo **SelIdents,
4933 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004934 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004935 bool IsSuper) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004936 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4937 CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004938 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4939 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004940
4941 // If we're actually at the argument expression (rather than prior to the
4942 // selector), we're actually performing code completion for an expression.
4943 // Determine whether we have a single, best method. If so, we can
4944 // code-complete the expression using the corresponding parameter type as
4945 // our preferred type, improving completion results.
4946 if (AtArgumentExpression) {
4947 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4948 NumSelIdents);
4949 if (PreferredType.isNull())
4950 CodeCompleteOrdinaryName(S, PCC_Expression);
4951 else
4952 CodeCompleteExpression(S, PreferredType);
4953 return;
4954 }
4955
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004956 HandleCodeCompleteResults(this, CodeCompleter,
4957 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004958 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004959}
4960
Douglas Gregord3c68542009-11-19 01:08:35 +00004961void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4962 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004963 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004964 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004965 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004966 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004967
4968 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004969
Douglas Gregor36ecb042009-11-17 23:22:23 +00004970 // If necessary, apply function/array conversion to the receiver.
4971 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00004972 if (RecExpr) {
4973 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
4974 if (Conv.isInvalid()) // conversion failed. bail.
4975 return;
4976 RecExpr = Conv.take();
4977 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004978 QualType ReceiverType = RecExpr? RecExpr->getType()
4979 : Super? Context.getObjCObjectPointerType(
4980 Context.getObjCInterfaceType(Super))
4981 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004982
Douglas Gregorda892642010-11-08 21:12:30 +00004983 // If we're messaging an expression with type "id" or "Class", check
4984 // whether we know something special about the receiver that allows
4985 // us to assume a more-specific receiver type.
4986 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4987 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
4988 if (ReceiverType->isObjCClassType())
4989 return CodeCompleteObjCClassMessage(S,
4990 ParsedType::make(Context.getObjCInterfaceType(IFace)),
4991 SelIdents, NumSelIdents,
4992 AtArgumentExpression, Super);
4993
4994 ReceiverType = Context.getObjCObjectPointerType(
4995 Context.getObjCInterfaceType(IFace));
4996 }
4997
Douglas Gregor36ecb042009-11-17 23:22:23 +00004998 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00004999 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5000 CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00005001 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005002
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005003 // If this is a send-to-super, try to add the special "super" send
5004 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005005 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005006 if (ObjCMethodDecl *SuperMethod
5007 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5008 Results))
5009 Results.Ignore(SuperMethod);
5010 }
5011
Douglas Gregor265f7492010-08-27 15:29:55 +00005012 // If we're inside an Objective-C method definition, prefer its selector to
5013 // others.
5014 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5015 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005016
Douglas Gregord36adf52010-09-16 16:06:31 +00005017 // Keep track of the selectors we've already added.
5018 VisitedSelectorSet Selectors;
5019
Douglas Gregorf74a4192009-11-18 00:06:18 +00005020 // Handle messages to Class. This really isn't a message to an instance
5021 // method, so we treat it the same way we would treat a message send to a
5022 // class method.
5023 if (ReceiverType->isObjCClassType() ||
5024 ReceiverType->isObjCQualifiedClassType()) {
5025 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5026 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005027 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005028 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005029 }
5030 }
5031 // Handle messages to a qualified ID ("id<foo>").
5032 else if (const ObjCObjectPointerType *QualID
5033 = ReceiverType->getAsObjCQualifiedIdType()) {
5034 // Search protocols for instance methods.
5035 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5036 E = QualID->qual_end();
5037 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005038 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005039 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005040 }
5041 // Handle messages to a pointer to interface type.
5042 else if (const ObjCObjectPointerType *IFacePtr
5043 = ReceiverType->getAsObjCInterfacePointerType()) {
5044 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005045 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005046 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5047 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005048
5049 // Search protocols for instance methods.
5050 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5051 E = IFacePtr->qual_end();
5052 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005053 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005054 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005055 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005056 // Handle messages to "id".
5057 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005058 // We're messaging "id", so provide all instance methods we know
5059 // about as code-completion results.
5060
5061 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005062 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005063 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005064 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5065 I != N; ++I) {
5066 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005067 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005068 continue;
5069
Sebastian Redldb9d2142010-08-02 23:18:59 +00005070 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005071 }
5072 }
5073
Sebastian Redldb9d2142010-08-02 23:18:59 +00005074 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5075 MEnd = MethodPool.end();
5076 M != MEnd; ++M) {
5077 for (ObjCMethodList *MethList = &M->second.first;
5078 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005079 MethList = MethList->Next) {
5080 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5081 NumSelIdents))
5082 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005083
5084 if (!Selectors.insert(MethList->Method->getSelector()))
5085 continue;
5086
Douglas Gregor13438f92010-04-06 16:40:00 +00005087 Result R(MethList->Method, 0);
5088 R.StartParameter = NumSelIdents;
5089 R.AllParametersAreInformative = false;
5090 Results.MaybeAddResult(R, CurContext);
5091 }
5092 }
5093 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005094 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005095
5096
5097 // If we're actually at the argument expression (rather than prior to the
5098 // selector), we're actually performing code completion for an expression.
5099 // Determine whether we have a single, best method. If so, we can
5100 // code-complete the expression using the corresponding parameter type as
5101 // our preferred type, improving completion results.
5102 if (AtArgumentExpression) {
5103 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5104 NumSelIdents);
5105 if (PreferredType.isNull())
5106 CodeCompleteOrdinaryName(S, PCC_Expression);
5107 else
5108 CodeCompleteExpression(S, PreferredType);
5109 return;
5110 }
5111
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005112 HandleCodeCompleteResults(this, CodeCompleter,
5113 CodeCompletionContext::CCC_Other,
5114 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005115}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005116
Douglas Gregorfb629412010-08-23 21:17:50 +00005117void Sema::CodeCompleteObjCForCollection(Scope *S,
5118 DeclGroupPtrTy IterationVar) {
5119 CodeCompleteExpressionData Data;
5120 Data.ObjCCollection = true;
5121
5122 if (IterationVar.getAsOpaquePtr()) {
5123 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5124 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5125 if (*I)
5126 Data.IgnoreDecls.push_back(*I);
5127 }
5128 }
5129
5130 CodeCompleteExpression(S, Data);
5131}
5132
Douglas Gregor458433d2010-08-26 15:07:07 +00005133void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5134 unsigned NumSelIdents) {
5135 // If we have an external source, load the entire class method
5136 // pool from the AST file.
5137 if (ExternalSource) {
5138 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5139 I != N; ++I) {
5140 Selector Sel = ExternalSource->GetExternalSelector(I);
5141 if (Sel.isNull() || MethodPool.count(Sel))
5142 continue;
5143
5144 ReadMethodPool(Sel);
5145 }
5146 }
5147
Douglas Gregor218937c2011-02-01 19:23:04 +00005148 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5149 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005150 Results.EnterNewScope();
5151 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5152 MEnd = MethodPool.end();
5153 M != MEnd; ++M) {
5154
5155 Selector Sel = M->first;
5156 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5157 continue;
5158
Douglas Gregor218937c2011-02-01 19:23:04 +00005159 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005160 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005161 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005162 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005163 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005164 continue;
5165 }
5166
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005167 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005168 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005169 if (I == NumSelIdents) {
5170 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005171 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005172 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005173 Accumulator.clear();
5174 }
5175 }
5176
Douglas Gregor813d8342011-02-18 22:29:55 +00005177 Accumulator += Sel.getNameForSlot(I).str();
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005178 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005179 }
Douglas Gregordae68752011-02-01 22:57:45 +00005180 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005181 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005182 }
5183 Results.ExitScope();
5184
5185 HandleCodeCompleteResults(this, CodeCompleter,
5186 CodeCompletionContext::CCC_SelectorName,
5187 Results.data(), Results.size());
5188}
5189
Douglas Gregor55385fe2009-11-18 04:19:12 +00005190/// \brief Add all of the protocol declarations that we find in the given
5191/// (translation unit) context.
5192static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005193 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005194 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005195 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005196
5197 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5198 DEnd = Ctx->decls_end();
5199 D != DEnd; ++D) {
5200 // Record any protocols we find.
5201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005202 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005203 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005204
5205 // Record any forward-declared protocols we find.
5206 if (ObjCForwardProtocolDecl *Forward
5207 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5208 for (ObjCForwardProtocolDecl::protocol_iterator
5209 P = Forward->protocol_begin(),
5210 PEnd = Forward->protocol_end();
5211 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005212 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005213 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005214 }
5215 }
5216}
5217
5218void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5219 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005220 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5221 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005222
Douglas Gregor70c23352010-12-09 21:44:02 +00005223 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5224 Results.EnterNewScope();
5225
5226 // Tell the result set to ignore all of the protocols we have
5227 // already seen.
5228 // FIXME: This doesn't work when caching code-completion results.
5229 for (unsigned I = 0; I != NumProtocols; ++I)
5230 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5231 Protocols[I].second))
5232 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005233
Douglas Gregor70c23352010-12-09 21:44:02 +00005234 // Add all protocols.
5235 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5236 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005237
Douglas Gregor70c23352010-12-09 21:44:02 +00005238 Results.ExitScope();
5239 }
5240
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005241 HandleCodeCompleteResults(this, CodeCompleter,
5242 CodeCompletionContext::CCC_ObjCProtocolName,
5243 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005244}
5245
5246void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005247 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5248 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005249
Douglas Gregor70c23352010-12-09 21:44:02 +00005250 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5251 Results.EnterNewScope();
5252
5253 // Add all protocols.
5254 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5255 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005256
Douglas Gregor70c23352010-12-09 21:44:02 +00005257 Results.ExitScope();
5258 }
5259
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005260 HandleCodeCompleteResults(this, CodeCompleter,
5261 CodeCompletionContext::CCC_ObjCProtocolName,
5262 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005263}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005264
5265/// \brief Add all of the Objective-C interface declarations that we find in
5266/// the given (translation unit) context.
5267static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5268 bool OnlyForwardDeclarations,
5269 bool OnlyUnimplemented,
5270 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005271 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005272
5273 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5274 DEnd = Ctx->decls_end();
5275 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005276 // Record any interfaces we find.
5277 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5278 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5279 (!OnlyUnimplemented || !Class->getImplementation()))
5280 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005281
5282 // Record any forward-declared interfaces we find.
5283 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5284 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005285 C != CEnd; ++C)
5286 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5287 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5288 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005289 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005290 }
5291 }
5292}
5293
5294void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005295 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5296 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005297 Results.EnterNewScope();
5298
5299 // Add all classes.
5300 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5301 false, Results);
5302
5303 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005304 // FIXME: Add a special context for this, use cached global completion
5305 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005306 HandleCodeCompleteResults(this, CodeCompleter,
5307 CodeCompletionContext::CCC_Other,
5308 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005309}
5310
Douglas Gregorc83c6872010-04-15 22:33:43 +00005311void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5312 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005313 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5314 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005315 Results.EnterNewScope();
5316
5317 // Make sure that we ignore the class we're currently defining.
5318 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005319 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005320 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005321 Results.Ignore(CurClass);
5322
5323 // Add all classes.
5324 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5325 false, Results);
5326
5327 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005328 // FIXME: Add a special context for this, use cached global completion
5329 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005330 HandleCodeCompleteResults(this, CodeCompleter,
5331 CodeCompletionContext::CCC_Other,
5332 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005333}
5334
5335void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005336 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5337 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005338 Results.EnterNewScope();
5339
5340 // Add all unimplemented classes.
5341 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5342 true, Results);
5343
5344 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005345 // FIXME: Add a special context for this, use cached global completion
5346 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005347 HandleCodeCompleteResults(this, CodeCompleter,
5348 CodeCompletionContext::CCC_Other,
5349 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005350}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005351
5352void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005353 IdentifierInfo *ClassName,
5354 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005355 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005356
Douglas Gregor218937c2011-02-01 19:23:04 +00005357 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5358 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005359
5360 // Ignore any categories we find that have already been implemented by this
5361 // interface.
5362 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5363 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005364 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005365 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5366 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5367 Category = Category->getNextClassCategory())
5368 CategoryNames.insert(Category->getIdentifier());
5369
5370 // Add all of the categories we know about.
5371 Results.EnterNewScope();
5372 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5373 for (DeclContext::decl_iterator D = TU->decls_begin(),
5374 DEnd = TU->decls_end();
5375 D != DEnd; ++D)
5376 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5377 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005378 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005379 Results.ExitScope();
5380
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005381 HandleCodeCompleteResults(this, CodeCompleter,
5382 CodeCompletionContext::CCC_Other,
5383 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005384}
5385
5386void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005387 IdentifierInfo *ClassName,
5388 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005389 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005390
5391 // Find the corresponding interface. If we couldn't find the interface, the
5392 // program itself is ill-formed. However, we'll try to be helpful still by
5393 // providing the list of all of the categories we know about.
5394 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005395 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005396 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5397 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005398 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005399
Douglas Gregor218937c2011-02-01 19:23:04 +00005400 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5401 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005402
5403 // Add all of the categories that have have corresponding interface
5404 // declarations in this class and any of its superclasses, except for
5405 // already-implemented categories in the class itself.
5406 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5407 Results.EnterNewScope();
5408 bool IgnoreImplemented = true;
5409 while (Class) {
5410 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5411 Category = Category->getNextClassCategory())
5412 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5413 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005414 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005415
5416 Class = Class->getSuperClass();
5417 IgnoreImplemented = false;
5418 }
5419 Results.ExitScope();
5420
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005421 HandleCodeCompleteResults(this, CodeCompleter,
5422 CodeCompletionContext::CCC_Other,
5423 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005424}
Douglas Gregor322328b2009-11-18 22:32:06 +00005425
John McCalld226f652010-08-21 09:40:31 +00005426void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005427 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005428 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5429 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005430
5431 // Figure out where this @synthesize lives.
5432 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005433 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005434 if (!Container ||
5435 (!isa<ObjCImplementationDecl>(Container) &&
5436 !isa<ObjCCategoryImplDecl>(Container)))
5437 return;
5438
5439 // Ignore any properties that have already been implemented.
5440 for (DeclContext::decl_iterator D = Container->decls_begin(),
5441 DEnd = Container->decls_end();
5442 D != DEnd; ++D)
5443 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5444 Results.Ignore(PropertyImpl->getPropertyDecl());
5445
5446 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005447 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005448 Results.EnterNewScope();
5449 if (ObjCImplementationDecl *ClassImpl
5450 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005451 AddObjCProperties(ClassImpl->getClassInterface(), false,
5452 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005453 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005454 else
5455 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005456 false, /*AllowNullaryMethods=*/false, CurContext,
5457 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005458 Results.ExitScope();
5459
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005460 HandleCodeCompleteResults(this, CodeCompleter,
5461 CodeCompletionContext::CCC_Other,
5462 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005463}
5464
5465void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5466 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005467 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005468 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005469 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5470 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005471
5472 // Figure out where this @synthesize lives.
5473 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005474 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005475 if (!Container ||
5476 (!isa<ObjCImplementationDecl>(Container) &&
5477 !isa<ObjCCategoryImplDecl>(Container)))
5478 return;
5479
5480 // Figure out which interface we're looking into.
5481 ObjCInterfaceDecl *Class = 0;
5482 if (ObjCImplementationDecl *ClassImpl
5483 = dyn_cast<ObjCImplementationDecl>(Container))
5484 Class = ClassImpl->getClassInterface();
5485 else
5486 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5487 ->getClassInterface();
5488
Douglas Gregore8426052011-04-18 14:40:46 +00005489 // Determine the type of the property we're synthesizing.
5490 QualType PropertyType = Context.getObjCIdType();
5491 if (Class) {
5492 if (ObjCPropertyDecl *Property
5493 = Class->FindPropertyDeclaration(PropertyName)) {
5494 PropertyType
5495 = Property->getType().getNonReferenceType().getUnqualifiedType();
5496
5497 // Give preference to ivars
5498 Results.setPreferredType(PropertyType);
5499 }
5500 }
5501
Douglas Gregor322328b2009-11-18 22:32:06 +00005502 // Add all of the instance variables in this class and its superclasses.
5503 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005504 bool SawSimilarlyNamedIvar = false;
5505 std::string NameWithPrefix;
5506 NameWithPrefix += '_';
5507 NameWithPrefix += PropertyName->getName().str();
5508 std::string NameWithSuffix = PropertyName->getName().str();
5509 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005510 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005511 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5512 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005513 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5514
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005515 // Determine whether we've seen an ivar with a name similar to the
5516 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005517 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005518 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005519 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005520 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005521
5522 // Reduce the priority of this result by one, to give it a slight
5523 // advantage over other results whose names don't match so closely.
5524 if (Results.size() &&
5525 Results.data()[Results.size() - 1].Kind
5526 == CodeCompletionResult::RK_Declaration &&
5527 Results.data()[Results.size() - 1].Declaration == Ivar)
5528 Results.data()[Results.size() - 1].Priority--;
5529 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005530 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005531 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005532
5533 if (!SawSimilarlyNamedIvar) {
5534 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005535 // an ivar of the appropriate type.
5536 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005537 typedef CodeCompletionResult Result;
5538 CodeCompletionAllocator &Allocator = Results.getAllocator();
5539 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5540
Douglas Gregore8426052011-04-18 14:40:46 +00005541 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5542 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005543 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5544 Results.AddResult(Result(Builder.TakeString(), Priority,
5545 CXCursor_ObjCIvarDecl));
5546 }
5547
Douglas Gregor322328b2009-11-18 22:32:06 +00005548 Results.ExitScope();
5549
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005550 HandleCodeCompleteResults(this, CodeCompleter,
5551 CodeCompletionContext::CCC_Other,
5552 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005553}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005554
Douglas Gregor408be5a2010-08-25 01:08:01 +00005555// Mapping from selectors to the methods that implement that selector, along
5556// with the "in original class" flag.
5557typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5558 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005559
5560/// \brief Find all of the methods that reside in the given container
5561/// (and its superclasses, protocols, etc.) that meet the given
5562/// criteria. Insert those methods into the map of known methods,
5563/// indexed by selector so they can be easily found.
5564static void FindImplementableMethods(ASTContext &Context,
5565 ObjCContainerDecl *Container,
5566 bool WantInstanceMethods,
5567 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005568 KnownMethodsMap &KnownMethods,
5569 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005570 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5571 // Recurse into protocols.
5572 const ObjCList<ObjCProtocolDecl> &Protocols
5573 = IFace->getReferencedProtocols();
5574 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005575 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005576 I != E; ++I)
5577 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005578 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005579
Douglas Gregorea766182010-10-18 18:21:28 +00005580 // Add methods from any class extensions and categories.
5581 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5582 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005583 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5584 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005585 KnownMethods, false);
5586
5587 // Visit the superclass.
5588 if (IFace->getSuperClass())
5589 FindImplementableMethods(Context, IFace->getSuperClass(),
5590 WantInstanceMethods, ReturnType,
5591 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005592 }
5593
5594 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5595 // Recurse into protocols.
5596 const ObjCList<ObjCProtocolDecl> &Protocols
5597 = Category->getReferencedProtocols();
5598 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005599 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005600 I != E; ++I)
5601 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005602 KnownMethods, InOriginalClass);
5603
5604 // If this category is the original class, jump to the interface.
5605 if (InOriginalClass && Category->getClassInterface())
5606 FindImplementableMethods(Context, Category->getClassInterface(),
5607 WantInstanceMethods, ReturnType, KnownMethods,
5608 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005609 }
5610
5611 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5612 // Recurse into protocols.
5613 const ObjCList<ObjCProtocolDecl> &Protocols
5614 = Protocol->getReferencedProtocols();
5615 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5616 E = Protocols.end();
5617 I != E; ++I)
5618 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005619 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005620 }
5621
5622 // Add methods in this container. This operation occurs last because
5623 // we want the methods from this container to override any methods
5624 // we've previously seen with the same selector.
5625 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5626 MEnd = Container->meth_end();
5627 M != MEnd; ++M) {
5628 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5629 if (!ReturnType.isNull() &&
5630 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5631 continue;
5632
Douglas Gregor408be5a2010-08-25 01:08:01 +00005633 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005634 }
5635 }
5636}
5637
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005638/// \brief Add the parenthesized return or parameter type chunk to a code
5639/// completion string.
5640static void AddObjCPassingTypeChunk(QualType Type,
5641 ASTContext &Context,
5642 CodeCompletionBuilder &Builder) {
5643 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5644 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5645 Builder.getAllocator()));
5646 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5647}
5648
5649/// \brief Determine whether the given class is or inherits from a class by
5650/// the given name.
5651static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
5652 llvm::StringRef Name) {
5653 if (!Class)
5654 return false;
5655
5656 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5657 return true;
5658
5659 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5660}
5661
5662/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5663/// Key-Value Observing (KVO).
5664static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5665 bool IsInstanceMethod,
5666 QualType ReturnType,
5667 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005668 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005669 ResultBuilder &Results) {
5670 IdentifierInfo *PropName = Property->getIdentifier();
5671 if (!PropName || PropName->getLength() == 0)
5672 return;
5673
5674
5675 // Builder that will create each code completion.
5676 typedef CodeCompletionResult Result;
5677 CodeCompletionAllocator &Allocator = Results.getAllocator();
5678 CodeCompletionBuilder Builder(Allocator);
5679
5680 // The selector table.
5681 SelectorTable &Selectors = Context.Selectors;
5682
5683 // The property name, copied into the code completion allocation region
5684 // on demand.
5685 struct KeyHolder {
5686 CodeCompletionAllocator &Allocator;
5687 llvm::StringRef Key;
5688 const char *CopiedKey;
5689
5690 KeyHolder(CodeCompletionAllocator &Allocator, llvm::StringRef Key)
5691 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5692
5693 operator const char *() {
5694 if (CopiedKey)
5695 return CopiedKey;
5696
5697 return CopiedKey = Allocator.CopyString(Key);
5698 }
5699 } Key(Allocator, PropName->getName());
5700
5701 // The uppercased name of the property name.
5702 std::string UpperKey = PropName->getName();
5703 if (!UpperKey.empty())
5704 UpperKey[0] = toupper(UpperKey[0]);
5705
5706 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5707 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5708 Property->getType());
5709 bool ReturnTypeMatchesVoid
5710 = ReturnType.isNull() || ReturnType->isVoidType();
5711
5712 // Add the normal accessor -(type)key.
5713 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005714 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005715 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5716 if (ReturnType.isNull())
5717 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5718
5719 Builder.AddTypedTextChunk(Key);
5720 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5721 CXCursor_ObjCInstanceMethodDecl));
5722 }
5723
5724 // If we have an integral or boolean property (or the user has provided
5725 // an integral or boolean return type), add the accessor -(type)isKey.
5726 if (IsInstanceMethod &&
5727 ((!ReturnType.isNull() &&
5728 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5729 (ReturnType.isNull() &&
5730 (Property->getType()->isIntegerType() ||
5731 Property->getType()->isBooleanType())))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005732 std::string SelectorName = (llvm::Twine("is") + UpperKey).str();
5733 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005734 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005735 if (ReturnType.isNull()) {
5736 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5737 Builder.AddTextChunk("BOOL");
5738 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5739 }
5740
5741 Builder.AddTypedTextChunk(
5742 Allocator.CopyString(SelectorId->getName()));
5743 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5744 CXCursor_ObjCInstanceMethodDecl));
5745 }
5746 }
5747
5748 // Add the normal mutator.
5749 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5750 !Property->getSetterMethodDecl()) {
Douglas Gregor62041592011-02-17 03:19:26 +00005751 std::string SelectorName = (llvm::Twine("set") + UpperKey).str();
5752 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005753 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005754 if (ReturnType.isNull()) {
5755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5756 Builder.AddTextChunk("void");
5757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5758 }
5759
5760 Builder.AddTypedTextChunk(
5761 Allocator.CopyString(SelectorId->getName()));
5762 Builder.AddTypedTextChunk(":");
5763 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5764 Builder.AddTextChunk(Key);
5765 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5766 CXCursor_ObjCInstanceMethodDecl));
5767 }
5768 }
5769
5770 // Indexed and unordered accessors
5771 unsigned IndexedGetterPriority = CCP_CodePattern;
5772 unsigned IndexedSetterPriority = CCP_CodePattern;
5773 unsigned UnorderedGetterPriority = CCP_CodePattern;
5774 unsigned UnorderedSetterPriority = CCP_CodePattern;
5775 if (const ObjCObjectPointerType *ObjCPointer
5776 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5777 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5778 // If this interface type is not provably derived from a known
5779 // collection, penalize the corresponding completions.
5780 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5781 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5782 if (!InheritsFromClassNamed(IFace, "NSArray"))
5783 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5784 }
5785
5786 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5787 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5788 if (!InheritsFromClassNamed(IFace, "NSSet"))
5789 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5790 }
5791 }
5792 } else {
5793 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5794 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5795 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5796 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5797 }
5798
5799 // Add -(NSUInteger)countOf<key>
5800 if (IsInstanceMethod &&
5801 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005802 std::string SelectorName = (llvm::Twine("countOf") + UpperKey).str();
5803 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005804 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005805 if (ReturnType.isNull()) {
5806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5807 Builder.AddTextChunk("NSUInteger");
5808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5809 }
5810
5811 Builder.AddTypedTextChunk(
5812 Allocator.CopyString(SelectorId->getName()));
5813 Results.AddResult(Result(Builder.TakeString(),
5814 std::min(IndexedGetterPriority,
5815 UnorderedGetterPriority),
5816 CXCursor_ObjCInstanceMethodDecl));
5817 }
5818 }
5819
5820 // Indexed getters
5821 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5822 if (IsInstanceMethod &&
5823 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005824 std::string SelectorName
5825 = (llvm::Twine("objectIn") + UpperKey + "AtIndex").str();
5826 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005827 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005828 if (ReturnType.isNull()) {
5829 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5830 Builder.AddTextChunk("id");
5831 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5832 }
5833
5834 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5836 Builder.AddTextChunk("NSUInteger");
5837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5838 Builder.AddTextChunk("index");
5839 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5840 CXCursor_ObjCInstanceMethodDecl));
5841 }
5842 }
5843
5844 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5845 if (IsInstanceMethod &&
5846 (ReturnType.isNull() ||
5847 (ReturnType->isObjCObjectPointerType() &&
5848 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5849 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5850 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005851 std::string SelectorName
5852 = (llvm::Twine(Property->getName()) + "AtIndexes").str();
5853 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005854 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005855 if (ReturnType.isNull()) {
5856 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5857 Builder.AddTextChunk("NSArray *");
5858 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5859 }
5860
5861 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5862 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5863 Builder.AddTextChunk("NSIndexSet *");
5864 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5865 Builder.AddTextChunk("indexes");
5866 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5867 CXCursor_ObjCInstanceMethodDecl));
5868 }
5869 }
5870
5871 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5872 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005873 std::string SelectorName = (llvm::Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005874 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005875 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005876 &Context.Idents.get("range")
5877 };
5878
Douglas Gregore74c25c2011-05-04 23:50:46 +00005879 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005880 if (ReturnType.isNull()) {
5881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5882 Builder.AddTextChunk("void");
5883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5884 }
5885
5886 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5887 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5888 Builder.AddPlaceholderChunk("object-type");
5889 Builder.AddTextChunk(" **");
5890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5891 Builder.AddTextChunk("buffer");
5892 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5893 Builder.AddTypedTextChunk("range:");
5894 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5895 Builder.AddTextChunk("NSRange");
5896 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5897 Builder.AddTextChunk("inRange");
5898 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5899 CXCursor_ObjCInstanceMethodDecl));
5900 }
5901 }
5902
5903 // Mutable indexed accessors
5904
5905 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5906 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005907 std::string SelectorName = (llvm::Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005908 IdentifierInfo *SelectorIds[2] = {
5909 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00005910 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005911 };
5912
Douglas Gregore74c25c2011-05-04 23:50:46 +00005913 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005914 if (ReturnType.isNull()) {
5915 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5916 Builder.AddTextChunk("void");
5917 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5918 }
5919
5920 Builder.AddTypedTextChunk("insertObject:");
5921 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5922 Builder.AddPlaceholderChunk("object-type");
5923 Builder.AddTextChunk(" *");
5924 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5925 Builder.AddTextChunk("object");
5926 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5927 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5928 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5929 Builder.AddPlaceholderChunk("NSUInteger");
5930 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5931 Builder.AddTextChunk("index");
5932 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5933 CXCursor_ObjCInstanceMethodDecl));
5934 }
5935 }
5936
5937 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5938 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005939 std::string SelectorName = (llvm::Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005941 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005942 &Context.Idents.get("atIndexes")
5943 };
5944
Douglas Gregore74c25c2011-05-04 23:50:46 +00005945 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005946 if (ReturnType.isNull()) {
5947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5948 Builder.AddTextChunk("void");
5949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5950 }
5951
5952 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5953 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5954 Builder.AddTextChunk("NSArray *");
5955 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5956 Builder.AddTextChunk("array");
5957 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5958 Builder.AddTypedTextChunk("atIndexes:");
5959 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5960 Builder.AddPlaceholderChunk("NSIndexSet *");
5961 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5962 Builder.AddTextChunk("indexes");
5963 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5964 CXCursor_ObjCInstanceMethodDecl));
5965 }
5966 }
5967
5968 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
5969 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005970 std::string SelectorName
5971 = (llvm::Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
5972 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005973 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005974 if (ReturnType.isNull()) {
5975 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5976 Builder.AddTextChunk("void");
5977 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5978 }
5979
5980 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5981 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5982 Builder.AddTextChunk("NSUInteger");
5983 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5984 Builder.AddTextChunk("index");
5985 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5986 CXCursor_ObjCInstanceMethodDecl));
5987 }
5988 }
5989
5990 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
5991 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005992 std::string SelectorName
5993 = (llvm::Twine("remove") + UpperKey + "AtIndexes").str();
5994 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005995 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005996 if (ReturnType.isNull()) {
5997 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5998 Builder.AddTextChunk("void");
5999 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6000 }
6001
6002 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6003 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6004 Builder.AddTextChunk("NSIndexSet *");
6005 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6006 Builder.AddTextChunk("indexes");
6007 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6008 CXCursor_ObjCInstanceMethodDecl));
6009 }
6010 }
6011
6012 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6013 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006014 std::string SelectorName
6015 = (llvm::Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006016 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006017 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006018 &Context.Idents.get("withObject")
6019 };
6020
Douglas Gregore74c25c2011-05-04 23:50:46 +00006021 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006022 if (ReturnType.isNull()) {
6023 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6024 Builder.AddTextChunk("void");
6025 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6026 }
6027
6028 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddPlaceholderChunk("NSUInteger");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 Builder.AddTextChunk("index");
6033 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6034 Builder.AddTypedTextChunk("withObject:");
6035 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6036 Builder.AddTextChunk("id");
6037 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6038 Builder.AddTextChunk("object");
6039 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6040 CXCursor_ObjCInstanceMethodDecl));
6041 }
6042 }
6043
6044 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6045 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006046 std::string SelectorName1
6047 = (llvm::Twine("replace") + UpperKey + "AtIndexes").str();
6048 std::string SelectorName2 = (llvm::Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006049 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006050 &Context.Idents.get(SelectorName1),
6051 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006052 };
6053
Douglas Gregore74c25c2011-05-04 23:50:46 +00006054 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006055 if (ReturnType.isNull()) {
6056 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6057 Builder.AddTextChunk("void");
6058 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6059 }
6060
6061 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6062 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6063 Builder.AddPlaceholderChunk("NSIndexSet *");
6064 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6065 Builder.AddTextChunk("indexes");
6066 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6067 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6068 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6069 Builder.AddTextChunk("NSArray *");
6070 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6071 Builder.AddTextChunk("array");
6072 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6073 CXCursor_ObjCInstanceMethodDecl));
6074 }
6075 }
6076
6077 // Unordered getters
6078 // - (NSEnumerator *)enumeratorOfKey
6079 if (IsInstanceMethod &&
6080 (ReturnType.isNull() ||
6081 (ReturnType->isObjCObjectPointerType() &&
6082 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6083 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6084 ->getName() == "NSEnumerator"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006085 std::string SelectorName = (llvm::Twine("enumeratorOf") + UpperKey).str();
6086 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006087 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006088 if (ReturnType.isNull()) {
6089 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6090 Builder.AddTextChunk("NSEnumerator *");
6091 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6092 }
6093
6094 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6095 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6096 CXCursor_ObjCInstanceMethodDecl));
6097 }
6098 }
6099
6100 // - (type *)memberOfKey:(type *)object
6101 if (IsInstanceMethod &&
6102 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006103 std::string SelectorName = (llvm::Twine("memberOf") + UpperKey).str();
6104 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006105 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006106 if (ReturnType.isNull()) {
6107 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6108 Builder.AddPlaceholderChunk("object-type");
6109 Builder.AddTextChunk(" *");
6110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6111 }
6112
6113 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6114 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6115 if (ReturnType.isNull()) {
6116 Builder.AddPlaceholderChunk("object-type");
6117 Builder.AddTextChunk(" *");
6118 } else {
6119 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6120 Builder.getAllocator()));
6121 }
6122 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6123 Builder.AddTextChunk("object");
6124 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6125 CXCursor_ObjCInstanceMethodDecl));
6126 }
6127 }
6128
6129 // Mutable unordered accessors
6130 // - (void)addKeyObject:(type *)object
6131 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006132 std::string SelectorName
6133 = (llvm::Twine("add") + UpperKey + llvm::Twine("Object")).str();
6134 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006135 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006136 if (ReturnType.isNull()) {
6137 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6138 Builder.AddTextChunk("void");
6139 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6140 }
6141
6142 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6143 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6144 Builder.AddPlaceholderChunk("object-type");
6145 Builder.AddTextChunk(" *");
6146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6147 Builder.AddTextChunk("object");
6148 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6149 CXCursor_ObjCInstanceMethodDecl));
6150 }
6151 }
6152
6153 // - (void)addKey:(NSSet *)objects
6154 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006155 std::string SelectorName = (llvm::Twine("add") + UpperKey).str();
6156 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006157 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006158 if (ReturnType.isNull()) {
6159 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6160 Builder.AddTextChunk("void");
6161 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6162 }
6163
6164 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6165 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6166 Builder.AddTextChunk("NSSet *");
6167 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6168 Builder.AddTextChunk("objects");
6169 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6170 CXCursor_ObjCInstanceMethodDecl));
6171 }
6172 }
6173
6174 // - (void)removeKeyObject:(type *)object
6175 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006176 std::string SelectorName
6177 = (llvm::Twine("remove") + UpperKey + llvm::Twine("Object")).str();
6178 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006179 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006180 if (ReturnType.isNull()) {
6181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6182 Builder.AddTextChunk("void");
6183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6184 }
6185
6186 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6187 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6188 Builder.AddPlaceholderChunk("object-type");
6189 Builder.AddTextChunk(" *");
6190 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6191 Builder.AddTextChunk("object");
6192 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6193 CXCursor_ObjCInstanceMethodDecl));
6194 }
6195 }
6196
6197 // - (void)removeKey:(NSSet *)objects
6198 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006199 std::string SelectorName = (llvm::Twine("remove") + UpperKey).str();
6200 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006201 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006202 if (ReturnType.isNull()) {
6203 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6204 Builder.AddTextChunk("void");
6205 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6206 }
6207
6208 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6210 Builder.AddTextChunk("NSSet *");
6211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6212 Builder.AddTextChunk("objects");
6213 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6214 CXCursor_ObjCInstanceMethodDecl));
6215 }
6216 }
6217
6218 // - (void)intersectKey:(NSSet *)objects
6219 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006220 std::string SelectorName = (llvm::Twine("intersect") + UpperKey).str();
6221 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006222 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006223 if (ReturnType.isNull()) {
6224 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6225 Builder.AddTextChunk("void");
6226 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6227 }
6228
6229 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6230 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6231 Builder.AddTextChunk("NSSet *");
6232 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6233 Builder.AddTextChunk("objects");
6234 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6235 CXCursor_ObjCInstanceMethodDecl));
6236 }
6237 }
6238
6239 // Key-Value Observing
6240 // + (NSSet *)keyPathsForValuesAffectingKey
6241 if (!IsInstanceMethod &&
6242 (ReturnType.isNull() ||
6243 (ReturnType->isObjCObjectPointerType() &&
6244 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6245 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6246 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006247 std::string SelectorName
6248 = (llvm::Twine("keyPathsForValuesAffecting") + UpperKey).str();
6249 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006250 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006251 if (ReturnType.isNull()) {
6252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6253 Builder.AddTextChunk("NSSet *");
6254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6255 }
6256
6257 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6258 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006259 CXCursor_ObjCClassMethodDecl));
6260 }
6261 }
6262
6263 // + (BOOL)automaticallyNotifiesObserversForKey
6264 if (!IsInstanceMethod &&
6265 (ReturnType.isNull() ||
6266 ReturnType->isIntegerType() ||
6267 ReturnType->isBooleanType())) {
6268 std::string SelectorName
6269 = (llvm::Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
6270 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6271 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6272 if (ReturnType.isNull()) {
6273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6274 Builder.AddTextChunk("BOOL");
6275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6276 }
6277
6278 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6279 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6280 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006281 }
6282 }
6283}
6284
Douglas Gregore8f5a172010-04-07 00:21:17 +00006285void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6286 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006287 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006288 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006289 // Determine the return type of the method we're declaring, if
6290 // provided.
6291 QualType ReturnType = GetTypeFromParser(ReturnTy);
6292
Douglas Gregorea766182010-10-18 18:21:28 +00006293 // Determine where we should start searching for methods.
6294 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006295 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006296 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006297 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6298 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006299 IsInImplementation = true;
6300 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006301 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006302 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006303 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006304 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006305 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006306 }
6307
6308 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006309 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006310 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006311 }
6312
Douglas Gregorea766182010-10-18 18:21:28 +00006313 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006314 HandleCodeCompleteResults(this, CodeCompleter,
6315 CodeCompletionContext::CCC_Other,
6316 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006317 return;
6318 }
6319
6320 // Find all of the methods that we could declare/implement here.
6321 KnownMethodsMap KnownMethods;
6322 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006323 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006324
Douglas Gregore8f5a172010-04-07 00:21:17 +00006325 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006326 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006327 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6328 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006329 Results.EnterNewScope();
6330 PrintingPolicy Policy(Context.PrintingPolicy);
6331 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00006332 Policy.SuppressStrongLifetime = true;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006333 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6334 MEnd = KnownMethods.end();
6335 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006336 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006337 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006338
6339 // If the result type was not already provided, add it to the
6340 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006341 if (ReturnType.isNull())
6342 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006343
6344 Selector Sel = Method->getSelector();
6345
6346 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006347 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006348 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006349
6350 // Add parameters to the pattern.
6351 unsigned I = 0;
6352 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6353 PEnd = Method->param_end();
6354 P != PEnd; (void)++P, ++I) {
6355 // Add the part of the selector name.
6356 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006357 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006358 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6360 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006361 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006362 } else
6363 break;
6364
6365 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006366 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006367
6368 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006369 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006370 }
6371
6372 if (Method->isVariadic()) {
6373 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006374 Builder.AddChunk(CodeCompletionString::CK_Comma);
6375 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006376 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006377
Douglas Gregor447107d2010-05-28 00:57:46 +00006378 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006379 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006380 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6381 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6382 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006383 if (!Method->getResultType()->isVoidType()) {
6384 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006385 Builder.AddTextChunk("return");
6386 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6387 Builder.AddPlaceholderChunk("expression");
6388 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006389 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006390 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006391
Douglas Gregor218937c2011-02-01 19:23:04 +00006392 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6393 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006394 }
6395
Douglas Gregor408be5a2010-08-25 01:08:01 +00006396 unsigned Priority = CCP_CodePattern;
6397 if (!M->second.second)
6398 Priority += CCD_InBaseClass;
6399
Douglas Gregor218937c2011-02-01 19:23:04 +00006400 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006401 Method->isInstanceMethod()
6402 ? CXCursor_ObjCInstanceMethodDecl
6403 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006404 }
6405
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006406 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6407 // the properties in this class and its categories.
6408 if (Context.getLangOptions().ObjC2) {
6409 llvm::SmallVector<ObjCContainerDecl *, 4> Containers;
6410 Containers.push_back(SearchDecl);
6411
Douglas Gregore74c25c2011-05-04 23:50:46 +00006412 VisitedSelectorSet KnownSelectors;
6413 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6414 MEnd = KnownMethods.end();
6415 M != MEnd; ++M)
6416 KnownSelectors.insert(M->first);
6417
6418
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006419 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6420 if (!IFace)
6421 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6422 IFace = Category->getClassInterface();
6423
6424 if (IFace) {
6425 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6426 Category = Category->getNextClassCategory())
6427 Containers.push_back(Category);
6428 }
6429
6430 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6431 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6432 PEnd = Containers[I]->prop_end();
6433 P != PEnd; ++P) {
6434 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006435 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006436 }
6437 }
6438 }
6439
Douglas Gregore8f5a172010-04-07 00:21:17 +00006440 Results.ExitScope();
6441
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006442 HandleCodeCompleteResults(this, CodeCompleter,
6443 CodeCompletionContext::CCC_Other,
6444 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006445}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006446
6447void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6448 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006449 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006450 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006451 IdentifierInfo **SelIdents,
6452 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006453 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006454 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006455 if (ExternalSource) {
6456 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6457 I != N; ++I) {
6458 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006459 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006460 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006461
6462 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006463 }
6464 }
6465
6466 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006467 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006468 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6469 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006470
6471 if (ReturnTy)
6472 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006473
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006474 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006475 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6476 MEnd = MethodPool.end();
6477 M != MEnd; ++M) {
6478 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6479 &M->second.second;
6480 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006481 MethList = MethList->Next) {
6482 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6483 NumSelIdents))
6484 continue;
6485
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006486 if (AtParameterName) {
6487 // Suggest parameter names we've seen before.
6488 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6489 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6490 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006491 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006492 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006493 Param->getIdentifier()->getName()));
6494 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006495 }
6496 }
6497
6498 continue;
6499 }
6500
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006501 Result R(MethList->Method, 0);
6502 R.StartParameter = NumSelIdents;
6503 R.AllParametersAreInformative = false;
6504 R.DeclaringEntity = true;
6505 Results.MaybeAddResult(R, CurContext);
6506 }
6507 }
6508
6509 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006510 HandleCodeCompleteResults(this, CodeCompleter,
6511 CodeCompletionContext::CCC_Other,
6512 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006513}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006514
Douglas Gregorf29c5232010-08-24 22:20:20 +00006515void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006516 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006517 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006518 Results.EnterNewScope();
6519
6520 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006521 CodeCompletionBuilder Builder(Results.getAllocator());
6522 Builder.AddTypedTextChunk("if");
6523 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6524 Builder.AddPlaceholderChunk("condition");
6525 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006526
6527 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006528 Builder.AddTypedTextChunk("ifdef");
6529 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6530 Builder.AddPlaceholderChunk("macro");
6531 Results.AddResult(Builder.TakeString());
6532
Douglas Gregorf44e8542010-08-24 19:08:16 +00006533 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006534 Builder.AddTypedTextChunk("ifndef");
6535 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6536 Builder.AddPlaceholderChunk("macro");
6537 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006538
6539 if (InConditional) {
6540 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006541 Builder.AddTypedTextChunk("elif");
6542 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6543 Builder.AddPlaceholderChunk("condition");
6544 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006545
6546 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006547 Builder.AddTypedTextChunk("else");
6548 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006549
6550 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006551 Builder.AddTypedTextChunk("endif");
6552 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006553 }
6554
6555 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006556 Builder.AddTypedTextChunk("include");
6557 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6558 Builder.AddTextChunk("\"");
6559 Builder.AddPlaceholderChunk("header");
6560 Builder.AddTextChunk("\"");
6561 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006562
6563 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006564 Builder.AddTypedTextChunk("include");
6565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6566 Builder.AddTextChunk("<");
6567 Builder.AddPlaceholderChunk("header");
6568 Builder.AddTextChunk(">");
6569 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006570
6571 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006572 Builder.AddTypedTextChunk("define");
6573 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6574 Builder.AddPlaceholderChunk("macro");
6575 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006576
6577 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006578 Builder.AddTypedTextChunk("define");
6579 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6580 Builder.AddPlaceholderChunk("macro");
6581 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6582 Builder.AddPlaceholderChunk("args");
6583 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6584 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006585
6586 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006587 Builder.AddTypedTextChunk("undef");
6588 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6589 Builder.AddPlaceholderChunk("macro");
6590 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006591
6592 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006593 Builder.AddTypedTextChunk("line");
6594 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6595 Builder.AddPlaceholderChunk("number");
6596 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006597
6598 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006599 Builder.AddTypedTextChunk("line");
6600 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6601 Builder.AddPlaceholderChunk("number");
6602 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6603 Builder.AddTextChunk("\"");
6604 Builder.AddPlaceholderChunk("filename");
6605 Builder.AddTextChunk("\"");
6606 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006607
6608 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006609 Builder.AddTypedTextChunk("error");
6610 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6611 Builder.AddPlaceholderChunk("message");
6612 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006613
6614 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006615 Builder.AddTypedTextChunk("pragma");
6616 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6617 Builder.AddPlaceholderChunk("arguments");
6618 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006619
6620 if (getLangOptions().ObjC1) {
6621 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006622 Builder.AddTypedTextChunk("import");
6623 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6624 Builder.AddTextChunk("\"");
6625 Builder.AddPlaceholderChunk("header");
6626 Builder.AddTextChunk("\"");
6627 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006628
6629 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006630 Builder.AddTypedTextChunk("import");
6631 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6632 Builder.AddTextChunk("<");
6633 Builder.AddPlaceholderChunk("header");
6634 Builder.AddTextChunk(">");
6635 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006636 }
6637
6638 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006639 Builder.AddTypedTextChunk("include_next");
6640 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6641 Builder.AddTextChunk("\"");
6642 Builder.AddPlaceholderChunk("header");
6643 Builder.AddTextChunk("\"");
6644 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006645
6646 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006647 Builder.AddTypedTextChunk("include_next");
6648 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6649 Builder.AddTextChunk("<");
6650 Builder.AddPlaceholderChunk("header");
6651 Builder.AddTextChunk(">");
6652 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006653
6654 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006655 Builder.AddTypedTextChunk("warning");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddPlaceholderChunk("message");
6658 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006659
6660 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6661 // completions for them. And __include_macros is a Clang-internal extension
6662 // that we don't want to encourage anyone to use.
6663
6664 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6665 Results.ExitScope();
6666
Douglas Gregorf44e8542010-08-24 19:08:16 +00006667 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006668 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006669 Results.data(), Results.size());
6670}
6671
6672void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006673 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006674 S->getFnParent()? Sema::PCC_RecoveryInFunction
6675 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006676}
6677
Douglas Gregorf29c5232010-08-24 22:20:20 +00006678void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006679 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006680 IsDefinition? CodeCompletionContext::CCC_MacroName
6681 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006682 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6683 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006684 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006685 Results.EnterNewScope();
6686 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6687 MEnd = PP.macro_end();
6688 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006689 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006690 M->first->getName()));
6691 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006692 }
6693 Results.ExitScope();
6694 } else if (IsDefinition) {
6695 // FIXME: Can we detect when the user just wrote an include guard above?
6696 }
6697
Douglas Gregor52779fb2010-09-23 23:01:17 +00006698 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006699 Results.data(), Results.size());
6700}
6701
Douglas Gregorf29c5232010-08-24 22:20:20 +00006702void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006703 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006704 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006705
6706 if (!CodeCompleter || CodeCompleter->includeMacros())
6707 AddMacroResults(PP, Results);
6708
6709 // defined (<macro>)
6710 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006711 CodeCompletionBuilder Builder(Results.getAllocator());
6712 Builder.AddTypedTextChunk("defined");
6713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6714 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6715 Builder.AddPlaceholderChunk("macro");
6716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6717 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006718 Results.ExitScope();
6719
6720 HandleCodeCompleteResults(this, CodeCompleter,
6721 CodeCompletionContext::CCC_PreprocessorExpression,
6722 Results.data(), Results.size());
6723}
6724
6725void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6726 IdentifierInfo *Macro,
6727 MacroInfo *MacroInfo,
6728 unsigned Argument) {
6729 // FIXME: In the future, we could provide "overload" results, much like we
6730 // do for function calls.
6731
6732 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006733 S->getFnParent()? Sema::PCC_RecoveryInFunction
6734 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006735}
6736
Douglas Gregor55817af2010-08-25 17:04:25 +00006737void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006738 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006739 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006740 0, 0);
6741}
6742
Douglas Gregordae68752011-02-01 22:57:45 +00006743void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
John McCall0a2c5e22010-08-25 06:19:51 +00006744 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006745 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006746 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6747 CodeCompletionDeclConsumer Consumer(Builder,
6748 Context.getTranslationUnitDecl());
6749 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6750 Consumer);
6751 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006752
6753 if (!CodeCompleter || CodeCompleter->includeMacros())
6754 AddMacroResults(PP, Builder);
6755
6756 Results.clear();
6757 Results.insert(Results.end(),
6758 Builder.data(), Builder.data() + Builder.size());
6759}