blob: 66ecae0b792ed91d96a8c9faeeb4293c6fda7d98 [file] [log] [blame]
Douglas Gregor2436e712009-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 McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall5c32be02010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor2436e712009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregord720daf2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCallcc14d1f2010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregor1154e272010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor67c692c2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000033
34using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor2436e712009-09-17 21:32:03 +000036
Douglas Gregor3545ff42009-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 McCall276321a2010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-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 Gregor05e7ca32009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor3545ff42009-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 Gregor05e7ca32009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor3545ff42009-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 Gregor6ae4c522010-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 Gregor7aa6b222010-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 Gregor3545ff42009-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 Gregor9be0ed42010-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 Gregorc2cb2e22010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregor05fcf842010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregor50832e02010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregor05fcf842010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregor50832e02010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor95887f92010-07-08 23:20:03 +0000161
Douglas Gregor0212fd72010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor3545ff42009-09-21 16:56:56 +0000164 public:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor0ac41382010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregor05fcf842010-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 Gregor3545ff42009-09-21 16:56:56 +0000191
Douglas Gregorf64acca2010-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 Gregorac322ec2010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregorf64acca2010-05-25 21:41:55 +0000197 }
198
Douglas Gregor3545ff42009-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 Gregor3545ff42009-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 Gregor7aa6b222010-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 Gregor9be0ed42010-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 Gregorc2cb2e22010-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 Gregor05fcf842010-11-02 20:36:02 +0000233
Douglas Gregor50832e02010-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 Gregor6ae4c522010-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 Gregor74661272010-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 Gregorb278aaf2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000251
Douglas Gregor7c208612010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor6ae4c522010-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 Gregore0717ab2010-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 Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000273 ///
Douglas Gregorc580c522010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor2af2f672009-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 Gregor3545ff42009-09-21 16:56:56 +0000278
Douglas Gregorc580c522010-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 Gregor09bbc652010-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 Gregorc580c522010-01-14 01:09:38 +0000292
Douglas Gregor78a21012010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor3545ff42009-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 Gregorbaf69612009-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 Gregor3545ff42009-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 Gregor9d64c5e2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor70febae2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregor85b50632010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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 Gregore412a5a2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor2b8162b2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregora817a192010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor68762e72010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregor05e7ca32009-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 Lattner9795b392010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner9795b392010-09-04 18:12:20 +0000377 }*/
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregor05e7ca32009-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 Gregor2af2f672009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregor68762e72010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor2af2f672009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregor68762e72010-08-23 21:17:50 +0000459 }
Douglas Gregor2af2f672009-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 Gregor9eb77012009-11-07 00:00:49 +0000464 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregor7c208612010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregor58acf322009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCallbbbbe4e2010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregor7c208612010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000488
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-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 Gregor3545ff42009-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 Gregor7c208612010-01-14 00:20:49 +0000497 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000498
Douglas Gregor58acf322009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor9f1570d2010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor9f1570d2010-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 Gregor7c208612010-01-14 00:20:49 +0000510 return false;
Douglas Gregor58acf322009-10-09 22:16:47 +0000511 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000512 }
Douglas Gregor0212fd72010-09-21 16:06:22 +0000513
Douglas Gregor2927c0c2010-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 Gregor59cab552010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregor59cab552010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor3545ff42009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor6ae4c522010-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 Gregor7c208612010-01-14 00:20:49 +0000541 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000542 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregore0717ab2010-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 Redl50c68252010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-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 Redl50c68252010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-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 Gregor95887f92010-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 Gregor6e240332010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-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 Gregor95887f92010-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 Gregor6e240332010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor95887f92010-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 Gregor603d81b2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor95887f92010-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 Gregoraf670a82011-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 Gregor95887f92010-07-08 23:20:03 +0000703}
704
Douglas Gregor50832e02010-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 Gregor5fb901d2010-09-20 23:11:55 +0000712
Douglas Gregor50832e02010-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 Gregor95887f92010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000729}
730
Douglas Gregor0212fd72010-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 Gregor7c208612010-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 Gregor6ae4c522010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor0212fd72010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor3545ff42009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-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 Gregor3545ff42009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor3545ff42009-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 Gregor05e7ca32009-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 Gregor3545ff42009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor3545ff42009-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 Gregor05e7ca32009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000840 return;
Douglas Gregor3545ff42009-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 Gregorc2cb2e22010-08-27 15:29:55 +0000849
Douglas Gregore412a5a2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000857
Douglas Gregor5bf52692009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-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 Gregore412a5a2009-09-23 22:26:46 +0000870
Douglas Gregor3545ff42009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000878}
879
Douglas Gregorc580c522010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-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 Gregorc580c522010-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 Gregor6ae4c522010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor0212fd72010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregorc580c522010-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 Gregora2db7932010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregorc580c522010-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 Gregor6ae4c522010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregora2db7932010-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 Gregor50832e02010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000938
Douglas Gregor9be0ed42010-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 Gregorc580c522010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +0000958}
959
Douglas Gregor78a21012010-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 Gregor3545ff42009-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 Gregor05e7ca32009-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 Gregor3545ff42009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor9d64c5e2009-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 Gregor70febae2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor05fcf842010-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 Gregor9d64c5e2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-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 Gregor9858ed52010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor05fcf842010-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 Gregor70febae2010-05-28 00:49:12 +00001019 return ND->getIdentifierNamespace() & IDNS;
1020}
1021
Douglas Gregor85b50632010-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 Gregor70febae2010-05-28 00:49:12 +00001033/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001034/// ordinary name lookup.
1035bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001036 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1037
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001038 unsigned IDNS = Decl::IDNS_Ordinary;
1039 if (SemaRef.getLangOptions().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001040 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001041
1042 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001043 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1044 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001045}
1046
Douglas Gregor3545ff42009-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 Bagnara6150c882010-05-11 21:36:43 +00001069 return RD->getTagKind() == TTK_Class ||
1070 RD->getTagKind() == TTK_Struct;
Douglas Gregor3545ff42009-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 Bagnara6150c882010-05-11 21:36:43 +00001082 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-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 Gregor99fe2ad2009-12-11 17:31:05 +00001098/// \brief Determines whether the given declaration is a type.
Douglas Gregor3545ff42009-09-21 16:56:56 +00001099bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregor99fa2642010-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 Gregor3545ff42009-09-21 16:56:56 +00001104}
1105
Douglas Gregor99fe2ad2009-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 Gregore412a5a2009-09-23 22:26:46 +00001109bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001110 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1111 ND = Using->getTargetDecl();
1112
Douglas Gregor70788392009-12-11 18:14:22 +00001113 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1114 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001115}
1116
Douglas Gregora817a192010-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 Gregor68762e72010-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 Gregora817a192010-05-27 23:06:34 +00001173
Douglas Gregor0ac41382010-09-23 23:01:17 +00001174bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1175 return false;
1176}
1177
Douglas Gregor2b8162b2010-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 Gregorc580c522010-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 Gregor09bbc652010-01-14 15:47:35 +00001195 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1196 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor3545ff42009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-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 Gregor504a6ae2010-01-10 23:08:15 +00001219
Douglas Gregor3545ff42009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregora2db7932010-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 Gregor3545ff42009-09-21 16:56:56 +00001226 }
1227
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001235
Douglas Gregorf4c33342010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregorb278aaf2011-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 Gregorf64acca2010-05-25 21:41:55 +00001243
Douglas Gregor3545ff42009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregora2db7932010-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 Gregorf4c33342010-05-28 00:22:41 +00001248
Douglas Gregorb278aaf2011-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 Gregor3545ff42009-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 Gregor78a21012010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001263
Douglas Gregorb278aaf2011-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 Gregorf4c33342010-05-28 00:22:41 +00001268
Douglas Gregorb278aaf2011-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 Gregor3545ff42009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallfaf5fb42010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-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 Gregor78a21012010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001286}
1287
John McCallfaf5fb42010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-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 Gregor504a6ae2010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallfaf5fb42010-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 Gregor504a6ae2010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001309 break;
1310
John McCallfaf5fb42010-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 Gregor5e35d592010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorf98e6a22010-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 Gregor48d46252010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001336
Douglas Gregorf4c33342010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregorb278aaf2011-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 Gregorf4c33342010-05-28 00:22:41 +00001345}
1346
John McCallfaf5fb42010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallfaf5fb42010-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 Gregor5e35d592010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001360 return true;
1361
John McCallfaf5fb42010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001368 return false;
1369
John McCallfaf5fb42010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001377/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001378static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001379 Scope *S,
1380 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001381 ResultBuilder &Results) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001382 CodeCompletionBuilder Builder(Results.getAllocator());
1383
John McCall276321a2010-08-25 06:19:51 +00001384 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001385 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001386 case Sema::PCC_Namespace:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001387 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001388 if (Results.includeCodePatterns()) {
1389 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-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 Gregorf4c33342010-05-28 00:22:41 +00001398 }
1399
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001400 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001407
1408 // Using directives
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001415
1416 // asm(string-literal)
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001422
Douglas Gregorf4c33342010-05-28 00:22:41 +00001423 if (Results.includeCodePatterns()) {
1424 // Explicit template instantiation
Douglas Gregorb278aaf2011-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 Gregorf4c33342010-05-28 00:22:41 +00001429 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001430 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001431
1432 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001433 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001434
Douglas Gregorf4c33342010-05-28 00:22:41 +00001435 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001436 // Fall through
1437
John McCallfaf5fb42010-08-26 23:41:50 +00001438 case Sema::PCC_Class:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001439 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001440 // Using declaration
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001447
Douglas Gregorf4c33342010-05-28 00:22:41 +00001448 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001449 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001458 }
1459
John McCallfaf5fb42010-08-26 23:41:50 +00001460 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001461 AddTypedefResult(Results);
1462
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001463 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001464 Builder.AddTypedTextChunk("public");
1465 Builder.AddChunk(CodeCompletionString::CK_Colon);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001467
1468 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("protected");
1470 Builder.AddChunk(CodeCompletionString::CK_Colon);
1471 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001472
1473 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("private");
1475 Builder.AddChunk(CodeCompletionString::CK_Colon);
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001477 }
1478 }
1479 // Fall through
1480
John McCallfaf5fb42010-08-26 23:41:50 +00001481 case Sema::PCC_Template:
1482 case Sema::PCC_MemberTemplate:
Douglas Gregorf64acca2010-05-25 21:41:55 +00001483 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001484 // template < parameters >
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001490 }
1491
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001494 break;
1495
John McCallfaf5fb42010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCInterface:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001497 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1498 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1499 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001500 break;
1501
John McCallfaf5fb42010-08-26 23:41:50 +00001502 case Sema::PCC_ObjCImplementation:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001503 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1504 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1505 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001506 break;
1507
John McCallfaf5fb42010-08-26 23:41:50 +00001508 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001509 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001510 break;
1511
John McCallfaf5fb42010-08-26 23:41:50 +00001512 case Sema::PCC_RecoveryInFunction:
1513 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001514 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001515
Douglas Gregorc05f6572011-04-12 02:47:21 +00001516 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1517 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001532 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001533 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001534 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001535
Douglas Gregorf64acca2010-05-25 21:41:55 +00001536 if (Results.includeCodePatterns()) {
1537 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("if");
1539 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001540 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001541 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001542 else
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001550
Douglas Gregorf64acca2010-05-25 21:41:55 +00001551 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001552 Builder.AddTypedTextChunk("switch");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001554 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001556 else
Douglas Gregorb278aaf2011-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 Gregorf64acca2010-05-25 21:41:55 +00001563 }
1564
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001565 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001566 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001567 // case expression:
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001573
1574 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("default");
1576 Builder.AddChunk(CodeCompletionString::CK_Colon);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001578 }
1579
Douglas Gregorf64acca2010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("while");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001586 else
Douglas Gregorb278aaf2011-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 Gregorf64acca2010-05-25 21:41:55 +00001594
1595 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001606
Douglas Gregorf64acca2010-05-25 21:41:55 +00001607 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001608 Builder.AddTypedTextChunk("for");
1609 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001610 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001611 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001612 else
Douglas Gregorb278aaf2011-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 Gregorf64acca2010-05-25 21:41:55 +00001625 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626
1627 if (S->getContinueParent()) {
1628 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("continue");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001631 }
1632
1633 if (S->getBreakParent()) {
1634 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("break");
1636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-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 Gregor9a28e842010-03-01 23:15:13 +00001647 else if (SemaRef.getCurBlock() &&
1648 !SemaRef.getCurBlock()->ReturnType.isNull())
1649 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001650 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001651 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001654 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001656
Douglas Gregorf4c33342010-05-28 00:22:41 +00001657 // goto identifier ;
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001662
Douglas Gregorf4c33342010-05-28 00:22:41 +00001663 // Using directives
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001670 }
1671
1672 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001673 case Sema::PCC_ForInit:
1674 case Sema::PCC_Condition:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001675 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001676 // Fall through: conditions and statements can have expressions.
1677
Douglas Gregor5e35d592010-09-14 23:59:36 +00001678 case Sema::PCC_ParenthesizedExpression:
John McCall31168b02011-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 McCallfaf5fb42010-08-26 23:41:50 +00001707 case Sema::PCC_Expression: {
Douglas Gregor504a6ae2010-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 Gregor78a21012010-01-14 16:01:26 +00001712 Results.AddResult(Result("this"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001713
1714 // true, false
Douglas Gregor78a21012010-01-14 16:01:26 +00001715 Results.AddResult(Result("true"));
1716 Results.AddResult(Result("false"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001717
Douglas Gregorc05f6572011-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 Gregorf4c33342010-05-28 00:22:41 +00001729
1730 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001739
Douglas Gregorf4c33342010-05-28 00:22:41 +00001740 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001749
Douglas Gregorf4c33342010-05-28 00:22:41 +00001750 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001759
Douglas Gregorc05f6572011-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 Gregorf4c33342010-05-28 00:22:41 +00001769 // new T ( ... )
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001777
Douglas Gregorf4c33342010-05-28 00:22:41 +00001778 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001789
Douglas Gregorf4c33342010-05-28 00:22:41 +00001790 // delete expression
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001795
Douglas Gregorf4c33342010-05-28 00:22:41 +00001796 // delete [] expression
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001804
Douglas Gregorc05f6572011-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 Gregora2db7932010-05-26 22:00:08 +00001812
1813 // FIXME: Rethrow?
Douglas Gregor504a6ae2010-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 Kremenek305a0a72010-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 Gregorf98e6a22010-01-13 23:51:12 +00001825 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001826 }
1827
Douglas Gregorf4c33342010-05-28 00:22:41 +00001828 // sizeof expression
Douglas Gregorb278aaf2011-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 Gregor504a6ae2010-01-10 23:08:15 +00001834 break;
1835 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00001836
John McCallfaf5fb42010-08-26 23:41:50 +00001837 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00001838 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00001839 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001840 }
1841
Douglas Gregor70febae2010-05-28 00:49:12 +00001842 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1843 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001844
John McCallfaf5fb42010-08-26 23:41:50 +00001845 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00001846 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001847}
1848
Douglas Gregor304f9b02011-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 Kramer8aef5962011-03-26 12:38:21 +00001854static const char *GetCompletionTypeString(QualType T,
1855 ASTContext &Context,
1856 CodeCompletionAllocator &Allocator) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00001857 PrintingPolicy Policy(Context.PrintingPolicy);
1858 Policy.AnonymousTagLocations = false;
John McCall31168b02011-06-15 23:02:42 +00001859 Policy.SuppressStrongLifetime = true;
1860
Douglas Gregor304f9b02011-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 Smithdda56e42011-04-15 14:24:37 +00001869 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregor304f9b02011-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 Gregorbcbf46c2011-02-01 22:57:45 +00001882 return Allocator.CopyString(Result);
Douglas Gregor304f9b02011-02-01 21:15:40 +00001883}
1884
Douglas Gregorb3fa9192009-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 Gregorb278aaf2011-02-01 19:23:04 +00001889 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001890 if (!ND)
1891 return;
Douglas Gregor0212fd72010-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 Gregorb3fa9192009-12-18 18:53:37 +00001898 // Determine the type of the declaration (if it has a type).
Douglas Gregor0212fd72010-09-21 16:06:22 +00001899 QualType T;
Douglas Gregorb3fa9192009-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 McCall31168b02011-06-15 23:02:42 +00001910 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001911 T = Value->getType();
John McCall31168b02011-06-15 23:02:42 +00001912 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001913 T = Property->getType();
1914
1915 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1916 return;
1917
Douglas Gregor304f9b02011-02-01 21:15:40 +00001918 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1919 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001920}
1921
Douglas Gregordbb71db2010-08-23 23:51:41 +00001922static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001923 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-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 Gregorb278aaf2011-02-01 19:23:04 +00001928 Result.AddTextChunk(", nil");
Douglas Gregordbb71db2010-08-23 23:51:41 +00001929 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001930 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00001931 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001932 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00001933 }
1934}
1935
Douglas Gregore90dd002010-08-24 16:15:59 +00001936static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor981a0c42010-08-29 19:47:46 +00001937 ParmVarDecl *Param,
1938 bool SuppressName = false) {
John McCall31168b02011-06-15 23:02:42 +00001939 PrintingPolicy Policy(Context.PrintingPolicy);
1940 Policy.AnonymousTagLocations = false;
1941 Policy.SuppressStrongLifetime = true;
1942
Douglas Gregore90dd002010-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 Gregor981a0c42010-08-29 19:47:46 +00001950 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00001951 Result = Param->getIdentifier()->getName();
1952
John McCall31168b02011-06-15 23:02:42 +00001953 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00001954
1955 if (ObjCMethodParam) {
1956 Result = "(" + Result;
1957 Result += ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00001958 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-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 Gregor24bbc462011-02-15 22:37:09 +00001966 FunctionTypeLoc *Block = 0;
1967 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregore90dd002010-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 Smithdda56e42011-04-15 14:24:37 +00001975 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregore90dd002010-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 Bagnara6d810632010-12-14 22:11:44 +00001991 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor24bbc462011-02-15 22:37:09 +00001992 Block = dyn_cast<FunctionTypeLoc>(&TL);
1993 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregore90dd002010-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 McCall31168b02011-06-15 23:02:42 +00002003 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-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 Gregor67da50e2010-09-08 22:47:51 +00002017 std::string Result;
2018 QualType ResultType = Block->getTypePtr()->getResultType();
2019 if (!ResultType->isVoidType())
John McCall31168b02011-06-15 23:02:42 +00002020 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor67da50e2010-09-08 22:47:51 +00002021
2022 Result = '^' + Result;
Douglas Gregor24bbc462011-02-15 22:37:09 +00002023 if (!BlockProto || Block->getNumArgs() == 0) {
2024 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor67da50e2010-09-08 22:47:51 +00002025 Result += "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002026 else
2027 Result += "(void)";
Douglas Gregor67da50e2010-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 Gregor24bbc462011-02-15 22:37:09 +00002035 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor67da50e2010-09-08 22:47:51 +00002036 Result += ", ...";
2037 }
2038 Result += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002039 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002040
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002041 if (Param->getIdentifier())
2042 Result += Param->getIdentifier()->getName();
2043
Douglas Gregore90dd002010-08-24 16:15:59 +00002044 return Result;
2045}
2046
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002050 CodeCompletionBuilder &Result,
2051 unsigned Start = 0,
2052 bool InOptional = false) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002053 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002054 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002055
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002056 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002057 ParmVarDecl *Param = Function->getParamDecl(P);
2058
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002059 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-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 Gregor3545ff42009-09-21 16:56:56 +00002068 }
2069
Douglas Gregorb278aaf2011-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 Gregor3545ff42009-09-21 16:56:56 +00002076
2077 // Format the placeholder string.
Douglas Gregore90dd002010-08-24 16:15:59 +00002078 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2079
Douglas Gregor400f5972010-08-31 05:13:43 +00002080 if (Function->isVariadic() && P == N - 1)
2081 PlaceholderStr += ", ...";
2082
Douglas Gregor3545ff42009-09-21 16:56:56 +00002083 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002084 Result.AddPlaceholderChunk(
2085 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002086 }
Douglas Gregorba449032009-09-22 21:42:17 +00002087
2088 if (const FunctionProtoType *Proto
2089 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002090 if (Proto->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002091 if (Proto->getNumArgs() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002092 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002093
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002094 MaybeAddSentinel(Context, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002095 }
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002101 CodeCompletionBuilder &Result,
2102 unsigned MaxParameters = 0,
2103 unsigned Start = 0,
2104 bool InDefaultArg = false) {
John McCall31168b02011-06-15 23:02:42 +00002105 PrintingPolicy Policy(Context.PrintingPolicy);
2106 Policy.AnonymousTagLocations = false;
2107
Douglas Gregor9eb77012009-11-07 00:00:49 +00002108 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002115 for (TemplateParameterList::iterator P = Params->begin() + Start;
2116 P != PEnd; ++P) {
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002132 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002133 if (NTTP->getIdentifier())
2134 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002135 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002152 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-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 Gregor3545ff42009-09-21 16:56:56 +00002162 }
2163
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002164 InDefaultArg = false;
2165
Douglas Gregor3545ff42009-09-21 16:56:56 +00002166 if (FirstParameter)
2167 FirstParameter = false;
2168 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002169 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002170
2171 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002172 Result.AddPlaceholderChunk(
2173 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002174 }
2175}
2176
Douglas Gregorf2510672009-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 Gregor0f622362009-12-11 18:44:16 +00002179static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002180AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002181 NestedNameSpecifier *Qualifier,
2182 bool QualifierIsInformative,
2183 ASTContext &Context) {
Douglas Gregorf2510672009-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 Gregor5bf52692009-09-22 23:15:58 +00002192 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002193 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002194 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002195 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002196}
2197
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002198static void
2199AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2200 FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002201 const FunctionProtoType *Proto
2202 = Function->getType()->getAs<FunctionProtoType>();
2203 if (!Proto || !Proto->getTypeQuals())
2204 return;
2205
Douglas Gregor304f9b02011-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 Gregor0f622362009-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 Gregorbcbf46c2011-02-01 22:57:45 +00002232 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002233}
2234
Douglas Gregor0212fd72010-09-21 16:06:22 +00002235/// \brief Add the name of the given declaration
2236static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002237 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-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 Gregor304f9b02011-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 Gregor0212fd72010-09-21 16:06:22 +00002270 case DeclarationName::Identifier:
2271 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002272 case DeclarationName::CXXDestructorName:
2273 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002274 Result.AddTypedTextChunk(
2275 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-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 Gregorbcbf46c2011-02-01 22:57:45 +00002293 Result.AddTypedTextChunk(
2294 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002295 break;
2296 }
2297
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002298 Result.AddTypedTextChunk(
2299 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002300 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002301 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002302 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002303 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002304 }
2305 break;
2306 }
2307 }
2308}
2309
Douglas Gregor3545ff42009-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 McCall276321a2010-08-25 06:19:51 +00002317CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002318 CodeCompletionAllocator &Allocator) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002319 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002320 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002321
John McCall31168b02011-06-15 23:02:42 +00002322 PrintingPolicy Policy(S.Context.PrintingPolicy);
2323 Policy.AnonymousTagLocations = false;
2324 Policy.SuppressStrongLifetime = true;
2325
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002326 if (Kind == RK_Pattern) {
2327 Pattern->Priority = Priority;
2328 Pattern->Availability = Availability;
2329 return Pattern;
2330 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002331
Douglas Gregorf09935f2009-12-01 05:55:20 +00002332 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002333 Result.AddTypedTextChunk(Keyword);
2334 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002335 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002336
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002337 if (Kind == RK_Macro) {
2338 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002339 assert(MI && "Not a macro?");
2340
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002341 Result.AddTypedTextChunk(
2342 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002343
2344 if (!MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002345 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002346
2347 // Format a function-like macro with placeholders for the arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002348 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-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 Gregorb278aaf2011-02-01 19:23:04 +00002352 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002353
2354 if (!MI->isVariadic() || A != AEnd - 1) {
2355 // Non-variadic argument.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002356 Result.AddPlaceholderChunk(
2357 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregorf329c7c2009-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 Gregorb278aaf2011-02-01 19:23:04 +00002365 Result.AddPlaceholderChunk("...");
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002366 else {
2367 std::string Arg = (*A)->getName();
2368 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002369 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002370 }
2371 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002372 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2373 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002374 }
2375
Douglas Gregorf64acca2010-05-25 21:41:55 +00002376 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +00002377 NamedDecl *ND = Declaration;
2378
Douglas Gregor9eb77012009-11-07 00:00:49 +00002379 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002382 Result.AddTextChunk("::");
2383 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002384 }
2385
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002386 AddResultTypeChunk(S.Context, ND, Result);
2387
Douglas Gregor3545ff42009-09-21 16:56:56 +00002388 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002389 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2390 S.Context);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002391 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002392 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002393 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002394 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00002395 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002396 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002397 }
2398
2399 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002400 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2401 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002402 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0212fd72010-09-21 16:06:22 +00002403 AddTypedNameChunk(S.Context, Function, Result);
2404
Douglas Gregor3545ff42009-09-21 16:56:56 +00002405 // Figure out which template parameters are deduced (or have default
2406 // arguments).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002407 SmallVector<bool, 16> Deduced;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002408 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 Gregorb278aaf2011-02-01 19:23:04 +00002418 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +00002427 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-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 Gregorb278aaf2011-02-01 19:23:04 +00002439 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002440 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2441 LastDeducibleArgument);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002442 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002443 }
2444
2445 // Add the function parameters
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002446 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002447 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002448 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00002449 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002450 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002451 }
2452
2453 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002454 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2455 S.Context);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002456 Result.AddTypedTextChunk(
2457 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002458 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002459 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002460 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2461 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002462 }
2463
Douglas Gregord3c5d792009-11-17 16:44:22 +00002464 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002465 Selector Sel = Method->getSelector();
2466 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002467 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002468 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002469 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002470 }
2471
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002472 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002473 SelName += ':';
2474 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002475 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002476 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002477 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-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 Gregorb278aaf2011-02-01 19:23:04 +00002482 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002483 }
Douglas Gregord3c5d792009-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 Gregor1b605f72009-11-19 01:08:35 +00002489 std::string Keyword;
2490 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002491 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002492 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002493 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002494 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002495 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002496 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002497 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002498 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002499 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002500
2501 // If we're before the starting parameter, skip the placeholder.
2502 if (Idx < StartParameter)
2503 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002504
2505 std::string Arg;
Douglas Gregore90dd002010-08-24 16:15:59 +00002506
2507 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor981a0c42010-08-29 19:47:46 +00002508 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregore90dd002010-08-24 16:15:59 +00002509 else {
John McCall31168b02011-06-15 23:02:42 +00002510 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002511 Arg = "(" + Arg + ")";
2512 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002513 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002514 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002515 }
2516
Douglas Gregor400f5972010-08-31 05:13:43 +00002517 if (Method->isVariadic() && (P + 1) == PEnd)
2518 Arg += ", ...";
2519
Douglas Gregor95887f92010-07-08 23:20:03 +00002520 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002521 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002522 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002523 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002524 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002525 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002526 }
2527
Douglas Gregor04c5f972009-12-23 00:21:46 +00002528 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002529 if (Method->param_size() == 0) {
2530 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002531 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002532 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002533 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002534 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002535 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002536 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002537
2538 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002539 }
2540
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002541 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002542 }
2543
Douglas Gregorf09935f2009-12-01 05:55:20 +00002544 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002545 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2546 S.Context);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002547
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002548 Result.AddTypedTextChunk(
2549 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002550 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002551}
2552
Douglas Gregorf0f51982009-09-23 00:34:09 +00002553CodeCompletionString *
2554CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2555 unsigned CurrentArg,
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002556 Sema &S,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002557 CodeCompletionAllocator &Allocator) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002558 typedef CodeCompletionString::Chunk Chunk;
John McCall31168b02011-06-15 23:02:42 +00002559 PrintingPolicy Policy(S.Context.PrintingPolicy);
2560 Policy.AnonymousTagLocations = false;
2561 Policy.SuppressStrongLifetime = true;
2562
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002563 // FIXME: Set priority, availability appropriately.
2564 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002565 FunctionDecl *FDecl = getFunction();
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002566 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregorf0f51982009-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 Gregor304f9b02011-02-01 21:15:40 +00002573 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2574 S.Context,
2575 Result.getAllocator()));
Douglas Gregorb278aaf2011-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 Gregorf0f51982009-09-23 00:34:09 +00002580 }
2581
2582 if (FDecl)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002583 Result.AddTextChunk(
2584 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002585 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002586 Result.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002587 Result.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00002588 Proto->getResultType().getAsString(Policy)));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002589
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002590 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-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 Gregorb278aaf2011-02-01 19:23:04 +00002594 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-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 McCall31168b02011-06-15 23:02:42 +00002606 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002607
2608 if (I == CurrentArg)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002609 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002610 Result.getAllocator().CopyString(ArgString)));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002611 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002612 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002613 }
2614
2615 if (Proto && Proto->isVariadic()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002616 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002617 if (CurrentArg < NumParams)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002618 Result.AddTextChunk("...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002619 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002620 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002621 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002622 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002623
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002624 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002625}
2626
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002627unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002628 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002629 bool PreferredTypeIsPointer) {
2630 unsigned Priority = CCP_Macro;
2631
Douglas Gregor9dcf58a2010-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 Gregor6e240332010-08-16 16:18:59 +00002635 Priority = CCP_Constant;
2636 if (PreferredTypeIsPointer)
2637 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-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 Gregor6e240332010-08-16 16:18:59 +00002647
2648 return Priority;
2649}
2650
Douglas Gregor09c0eb12010-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 Smithdda56e42011-04-15 14:24:37 +00002683 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-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 Gregor4cd65962011-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 Gregor09c0eb12010-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 Gregor55b037b2010-07-08 20:55:51 +00002725static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2726 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00002727 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00002728
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002729 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002730
Douglas Gregor9eb77012009-11-07 00:00:49 +00002731 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2732 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00002733 M != MEnd; ++M) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002734 Results.AddResult(Result(M->first,
2735 getMacroUsagePriority(M->first->getName(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002736 PP.getLangOptions(),
Douglas Gregor6e240332010-08-16 16:18:59 +00002737 TargetTypeIsPointer)));
Douglas Gregor55b037b2010-07-08 20:55:51 +00002738 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002739
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002740 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002741
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002742}
2743
Douglas Gregorce0e8562010-08-23 21:54:33 +00002744static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2745 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00002746 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00002747
2748 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002749
Douglas Gregorce0e8562010-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 Dunbar242ea9a2009-11-13 08:58:20 +00002757static void HandleCodeCompleteResults(Sema *S,
2758 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002759 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002760 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002761 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002762 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002763 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002764}
2765
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002766static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2767 Sema::ParserCompletionContext PCC) {
2768 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00002769 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002770 return CodeCompletionContext::CCC_TopLevel;
2771
John McCallfaf5fb42010-08-26 23:41:50 +00002772 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002773 return CodeCompletionContext::CCC_ClassStructUnion;
2774
John McCallfaf5fb42010-08-26 23:41:50 +00002775 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002776 return CodeCompletionContext::CCC_ObjCInterface;
2777
John McCallfaf5fb42010-08-26 23:41:50 +00002778 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002779 return CodeCompletionContext::CCC_ObjCImplementation;
2780
John McCallfaf5fb42010-08-26 23:41:50 +00002781 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002782 return CodeCompletionContext::CCC_ObjCIvarList;
2783
John McCallfaf5fb42010-08-26 23:41:50 +00002784 case Sema::PCC_Template:
2785 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-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 McCallfaf5fb42010-08-26 23:41:50 +00002793 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002794 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00002795
John McCallfaf5fb42010-08-26 23:41:50 +00002796 case Sema::PCC_ForInit:
Douglas Gregorc769d6e2010-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 McCallfaf5fb42010-08-26 23:41:50 +00002804 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002805 return CodeCompletionContext::CCC_Expression;
2806
John McCallfaf5fb42010-08-26 23:41:50 +00002807 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002808 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00002809
John McCallfaf5fb42010-08-26 23:41:50 +00002810 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00002811 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00002812
2813 case Sema::PCC_ParenthesizedExpression:
2814 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00002815
2816 case Sema::PCC_LocalDeclarationSpecifiers:
2817 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002818 }
2819
2820 return CodeCompletionContext::CCC_Other;
2821}
2822
Douglas Gregorac322ec2010-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 Gregorb278aaf2011-02-01 19:23:04 +00002856 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorac322ec2010-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 Gregorbcbf46c2011-02-01 22:57:45 +00002870 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00002871 }
2872 } else if (!InContext->Equals(Overridden->getDeclContext()))
2873 continue;
2874
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002875 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002876 Overridden->getNameAsString()));
2877 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-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 Gregorb278aaf2011-02-01 19:23:04 +00002885 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00002886
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002887 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002888 (*P)->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00002889 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2891 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00002892 CCP_SuperCompletion,
2893 CXCursor_CXXMethod));
2894 Results.Ignore(Overridden);
2895 }
2896}
2897
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002898void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002899 ParserCompletionContext CompletionContext) {
John McCall276321a2010-08-25 06:19:51 +00002900 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00002902 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00002903 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00002904
Douglas Gregor504a6ae2010-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 Gregor00c37ef2010-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 Gregorf02e5f32010-08-24 01:11:00 +00002916 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002917 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002918 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2919 break;
2920
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002921 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002922 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00002923 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002924 case PCC_ForInit:
2925 case PCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00002926 if (WantTypesInContext(CompletionContext, getLangOptions()))
2927 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2928 else
2929 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00002930
2931 if (getLangOptions().CPlusPlus)
2932 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002933 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00002934
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002935 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00002936 // Unfiltered
2937 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002938 }
2939
Douglas Gregor9be0ed42010-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 Gregorc580c522010-01-14 01:09:38 +00002947 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002948 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2949 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00002950
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002951 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00002952 Results.ExitScope();
2953
Douglas Gregorce0e8562010-08-23 21:54:33 +00002954 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00002955 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-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 Gregor80039242011-02-15 20:33:25 +00002973 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00002974 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00002975 }
2976
Douglas Gregor9eb77012009-11-07 00:00:49 +00002977 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002978 AddMacroResults(PP, Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00002979
Douglas Gregor50832e02010-09-20 22:39:41 +00002980 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002981 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00002982}
2983
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00002984static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2985 ParsedType Receiver,
2986 IdentifierInfo **SelIdents,
2987 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00002988 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-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 McCall276321a2010-08-25 06:19:51 +00002995 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00002997 AllowNestedNameSpecifiers
2998 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2999 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-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 Gregor0ac41382010-09-23 23:01:17 +00003016 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003017 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3018 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3019 CodeCompleter->includeGlobals());
Douglas Gregor0ac41382010-09-23 23:01:17 +00003020 Results.setFilter(0);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003021 }
3022 }
3023 Results.ExitScope();
3024
Douglas Gregorbfcea8b2010-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 Gregorf86e4da2010-09-20 23:34:21 +00003043 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003044 }
3045
Douglas Gregor56ccce02010-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 Gregor0ac41382010-09-23 23:01:17 +00003049 HandleCodeCompleteResults(this, CodeCompleter,
3050 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003051 Results.data(), Results.size());
3052}
3053
Douglas Gregor68762e72010-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;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003062 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003063};
3064
Douglas Gregor7aa6b222010-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 Gregor85b50632010-07-28 21:50:18 +00003067///
3068/// \param IntegralConstantExpression Only permit integral constant
3069/// expressions.
Douglas Gregor68762e72010-08-23 21:17:50 +00003070void Sema::CodeCompleteExpression(Scope *S,
3071 const CodeCompleteExpressionData &Data) {
John McCall276321a2010-08-25 06:19:51 +00003072 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003073 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3074 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003075 if (Data.ObjCCollection)
3076 Results.setFilter(&ResultBuilder::IsObjCCollection);
3077 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003078 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003079 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003080 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3081 else
3082 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-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 Gregor7aa6b222010-05-30 01:49:25 +00003090
3091 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003092 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3093 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003094
3095 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003096 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003097 Results.ExitScope();
3098
Douglas Gregor55b037b2010-07-08 20:55:51 +00003099 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003100 if (!Data.PreferredType.isNull())
3101 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3102 || Data.PreferredType->isMemberPointerType()
3103 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003104
Douglas Gregorce0e8562010-08-23 21:54:33 +00003105 if (S->getFnParent() &&
3106 !Data.ObjCCollection &&
3107 !Data.IntegralConstantExpression)
3108 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3109
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003110 if (CodeCompleter->includeMacros())
Douglas Gregor55b037b2010-07-08 20:55:51 +00003111 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003112 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003113 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3114 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003115 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003116}
3117
Douglas Gregoreda7e542010-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 Gregored0b69d2010-09-15 16:23:04 +00003123}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003124
Douglas Gregorb888acf2010-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 Gregor9291bad2009-11-18 01:29:26 +00003129static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003130 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003131 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003132 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003133 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003134 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003135 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-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 Gregorb888acf2010-12-09 23:01:55 +00003141 ++P) {
3142 if (AddedProperties.insert(P->getIdentifier()))
3143 Results.MaybeAddResult(Result(*P, 0), CurContext);
3144 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003145
Douglas Gregor95147142011-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 Gregor9291bad2009-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 Gregor95147142011-05-05 15:50:42 +00003193 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3194 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003195 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003196 if (AllowCategories) {
3197 // Look through categories.
3198 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3199 Category; Category = Category->getNextClassCategory())
Douglas Gregor95147142011-05-05 15:50:42 +00003200 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3201 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003202 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003203
3204 // Look through protocols.
Ted Kremenek0ef508d2010-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 Gregor95147142011-05-05 15:50:42 +00003208 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3209 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003210
3211 // Look in the superclass.
3212 if (IFace->getSuperClass())
Douglas Gregor95147142011-05-05 15:50:42 +00003213 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3214 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003215 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003216 } else if (const ObjCCategoryDecl *Category
3217 = dyn_cast<ObjCCategoryDecl>(Container)) {
3218 // Look through protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00003219 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3220 PEnd = Category->protocol_end();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003221 P != PEnd; ++P)
Douglas Gregor95147142011-05-05 15:50:42 +00003222 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3223 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003224 }
3225}
3226
Douglas Gregor2436e712009-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 McCall276321a2010-08-25 06:19:51 +00003233 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003234
Douglas Gregor2436e712009-09-17 21:32:03 +00003235 Expr *Base = static_cast<Expr *>(BaseE);
3236 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-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 Gregor9be0ed42010-08-26 16:36:48 +00003242 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003243 else
3244 return;
3245 }
3246
Douglas Gregor21325842011-07-07 16:03:39 +00003247 enum CodeCompletionContext::Kind contextKind;
3248
3249 if (IsArrow) {
3250 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3251 }
3252 else {
3253 if (BaseType->isObjCObjectPointerType() ||
3254 BaseType->isObjCObjectOrInterfaceType()) {
3255 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3256 }
3257 else {
3258 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3259 }
3260 }
3261
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003262 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00003263 CodeCompletionContext(contextKind,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003264 BaseType),
3265 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003266 Results.EnterNewScope();
3267 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003268 // Indicate that we are performing a member access, and the cv-qualifiers
3269 // for the base object type.
3270 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3271
Douglas Gregor9291bad2009-11-18 01:29:26 +00003272 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003273 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003274 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003275 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3276 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003277
Douglas Gregor9291bad2009-11-18 01:29:26 +00003278 if (getLangOptions().CPlusPlus) {
3279 if (!Results.empty()) {
3280 // The "template" keyword can follow "->" or "." in the grammar.
3281 // However, we only want to suggest the template keyword if something
3282 // is dependent.
3283 bool IsDependent = BaseType->isDependentType();
3284 if (!IsDependent) {
3285 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3286 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3287 IsDependent = Ctx->isDependentContext();
3288 break;
3289 }
3290 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003291
Douglas Gregor9291bad2009-11-18 01:29:26 +00003292 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003293 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003294 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003295 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003296 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3297 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003298 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003299
3300 // Add property results based on our interface.
3301 const ObjCObjectPointerType *ObjCPtr
3302 = BaseType->getAsObjCInterfacePointerType();
3303 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor95147142011-05-05 15:50:42 +00003304 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3305 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003306 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003307
3308 // Add properties from the protocols in a qualified interface.
3309 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3310 E = ObjCPtr->qual_end();
3311 I != E; ++I)
Douglas Gregor95147142011-05-05 15:50:42 +00003312 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3313 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003314 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003315 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003316 // Objective-C instance variable access.
3317 ObjCInterfaceDecl *Class = 0;
3318 if (const ObjCObjectPointerType *ObjCPtr
3319 = BaseType->getAs<ObjCObjectPointerType>())
3320 Class = ObjCPtr->getInterfaceDecl();
3321 else
John McCall8b07ec22010-05-15 11:32:37 +00003322 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003323
3324 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003325 if (Class) {
3326 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3327 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003328 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3329 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003330 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003331 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003332
3333 // FIXME: How do we cope with isa?
3334
3335 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003336
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003337 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003338 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003339 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003340 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003341}
3342
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003343void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3344 if (!CodeCompleter)
3345 return;
3346
John McCall276321a2010-08-25 06:19:51 +00003347 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003348 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003349 enum CodeCompletionContext::Kind ContextKind
3350 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003351 switch ((DeclSpec::TST)TagSpec) {
3352 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003353 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003354 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003355 break;
3356
3357 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003358 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003359 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003360 break;
3361
3362 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003363 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003364 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003365 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003366 break;
3367
3368 default:
3369 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3370 return;
3371 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003372
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003373 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003374 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003375
3376 // First pass: look for tags.
3377 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003378 LookupVisibleDecls(S, LookupTagName, Consumer,
3379 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003380
Douglas Gregor39982192010-08-15 06:18:01 +00003381 if (CodeCompleter->includeGlobals()) {
3382 // Second pass: look for nested name specifiers.
3383 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3384 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3385 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003386
Douglas Gregor0ac41382010-09-23 23:01:17 +00003387 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003388 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003389}
3390
Douglas Gregor28c78432010-08-27 17:35:51 +00003391void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003392 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3393 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003394 Results.EnterNewScope();
3395 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3396 Results.AddResult("const");
3397 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3398 Results.AddResult("volatile");
3399 if (getLangOptions().C99 &&
3400 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3401 Results.AddResult("restrict");
3402 Results.ExitScope();
3403 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003404 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003405 Results.data(), Results.size());
3406}
3407
Douglas Gregord328d572009-09-21 18:10:23 +00003408void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003409 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003410 return;
3411
John McCallaab3e412010-08-25 08:40:02 +00003412 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregor85b50632010-07-28 21:50:18 +00003413 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregor68762e72010-08-23 21:17:50 +00003414 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3415 Data.IntegralConstantExpression = true;
3416 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003417 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003418 }
Douglas Gregord328d572009-09-21 18:10:23 +00003419
3420 // Code-complete the cases of a switch statement over an enumeration type
3421 // by providing the list of
3422 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3423
3424 // Determine which enumerators we have already seen in the switch statement.
3425 // FIXME: Ideally, we would also be able to look *past* the code-completion
3426 // token, in case we are code-completing in the middle of the switch and not
3427 // at the end. However, we aren't able to do so at the moment.
3428 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00003429 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00003430 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3431 SC = SC->getNextSwitchCase()) {
3432 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3433 if (!Case)
3434 continue;
3435
3436 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3438 if (EnumConstantDecl *Enumerator
3439 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3440 // We look into the AST of the case statement to determine which
3441 // enumerator was named. Alternatively, we could compute the value of
3442 // the integral constant expression, then compare it against the
3443 // values of each enumerator. However, value-based approach would not
3444 // work as well with C++ templates where enumerators declared within a
3445 // template are type- and value-dependent.
3446 EnumeratorsSeen.insert(Enumerator);
3447
Douglas Gregorf2510672009-09-21 19:57:38 +00003448 // If this is a qualified-id, keep track of the nested-name-specifier
3449 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003450 //
3451 // switch (TagD.getKind()) {
3452 // case TagDecl::TK_enum:
3453 // break;
3454 // case XXX
3455 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003456 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003457 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3458 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003459 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003460 }
3461 }
3462
Douglas Gregorf2510672009-09-21 19:57:38 +00003463 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3464 // If there are no prior enumerators in C++, check whether we have to
3465 // qualify the names of the enumerators that we suggest, because they
3466 // may not be visible in this scope.
3467 Qualifier = getRequiredQualification(Context, CurContext,
3468 Enum->getDeclContext());
3469
3470 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3471 }
3472
Douglas Gregord328d572009-09-21 18:10:23 +00003473 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003474 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3475 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003476 Results.EnterNewScope();
3477 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3478 EEnd = Enum->enumerator_end();
3479 E != EEnd; ++E) {
3480 if (EnumeratorsSeen.count(*E))
3481 continue;
3482
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00003483 CodeCompletionResult R(*E, Qualifier);
3484 R.Priority = CCP_EnumInCase;
3485 Results.AddResult(R, CurContext, 0, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003486 }
3487 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003488
Douglas Gregor21325842011-07-07 16:03:39 +00003489 //We need to make sure we're setting the right context,
3490 //so only say we include macros if the code completer says we do
3491 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3492 if (CodeCompleter->includeMacros()) {
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003493 AddMacroResults(PP, Results);
Douglas Gregor21325842011-07-07 16:03:39 +00003494 kind = CodeCompletionContext::CCC_OtherWithMacros;
3495 }
3496
3497
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003498 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003499 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003500 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003501}
3502
Douglas Gregorcabea402009-09-22 15:41:20 +00003503namespace {
3504 struct IsBetterOverloadCandidate {
3505 Sema &S;
John McCallbc077cf2010-02-08 23:07:23 +00003506 SourceLocation Loc;
Douglas Gregorcabea402009-09-22 15:41:20 +00003507
3508 public:
John McCallbc077cf2010-02-08 23:07:23 +00003509 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3510 : S(S), Loc(Loc) { }
Douglas Gregorcabea402009-09-22 15:41:20 +00003511
3512 bool
3513 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall5c32be02010-08-24 20:38:10 +00003514 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregorcabea402009-09-22 15:41:20 +00003515 }
3516 };
3517}
3518
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003519static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3520 if (NumArgs && !Args)
3521 return true;
3522
3523 for (unsigned I = 0; I != NumArgs; ++I)
3524 if (!Args[I])
3525 return true;
3526
3527 return false;
3528}
3529
Douglas Gregorcabea402009-09-22 15:41:20 +00003530void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3531 ExprTy **ArgsIn, unsigned NumArgs) {
3532 if (!CodeCompleter)
3533 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003534
3535 // When we're code-completing for a call, we fall back to ordinary
3536 // name code-completion whenever we can't produce specific
3537 // results. We may want to revisit this strategy in the future,
3538 // e.g., by merging the two kinds of results.
3539
Douglas Gregorcabea402009-09-22 15:41:20 +00003540 Expr *Fn = (Expr *)FnIn;
3541 Expr **Args = (Expr **)ArgsIn;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003542
Douglas Gregorcabea402009-09-22 15:41:20 +00003543 // Ignore type-dependent call expressions entirely.
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003544 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregor3ef59522009-12-11 19:06:04 +00003545 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003546 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00003547 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003548 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003549
John McCall57500772009-12-16 12:17:52 +00003550 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00003551 SourceLocation Loc = Fn->getExprLoc();
3552 OverloadCandidateSet CandidateSet(Loc);
John McCall57500772009-12-16 12:17:52 +00003553
Douglas Gregorcabea402009-09-22 15:41:20 +00003554 // FIXME: What if we're calling something that isn't a function declaration?
3555 // FIXME: What if we're calling a pseudo-destructor?
3556 // FIXME: What if we're calling a member function?
3557
Douglas Gregorff59f672010-01-21 15:46:19 +00003558 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003559 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00003560
John McCall57500772009-12-16 12:17:52 +00003561 Expr *NakedFn = Fn->IgnoreParenCasts();
3562 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3563 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3564 /*PartialOverloading=*/ true);
3565 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3566 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorff59f672010-01-21 15:46:19 +00003567 if (FDecl) {
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003568 if (!getLangOptions().CPlusPlus ||
3569 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorff59f672010-01-21 15:46:19 +00003570 Results.push_back(ResultCandidate(FDecl));
3571 else
John McCallb89836b2010-01-26 01:37:31 +00003572 // FIXME: access?
John McCalla0296f72010-03-19 07:35:19 +00003573 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3574 Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003575 false, /*PartialOverloading*/true);
Douglas Gregorff59f672010-01-21 15:46:19 +00003576 }
John McCall57500772009-12-16 12:17:52 +00003577 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003578
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003579 QualType ParamType;
3580
Douglas Gregorff59f672010-01-21 15:46:19 +00003581 if (!CandidateSet.empty()) {
3582 // Sort the overload candidate set by placing the best overloads first.
3583 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCallbc077cf2010-02-08 23:07:23 +00003584 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregorcabea402009-09-22 15:41:20 +00003585
Douglas Gregorff59f672010-01-21 15:46:19 +00003586 // Add the remaining viable overload candidates as code-completion reslults.
3587 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3588 CandEnd = CandidateSet.end();
3589 Cand != CandEnd; ++Cand) {
3590 if (Cand->Viable)
3591 Results.push_back(ResultCandidate(Cand->Function));
3592 }
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003593
3594 // From the viable candidates, try to determine the type of this parameter.
3595 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3596 if (const FunctionType *FType = Results[I].getFunctionType())
3597 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3598 if (NumArgs < Proto->getNumArgs()) {
3599 if (ParamType.isNull())
3600 ParamType = Proto->getArgType(NumArgs);
3601 else if (!Context.hasSameUnqualifiedType(
3602 ParamType.getNonReferenceType(),
3603 Proto->getArgType(NumArgs).getNonReferenceType())) {
3604 ParamType = QualType();
3605 break;
3606 }
3607 }
3608 }
3609 } else {
3610 // Try to determine the parameter type from the type of the expression
3611 // being called.
3612 QualType FunctionType = Fn->getType();
3613 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3614 FunctionType = Ptr->getPointeeType();
3615 else if (const BlockPointerType *BlockPtr
3616 = FunctionType->getAs<BlockPointerType>())
3617 FunctionType = BlockPtr->getPointeeType();
3618 else if (const MemberPointerType *MemPtr
3619 = FunctionType->getAs<MemberPointerType>())
3620 FunctionType = MemPtr->getPointeeType();
3621
3622 if (const FunctionProtoType *Proto
3623 = FunctionType->getAs<FunctionProtoType>()) {
3624 if (NumArgs < Proto->getNumArgs())
3625 ParamType = Proto->getArgType(NumArgs);
3626 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003627 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00003628
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003629 if (ParamType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003630 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003631 else
3632 CodeCompleteExpression(S, ParamType);
3633
Douglas Gregorc01890e2010-04-06 20:19:47 +00003634 if (!Results.empty())
Douglas Gregor3ef59522009-12-11 19:06:04 +00003635 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3636 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00003637}
3638
John McCall48871652010-08-21 09:40:31 +00003639void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3640 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003641 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003642 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003643 return;
3644 }
3645
3646 CodeCompleteExpression(S, VD->getType());
3647}
3648
3649void Sema::CodeCompleteReturn(Scope *S) {
3650 QualType ResultType;
3651 if (isa<BlockDecl>(CurContext)) {
3652 if (BlockScopeInfo *BSI = getCurBlock())
3653 ResultType = BSI->ReturnType;
3654 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3655 ResultType = Function->getResultType();
3656 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3657 ResultType = Method->getResultType();
3658
3659 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003660 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003661 else
3662 CodeCompleteExpression(S, ResultType);
3663}
3664
3665void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3666 if (LHS)
3667 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3668 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003669 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003670}
3671
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003672void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00003673 bool EnteringContext) {
3674 if (!SS.getScopeRep() || !CodeCompleter)
3675 return;
3676
Douglas Gregor3545ff42009-09-21 16:56:56 +00003677 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3678 if (!Ctx)
3679 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00003680
3681 // Try to instantiate any non-dependent declaration contexts before
3682 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00003683 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00003684 return;
3685
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003686 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3687 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003688 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003689
Douglas Gregor3545ff42009-09-21 16:56:56 +00003690 // The "template" keyword can follow "::" in the grammar, but only
3691 // put it into the grammar if the nested-name-specifier is dependent.
3692 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3693 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00003694 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00003695
3696 // Add calls to overridden virtual functions, if there are any.
3697 //
3698 // FIXME: This isn't wonderful, because we don't know whether we're actually
3699 // in a context that permits expressions. This is a general issue with
3700 // qualified-id completions.
3701 if (!EnteringContext)
3702 MaybeAddOverrideCalls(*this, Ctx, Results);
3703 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003704
Douglas Gregorac322ec2010-08-27 21:18:54 +00003705 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3706 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3707
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003708 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00003709 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003710 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003711}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003712
3713void Sema::CodeCompleteUsing(Scope *S) {
3714 if (!CodeCompleter)
3715 return;
3716
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003717 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003718 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3719 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003720 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003721
3722 // If we aren't in class scope, we could see the "namespace" keyword.
3723 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00003724 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00003725
3726 // After "using", we can see anything that would start a
3727 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003728 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003729 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3730 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00003731 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003732
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003733 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003734 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003735 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003736}
3737
3738void Sema::CodeCompleteUsingDirective(Scope *S) {
3739 if (!CodeCompleter)
3740 return;
3741
Douglas Gregor3545ff42009-09-21 16:56:56 +00003742 // After "using namespace", we expect to see a namespace name or namespace
3743 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003744 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3745 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003746 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003747 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003748 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003749 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3750 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00003751 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003752 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00003753 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003754 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003755}
3756
3757void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3758 if (!CodeCompleter)
3759 return;
3760
Douglas Gregor3545ff42009-09-21 16:56:56 +00003761 DeclContext *Ctx = (DeclContext *)S->getEntity();
3762 if (!S->getParent())
3763 Ctx = Context.getTranslationUnitDecl();
3764
Douglas Gregor0ac41382010-09-23 23:01:17 +00003765 bool SuppressedGlobalResults
3766 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3767
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003768 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003769 SuppressedGlobalResults
3770 ? CodeCompletionContext::CCC_Namespace
3771 : CodeCompletionContext::CCC_Other,
3772 &ResultBuilder::IsNamespace);
3773
3774 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003775 // We only want to see those namespaces that have already been defined
3776 // within this scope, because its likely that the user is creating an
3777 // extended namespace declaration. Keep track of the most recent
3778 // definition of each namespace.
3779 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3780 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3781 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3782 NS != NSEnd; ++NS)
3783 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3784
3785 // Add the most recent definition (or extended definition) of each
3786 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00003787 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003788 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3789 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3790 NS != NSEnd; ++NS)
John McCall276321a2010-08-25 06:19:51 +00003791 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003792 CurContext, 0, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003793 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003794 }
3795
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003796 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003797 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003798 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003799}
3800
3801void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3802 if (!CodeCompleter)
3803 return;
3804
Douglas Gregor3545ff42009-09-21 16:56:56 +00003805 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003806 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3807 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003808 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003809 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003810 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3811 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003812 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003813 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003814 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003815}
3816
Douglas Gregorc811ede2009-09-18 20:05:18 +00003817void Sema::CodeCompleteOperatorName(Scope *S) {
3818 if (!CodeCompleter)
3819 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003820
John McCall276321a2010-08-25 06:19:51 +00003821 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003822 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3823 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003824 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003825 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00003826
Douglas Gregor3545ff42009-09-21 16:56:56 +00003827 // Add the names of overloadable operators.
3828#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3829 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00003830 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00003831#include "clang/Basic/OperatorKinds.def"
3832
3833 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003834 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003835 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003836 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3837 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00003838
3839 // Add any type specifiers
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003840 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003841 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003842
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003843 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00003844 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003845 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00003846}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003847
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003848void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Alexis Hunt1d792652011-01-08 20:30:50 +00003849 CXXCtorInitializer** Initializers,
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003850 unsigned NumInitializers) {
John McCall31168b02011-06-15 23:02:42 +00003851 PrintingPolicy Policy(Context.PrintingPolicy);
3852 Policy.AnonymousTagLocations = false;
3853 Policy.SuppressStrongLifetime = true;
3854
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003855 CXXConstructorDecl *Constructor
3856 = static_cast<CXXConstructorDecl *>(ConstructorD);
3857 if (!Constructor)
3858 return;
3859
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003860 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003861 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003862 Results.EnterNewScope();
3863
3864 // Fill in any already-initialized fields or base classes.
3865 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3866 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3867 for (unsigned I = 0; I != NumInitializers; ++I) {
3868 if (Initializers[I]->isBaseInitializer())
3869 InitializedBases.insert(
3870 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3871 else
Francois Pichetd583da02010-12-04 09:14:42 +00003872 InitializedFields.insert(cast<FieldDecl>(
3873 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003874 }
3875
3876 // Add completions for base classes.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003877 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor99129ef2010-08-29 19:27:27 +00003878 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003879 CXXRecordDecl *ClassDecl = Constructor->getParent();
3880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3881 BaseEnd = ClassDecl->bases_end();
3882 Base != BaseEnd; ++Base) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00003883 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3884 SawLastInitializer
3885 = NumInitializers > 0 &&
3886 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3887 Context.hasSameUnqualifiedType(Base->getType(),
3888 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003889 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00003890 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003891
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003892 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003893 Results.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00003894 Base->getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003895 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3896 Builder.AddPlaceholderChunk("args");
3897 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3898 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00003899 SawLastInitializer? CCP_NextInitializer
3900 : CCP_MemberDeclaration));
3901 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003902 }
3903
3904 // Add completions for virtual base classes.
3905 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3906 BaseEnd = ClassDecl->vbases_end();
3907 Base != BaseEnd; ++Base) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00003908 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3909 SawLastInitializer
3910 = NumInitializers > 0 &&
3911 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3912 Context.hasSameUnqualifiedType(Base->getType(),
3913 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003914 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00003915 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003916
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003917 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003918 Builder.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00003919 Base->getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3921 Builder.AddPlaceholderChunk("args");
3922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3923 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00003924 SawLastInitializer? CCP_NextInitializer
3925 : CCP_MemberDeclaration));
3926 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003927 }
3928
3929 // Add completions for members.
3930 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3931 FieldEnd = ClassDecl->field_end();
3932 Field != FieldEnd; ++Field) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00003933 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3934 SawLastInitializer
3935 = NumInitializers > 0 &&
Francois Pichetd583da02010-12-04 09:14:42 +00003936 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3937 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003938 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00003939 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003940
3941 if (!Field->getDeclName())
3942 continue;
3943
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003944 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003945 Field->getIdentifier()->getName()));
3946 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3947 Builder.AddPlaceholderChunk("args");
3948 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3949 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00003950 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00003951 : CCP_MemberDeclaration,
3952 CXCursor_MemberRef));
Douglas Gregor99129ef2010-08-29 19:27:27 +00003953 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003954 }
3955 Results.ExitScope();
3956
Douglas Gregor0ac41382010-09-23 23:01:17 +00003957 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003958 Results.data(), Results.size());
3959}
3960
Douglas Gregorf1934162010-01-13 21:24:21 +00003961// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3962// true or false.
3963#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003964static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00003965 ResultBuilder &Results,
3966 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00003967 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00003968 // Since we have an implementation, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00003969 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00003970
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003971 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00003972 if (LangOpts.ObjC2) {
3973 // @dynamic
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003974 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3975 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3976 Builder.AddPlaceholderChunk("property");
3977 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00003978
3979 // @synthesize
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003980 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3981 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3982 Builder.AddPlaceholderChunk("property");
3983 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00003984 }
3985}
3986
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003987static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00003988 ResultBuilder &Results,
3989 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00003990 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00003991
3992 // Since we have an interface or protocol, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00003993 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00003994
3995 if (LangOpts.ObjC2) {
3996 // @property
Douglas Gregor78a21012010-01-14 16:01:26 +00003997 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorf1934162010-01-13 21:24:21 +00003998
3999 // @required
Douglas Gregor78a21012010-01-14 16:01:26 +00004000 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004001
4002 // @optional
Douglas Gregor78a21012010-01-14 16:01:26 +00004003 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004004 }
4005}
4006
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004007static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004008 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004009 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00004010
4011 // @class name ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004012 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4014 Builder.AddPlaceholderChunk("name");
4015 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004016
Douglas Gregorf4c33342010-05-28 00:22:41 +00004017 if (Results.includeCodePatterns()) {
4018 // @interface name
4019 // FIXME: Could introduce the whole pattern, including superclasses and
4020 // such.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004021 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4022 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4023 Builder.AddPlaceholderChunk("class");
4024 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004025
Douglas Gregorf4c33342010-05-28 00:22:41 +00004026 // @protocol name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004027 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4028 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4029 Builder.AddPlaceholderChunk("protocol");
4030 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004031
4032 // @implementation name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004033 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4034 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4035 Builder.AddPlaceholderChunk("class");
4036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004037 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004038
4039 // @compatibility_alias name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004040 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4041 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4042 Builder.AddPlaceholderChunk("alias");
4043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4044 Builder.AddPlaceholderChunk("class");
4045 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004046}
4047
John McCall48871652010-08-21 09:40:31 +00004048void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorf48706c2009-12-07 09:27:33 +00004049 bool InInterface) {
John McCall276321a2010-08-25 06:19:51 +00004050 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004051 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4052 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004053 Results.EnterNewScope();
Douglas Gregorf1934162010-01-13 21:24:21 +00004054 if (ObjCImpDecl)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004055 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004056 else if (InInterface)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004057 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004058 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004059 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004060 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004061 HandleCodeCompleteResults(this, CodeCompleter,
4062 CodeCompletionContext::CCC_Other,
4063 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004064}
4065
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004066static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004067 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004068 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004069
4070 // @encode ( type-name )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004071 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4073 Builder.AddPlaceholderChunk("type-name");
4074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4075 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004076
4077 // @protocol ( protocol-name )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004078 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4080 Builder.AddPlaceholderChunk("protocol-name");
4081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4082 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004083
4084 // @selector ( selector )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004085 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4087 Builder.AddPlaceholderChunk("selector");
4088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4089 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004090}
4091
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004092static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004093 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004094 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00004095
Douglas Gregorf4c33342010-05-28 00:22:41 +00004096 if (Results.includeCodePatterns()) {
4097 // @try { statements } @catch ( declaration ) { statements } @finally
4098 // { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004099 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4100 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4101 Builder.AddPlaceholderChunk("statements");
4102 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4103 Builder.AddTextChunk("@catch");
4104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4105 Builder.AddPlaceholderChunk("parameter");
4106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4107 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4108 Builder.AddPlaceholderChunk("statements");
4109 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4110 Builder.AddTextChunk("@finally");
4111 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4112 Builder.AddPlaceholderChunk("statements");
4113 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4114 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004115 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004116
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004117 // @throw
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004118 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4119 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4120 Builder.AddPlaceholderChunk("expression");
4121 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004122
Douglas Gregorf4c33342010-05-28 00:22:41 +00004123 if (Results.includeCodePatterns()) {
4124 // @synchronized ( expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004125 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4127 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4128 Builder.AddPlaceholderChunk("expression");
4129 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4130 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4131 Builder.AddPlaceholderChunk("statements");
4132 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4133 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004134 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004135}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004136
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004137static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004138 ResultBuilder &Results,
4139 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004140 typedef CodeCompletionResult Result;
Douglas Gregor78a21012010-01-14 16:01:26 +00004141 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4142 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4143 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregor48d46252010-01-13 21:54:15 +00004144 if (LangOpts.ObjC2)
Douglas Gregor78a21012010-01-14 16:01:26 +00004145 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregor48d46252010-01-13 21:54:15 +00004146}
4147
4148void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004149 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4150 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004151 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004152 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004153 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004154 HandleCodeCompleteResults(this, CodeCompleter,
4155 CodeCompletionContext::CCC_Other,
4156 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004157}
4158
4159void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4161 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004162 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004163 AddObjCStatementResults(Results, false);
4164 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004165 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004166 HandleCodeCompleteResults(this, CodeCompleter,
4167 CodeCompletionContext::CCC_Other,
4168 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004169}
4170
4171void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004172 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4173 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004174 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004175 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004176 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004177 HandleCodeCompleteResults(this, CodeCompleter,
4178 CodeCompletionContext::CCC_Other,
4179 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004180}
4181
Douglas Gregore6078da2009-11-19 00:14:45 +00004182/// \brief Determine whether the addition of the given flag to an Objective-C
4183/// property's attributes will cause a conflict.
4184static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4185 // Check if we've already added this flag.
4186 if (Attributes & NewFlag)
4187 return true;
4188
4189 Attributes |= NewFlag;
4190
4191 // Check for collisions with "readonly".
4192 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4193 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4194 ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004195 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004196 ObjCDeclSpec::DQ_PR_copy |
John McCall31168b02011-06-15 23:02:42 +00004197 ObjCDeclSpec::DQ_PR_retain |
4198 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregore6078da2009-11-19 00:14:45 +00004199 return true;
4200
John McCall31168b02011-06-15 23:02:42 +00004201 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregore6078da2009-11-19 00:14:45 +00004202 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004203 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004204 ObjCDeclSpec::DQ_PR_copy |
John McCall31168b02011-06-15 23:02:42 +00004205 ObjCDeclSpec::DQ_PR_retain|
4206 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregore6078da2009-11-19 00:14:45 +00004207 if (AssignCopyRetMask &&
4208 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004209 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004210 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004211 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4212 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregore6078da2009-11-19 00:14:45 +00004213 return true;
4214
4215 return false;
4216}
4217
Douglas Gregor36029f42009-11-18 23:08:07 +00004218void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004219 if (!CodeCompleter)
4220 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004221
Steve Naroff936354c2009-10-08 21:55:05 +00004222 unsigned Attributes = ODS.getPropertyAttributes();
4223
John McCall276321a2010-08-25 06:19:51 +00004224 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004225 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4226 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004227 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00004228 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004229 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004230 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004231 Results.AddResult(CodeCompletionResult("assign"));
John McCall31168b02011-06-15 23:02:42 +00004232 if (!ObjCPropertyFlagConflicts(Attributes,
4233 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4234 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004235 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004236 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004237 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004238 Results.AddResult(CodeCompletionResult("retain"));
John McCall31168b02011-06-15 23:02:42 +00004239 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4240 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004241 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004242 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004243 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004244 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004245 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4246 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004247 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004248 CodeCompletionBuilder Setter(Results.getAllocator());
4249 Setter.AddTypedTextChunk("setter");
4250 Setter.AddTextChunk(" = ");
4251 Setter.AddPlaceholderChunk("method");
4252 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004253 }
Douglas Gregore6078da2009-11-19 00:14:45 +00004254 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004255 CodeCompletionBuilder Getter(Results.getAllocator());
4256 Getter.AddTypedTextChunk("getter");
4257 Getter.AddTextChunk(" = ");
4258 Getter.AddPlaceholderChunk("method");
4259 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004260 }
Steve Naroff936354c2009-10-08 21:55:05 +00004261 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004262 HandleCodeCompleteResults(this, CodeCompleter,
4263 CodeCompletionContext::CCC_Other,
4264 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004265}
Steve Naroffeae65032009-11-07 02:08:14 +00004266
Douglas Gregorc8537c52009-11-19 07:41:15 +00004267/// \brief Descripts the kind of Objective-C method that we want to find
4268/// via code completion.
4269enum ObjCMethodKind {
4270 MK_Any, //< Any kind of method, provided it means other specified criteria.
4271 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4272 MK_OneArgSelector //< One-argument selector.
4273};
4274
Douglas Gregor67c692c2010-08-26 15:07:07 +00004275static bool isAcceptableObjCSelector(Selector Sel,
4276 ObjCMethodKind WantKind,
4277 IdentifierInfo **SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004278 unsigned NumSelIdents,
4279 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004280 if (NumSelIdents > Sel.getNumArgs())
4281 return false;
4282
4283 switch (WantKind) {
4284 case MK_Any: break;
4285 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4286 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4287 }
4288
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004289 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4290 return false;
4291
Douglas Gregor67c692c2010-08-26 15:07:07 +00004292 for (unsigned I = 0; I != NumSelIdents; ++I)
4293 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4294 return false;
4295
4296 return true;
4297}
4298
Douglas Gregorc8537c52009-11-19 07:41:15 +00004299static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4300 ObjCMethodKind WantKind,
4301 IdentifierInfo **SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004302 unsigned NumSelIdents,
4303 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004304 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004305 NumSelIdents, AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004306}
Douglas Gregor1154e272010-09-16 16:06:31 +00004307
4308namespace {
4309 /// \brief A set of selectors, which is used to avoid introducing multiple
4310 /// completions with the same selector into the result set.
4311 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4312}
4313
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004314/// \brief Add all of the Objective-C methods in the given Objective-C
4315/// container to the set of results.
4316///
4317/// The container will be a class, protocol, category, or implementation of
4318/// any of the above. This mether will recurse to include methods from
4319/// the superclasses of classes along with their categories, protocols, and
4320/// implementations.
4321///
4322/// \param Container the container in which we'll look to find methods.
4323///
4324/// \param WantInstance whether to add instance methods (only); if false, this
4325/// routine will add factory methods (only).
4326///
4327/// \param CurContext the context in which we're performing the lookup that
4328/// finds methods.
4329///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004330/// \param AllowSameLength Whether we allow a method to be added to the list
4331/// when it has the same number of parameters as we have selector identifiers.
4332///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004333/// \param Results the structure into which we'll add results.
4334static void AddObjCMethods(ObjCContainerDecl *Container,
4335 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00004336 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00004337 IdentifierInfo **SelIdents,
4338 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004339 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00004340 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004341 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00004342 ResultBuilder &Results,
4343 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00004344 typedef CodeCompletionResult Result;
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004345 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4346 MEnd = Container->meth_end();
4347 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00004348 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4349 // Check whether the selector identifiers we've been given are a
4350 // subset of the identifiers for this particular method.
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004351 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4352 AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00004353 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004354
Douglas Gregor1154e272010-09-16 16:06:31 +00004355 if (!Selectors.insert((*M)->getSelector()))
4356 continue;
4357
Douglas Gregor1b605f72009-11-19 01:08:35 +00004358 Result R = Result(*M, 0);
4359 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004360 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00004361 if (!InOriginalClass)
4362 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004363 Results.MaybeAddResult(R, CurContext);
4364 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004365 }
4366
Douglas Gregorf37c9492010-09-16 15:34:59 +00004367 // Visit the protocols of protocols.
4368 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4369 const ObjCList<ObjCProtocolDecl> &Protocols
4370 = Protocol->getReferencedProtocols();
4371 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4372 E = Protocols.end();
4373 I != E; ++I)
4374 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004375 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorf37c9492010-09-16 15:34:59 +00004376 }
4377
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004378 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4379 if (!IFace)
4380 return;
4381
4382 // Add methods in protocols.
4383 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4384 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4385 E = Protocols.end();
4386 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004387 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004388 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004389
4390 // Add methods in categories.
4391 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4392 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00004393 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004394 NumSelIdents, CurContext, Selectors, AllowSameLength,
4395 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004396
4397 // Add a categories protocol methods.
4398 const ObjCList<ObjCProtocolDecl> &Protocols
4399 = CatDecl->getReferencedProtocols();
4400 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4401 E = Protocols.end();
4402 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004403 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004404 NumSelIdents, CurContext, Selectors, AllowSameLength,
4405 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004406
4407 // Add methods in category implementations.
4408 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004409 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004410 NumSelIdents, CurContext, Selectors, AllowSameLength,
4411 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004412 }
4413
4414 // Add methods in superclass.
4415 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004416 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004417 SelIdents, NumSelIdents, CurContext, Selectors,
4418 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004419
4420 // Add methods in our implementation, if any.
4421 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004422 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004423 NumSelIdents, CurContext, Selectors, AllowSameLength,
4424 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004425}
4426
4427
Douglas Gregor87e92752010-12-21 17:34:17 +00004428void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall276321a2010-08-25 06:19:51 +00004429 typedef CodeCompletionResult Result;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004430
4431 // Try to find the interface where getters might live.
John McCall48871652010-08-21 09:40:31 +00004432 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004433 if (!Class) {
4434 if (ObjCCategoryDecl *Category
John McCall48871652010-08-21 09:40:31 +00004435 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004436 Class = Category->getClassInterface();
4437
4438 if (!Class)
4439 return;
4440 }
4441
4442 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004443 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4444 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004445 Results.EnterNewScope();
4446
Douglas Gregor1154e272010-09-16 16:06:31 +00004447 VisitedSelectorSet Selectors;
4448 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004449 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004450 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004451 HandleCodeCompleteResults(this, CodeCompleter,
4452 CodeCompletionContext::CCC_Other,
4453 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00004454}
4455
Douglas Gregor87e92752010-12-21 17:34:17 +00004456void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall276321a2010-08-25 06:19:51 +00004457 typedef CodeCompletionResult Result;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004458
4459 // Try to find the interface where setters might live.
4460 ObjCInterfaceDecl *Class
John McCall48871652010-08-21 09:40:31 +00004461 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004462 if (!Class) {
4463 if (ObjCCategoryDecl *Category
John McCall48871652010-08-21 09:40:31 +00004464 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004465 Class = Category->getClassInterface();
4466
4467 if (!Class)
4468 return;
4469 }
4470
4471 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004472 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4473 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004474 Results.EnterNewScope();
4475
Douglas Gregor1154e272010-09-16 16:06:31 +00004476 VisitedSelectorSet Selectors;
4477 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004478 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004479
4480 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004481 HandleCodeCompleteResults(this, CodeCompleter,
4482 CodeCompletionContext::CCC_Other,
4483 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004484}
4485
Douglas Gregorf34a6f02011-02-15 22:19:42 +00004486void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4487 bool IsParameter) {
John McCall276321a2010-08-25 06:19:51 +00004488 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004489 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4490 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00004491 Results.EnterNewScope();
4492
4493 // Add context-sensitive, Objective-C parameter-passing keywords.
4494 bool AddedInOut = false;
4495 if ((DS.getObjCDeclQualifier() &
4496 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4497 Results.AddResult("in");
4498 Results.AddResult("inout");
4499 AddedInOut = true;
4500 }
4501 if ((DS.getObjCDeclQualifier() &
4502 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4503 Results.AddResult("out");
4504 if (!AddedInOut)
4505 Results.AddResult("inout");
4506 }
4507 if ((DS.getObjCDeclQualifier() &
4508 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4509 ObjCDeclSpec::DQ_Oneway)) == 0) {
4510 Results.AddResult("bycopy");
4511 Results.AddResult("byref");
4512 Results.AddResult("oneway");
4513 }
4514
Douglas Gregorf34a6f02011-02-15 22:19:42 +00004515 // If we're completing the return type of an Objective-C method and the
4516 // identifier IBAction refers to a macro, provide a completion item for
4517 // an action, e.g.,
4518 // IBAction)<#selector#>:(id)sender
4519 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4520 Context.Idents.get("IBAction").hasMacroDefinition()) {
4521 typedef CodeCompletionString::Chunk Chunk;
4522 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4523 CXAvailability_Available);
4524 Builder.AddTypedTextChunk("IBAction");
4525 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4526 Builder.AddPlaceholderChunk("selector");
4527 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4528 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4529 Builder.AddTextChunk("id");
4530 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4531 Builder.AddTextChunk("sender");
4532 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4533 }
4534
Douglas Gregor99fa2642010-08-24 01:06:58 +00004535 // Add various builtin type names and specifiers.
4536 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4537 Results.ExitScope();
4538
4539 // Add the various type names
4540 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4541 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4542 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4543 CodeCompleter->includeGlobals());
4544
4545 if (CodeCompleter->includeMacros())
4546 AddMacroResults(PP, Results);
4547
4548 HandleCodeCompleteResults(this, CodeCompleter,
4549 CodeCompletionContext::CCC_Type,
4550 Results.data(), Results.size());
4551}
4552
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004553/// \brief When we have an expression with type "id", we may assume
4554/// that it has some more-specific class type based on knowledge of
4555/// common uses of Objective-C. This routine returns that class type,
4556/// or NULL if no better result could be determined.
4557static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00004558 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004559 if (!Msg)
4560 return 0;
4561
4562 Selector Sel = Msg->getSelector();
4563 if (Sel.isNull())
4564 return 0;
4565
4566 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4567 if (!Id)
4568 return 0;
4569
4570 ObjCMethodDecl *Method = Msg->getMethodDecl();
4571 if (!Method)
4572 return 0;
4573
4574 // Determine the class that we're sending the message to.
Douglas Gregor9a129192010-04-21 00:45:42 +00004575 ObjCInterfaceDecl *IFace = 0;
4576 switch (Msg->getReceiverKind()) {
4577 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00004578 if (const ObjCObjectType *ObjType
4579 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4580 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00004581 break;
4582
4583 case ObjCMessageExpr::Instance: {
4584 QualType T = Msg->getInstanceReceiver()->getType();
4585 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4586 IFace = Ptr->getInterfaceDecl();
4587 break;
4588 }
4589
4590 case ObjCMessageExpr::SuperInstance:
4591 case ObjCMessageExpr::SuperClass:
4592 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004593 }
4594
4595 if (!IFace)
4596 return 0;
4597
4598 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4599 if (Method->isInstanceMethod())
4600 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4601 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00004602 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004603 .Case("autorelease", IFace)
4604 .Case("copy", IFace)
4605 .Case("copyWithZone", IFace)
4606 .Case("mutableCopy", IFace)
4607 .Case("mutableCopyWithZone", IFace)
4608 .Case("awakeFromCoder", IFace)
4609 .Case("replacementObjectFromCoder", IFace)
4610 .Case("class", IFace)
4611 .Case("classForCoder", IFace)
4612 .Case("superclass", Super)
4613 .Default(0);
4614
4615 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4616 .Case("new", IFace)
4617 .Case("alloc", IFace)
4618 .Case("allocWithZone", IFace)
4619 .Case("class", IFace)
4620 .Case("superclass", Super)
4621 .Default(0);
4622}
4623
Douglas Gregor6fc04132010-08-27 15:10:57 +00004624// Add a special completion for a message send to "super", which fills in the
4625// most likely case of forwarding all of our arguments to the superclass
4626// function.
4627///
4628/// \param S The semantic analysis object.
4629///
4630/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4631/// the "super" keyword. Otherwise, we just need to provide the arguments.
4632///
4633/// \param SelIdents The identifiers in the selector that have already been
4634/// provided as arguments for a send to "super".
4635///
4636/// \param NumSelIdents The number of identifiers in \p SelIdents.
4637///
4638/// \param Results The set of results to augment.
4639///
4640/// \returns the Objective-C method declaration that would be invoked by
4641/// this "super" completion. If NULL, no completion was added.
4642static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4643 IdentifierInfo **SelIdents,
4644 unsigned NumSelIdents,
4645 ResultBuilder &Results) {
4646 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4647 if (!CurMethod)
4648 return 0;
4649
4650 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4651 if (!Class)
4652 return 0;
4653
4654 // Try to find a superclass method with the same selector.
4655 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00004656 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4657 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00004658 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4659 CurMethod->isInstanceMethod());
4660
Douglas Gregorb5f1e462011-02-16 00:51:18 +00004661 // Check in categories or class extensions.
4662 if (!SuperMethod) {
4663 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4664 Category = Category->getNextClassCategory())
4665 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4666 CurMethod->isInstanceMethod())))
4667 break;
4668 }
4669 }
4670
Douglas Gregor6fc04132010-08-27 15:10:57 +00004671 if (!SuperMethod)
4672 return 0;
4673
4674 // Check whether the superclass method has the same signature.
4675 if (CurMethod->param_size() != SuperMethod->param_size() ||
4676 CurMethod->isVariadic() != SuperMethod->isVariadic())
4677 return 0;
4678
4679 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4680 CurPEnd = CurMethod->param_end(),
4681 SuperP = SuperMethod->param_begin();
4682 CurP != CurPEnd; ++CurP, ++SuperP) {
4683 // Make sure the parameter types are compatible.
4684 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4685 (*SuperP)->getType()))
4686 return 0;
4687
4688 // Make sure we have a parameter name to forward!
4689 if (!(*CurP)->getIdentifier())
4690 return 0;
4691 }
4692
4693 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004694 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor6fc04132010-08-27 15:10:57 +00004695
4696 // Give this completion a return type.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004697 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004698
4699 // If we need the "super" keyword, add it (plus some spacing).
4700 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004701 Builder.AddTypedTextChunk("super");
4702 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004703 }
4704
4705 Selector Sel = CurMethod->getSelector();
4706 if (Sel.isUnarySelector()) {
4707 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004708 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004709 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004710 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004711 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004712 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004713 } else {
4714 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4715 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4716 if (I > NumSelIdents)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004718
4719 if (I < NumSelIdents)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004720 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004721 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004722 Sel.getNameForSlot(I) + ":"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004723 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004724 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004725 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004726 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004727 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004728 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004729 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004730 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004731 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004732 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004733 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004734 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004735 }
4736 }
4737 }
4738
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004739 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor6fc04132010-08-27 15:10:57 +00004740 SuperMethod->isInstanceMethod()
4741 ? CXCursor_ObjCInstanceMethodDecl
4742 : CXCursor_ObjCClassMethodDecl));
4743 return SuperMethod;
4744}
4745
Douglas Gregora817a192010-05-27 23:06:34 +00004746void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00004747 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004748 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4749 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004750 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00004751
Douglas Gregora817a192010-05-27 23:06:34 +00004752 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4753 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00004754 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4755 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00004756
4757 // If we are in an Objective-C method inside a class that has a superclass,
4758 // add "super" as an option.
4759 if (ObjCMethodDecl *Method = getCurMethodDecl())
4760 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00004761 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00004762 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004763
4764 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4765 }
Douglas Gregora817a192010-05-27 23:06:34 +00004766
4767 Results.ExitScope();
4768
4769 if (CodeCompleter->includeMacros())
4770 AddMacroResults(PP, Results);
Douglas Gregor50832e02010-09-20 22:39:41 +00004771 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004772 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00004773
4774}
4775
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004776void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4777 IdentifierInfo **SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004778 unsigned NumSelIdents,
4779 bool AtArgumentExpression) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004780 ObjCInterfaceDecl *CDecl = 0;
4781 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4782 // Figure out which interface we're in.
4783 CDecl = CurMethod->getClassInterface();
4784 if (!CDecl)
4785 return;
4786
4787 // Find the superclass of this class.
4788 CDecl = CDecl->getSuperClass();
4789 if (!CDecl)
4790 return;
4791
4792 if (CurMethod->isInstanceMethod()) {
4793 // We are inside an instance method, which means that the message
4794 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00004795 // current object.
4796 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor6fc04132010-08-27 15:10:57 +00004797 SelIdents, NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004798 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00004799 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004800 }
4801
4802 // Fall through to send to the superclass in CDecl.
4803 } else {
4804 // "super" may be the name of a type or variable. Figure out which
4805 // it is.
4806 IdentifierInfo *Super = &Context.Idents.get("super");
4807 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4808 LookupOrdinaryName);
4809 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4810 // "super" names an interface. Use it.
4811 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00004812 if (const ObjCObjectType *Iface
4813 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4814 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004815 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4816 // "super" names an unresolved type; we can't be more specific.
4817 } else {
4818 // Assume that "super" names some kind of value and parse that way.
4819 CXXScopeSpec SS;
4820 UnqualifiedId id;
4821 id.setIdentifier(Super, SuperLoc);
John McCalldadc5752010-08-24 06:29:42 +00004822 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004823 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004824 SelIdents, NumSelIdents,
4825 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004826 }
4827
4828 // Fall through
4829 }
4830
John McCallba7bf592010-08-24 05:47:05 +00004831 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004832 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00004833 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004834 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004835 NumSelIdents, AtArgumentExpression,
4836 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004837}
4838
Douglas Gregor74661272010-09-21 00:03:25 +00004839/// \brief Given a set of code-completion results for the argument of a message
4840/// send, determine the preferred type (if any) for that argument expression.
4841static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4842 unsigned NumSelIdents) {
4843 typedef CodeCompletionResult Result;
4844 ASTContext &Context = Results.getSema().Context;
4845
4846 QualType PreferredType;
4847 unsigned BestPriority = CCP_Unlikely * 2;
4848 Result *ResultsData = Results.data();
4849 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4850 Result &R = ResultsData[I];
4851 if (R.Kind == Result::RK_Declaration &&
4852 isa<ObjCMethodDecl>(R.Declaration)) {
4853 if (R.Priority <= BestPriority) {
4854 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4855 if (NumSelIdents <= Method->param_size()) {
4856 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4857 ->getType();
4858 if (R.Priority < BestPriority || PreferredType.isNull()) {
4859 BestPriority = R.Priority;
4860 PreferredType = MyPreferredType;
4861 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4862 MyPreferredType)) {
4863 PreferredType = QualType();
4864 }
4865 }
4866 }
4867 }
4868 }
4869
4870 return PreferredType;
4871}
4872
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004873static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4874 ParsedType Receiver,
4875 IdentifierInfo **SelIdents,
4876 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004877 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004878 bool IsSuper,
4879 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00004880 typedef CodeCompletionResult Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00004881 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004882
Douglas Gregor8ce33212009-11-17 17:59:40 +00004883 // If the given name refers to an interface type, retrieve the
4884 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004885 if (Receiver) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004886 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004887 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00004888 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4889 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00004890 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004891
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004892 // Add all of the factory methods in this Objective-C class, its protocols,
4893 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00004894 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004895
Douglas Gregor6fc04132010-08-27 15:10:57 +00004896 // If this is a send-to-super, try to add the special "super" send
4897 // completion.
4898 if (IsSuper) {
4899 if (ObjCMethodDecl *SuperMethod
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004900 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4901 Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00004902 Results.Ignore(SuperMethod);
4903 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004904
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00004905 // If we're inside an Objective-C method definition, prefer its selector to
4906 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004907 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00004908 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004909
Douglas Gregor1154e272010-09-16 16:06:31 +00004910 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00004911 if (CDecl)
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004912 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004913 SemaRef.CurContext, Selectors, AtArgumentExpression,
4914 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004915 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00004916 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004917
Douglas Gregord720daf2010-04-06 17:30:22 +00004918 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004919 // pool from the AST file.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004920 if (SemaRef.ExternalSource) {
4921 for (uint32_t I = 0,
4922 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00004923 I != N; ++I) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004924 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4925 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00004926 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004927
4928 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00004929 }
4930 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004931
4932 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4933 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00004934 M != MEnd; ++M) {
4935 for (ObjCMethodList *MethList = &M->second.second;
4936 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00004937 MethList = MethList->Next) {
4938 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4939 NumSelIdents))
4940 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004941
Douglas Gregor6285f752010-04-06 16:40:00 +00004942 Result R(MethList->Method, 0);
4943 R.StartParameter = NumSelIdents;
4944 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004945 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00004946 }
4947 }
4948 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004949
4950 Results.ExitScope();
4951}
Douglas Gregor6285f752010-04-06 16:40:00 +00004952
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004953void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4954 IdentifierInfo **SelIdents,
4955 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004956 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00004957 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00004958
4959 QualType T = this->GetTypeFromParser(Receiver);
4960
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004961 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor63745d52011-07-21 01:05:26 +00004962 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregorea777402011-07-26 15:24:30 +00004963 T, SelIdents, NumSelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00004964
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004965 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4966 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00004967
4968 // If we're actually at the argument expression (rather than prior to the
4969 // selector), we're actually performing code completion for an expression.
4970 // Determine whether we have a single, best method. If so, we can
4971 // code-complete the expression using the corresponding parameter type as
4972 // our preferred type, improving completion results.
4973 if (AtArgumentExpression) {
4974 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregor63745d52011-07-21 01:05:26 +00004975 NumSelIdents);
Douglas Gregor74661272010-09-21 00:03:25 +00004976 if (PreferredType.isNull())
4977 CodeCompleteOrdinaryName(S, PCC_Expression);
4978 else
4979 CodeCompleteExpression(S, PreferredType);
4980 return;
4981 }
4982
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004983 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00004984 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00004985 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00004986}
4987
Douglas Gregor1b605f72009-11-19 01:08:35 +00004988void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4989 IdentifierInfo **SelIdents,
Douglas Gregor6fc04132010-08-27 15:10:57 +00004990 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004991 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00004992 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00004993 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00004994
4995 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00004996
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004997 // If necessary, apply function/array conversion to the receiver.
4998 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00004999 if (RecExpr) {
5000 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5001 if (Conv.isInvalid()) // conversion failed. bail.
5002 return;
5003 RecExpr = Conv.take();
5004 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005005 QualType ReceiverType = RecExpr? RecExpr->getType()
5006 : Super? Context.getObjCObjectPointerType(
5007 Context.getObjCInterfaceType(Super))
5008 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005009
Douglas Gregordc520b02010-11-08 21:12:30 +00005010 // If we're messaging an expression with type "id" or "Class", check
5011 // whether we know something special about the receiver that allows
5012 // us to assume a more-specific receiver type.
5013 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5014 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5015 if (ReceiverType->isObjCClassType())
5016 return CodeCompleteObjCClassMessage(S,
5017 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5018 SelIdents, NumSelIdents,
5019 AtArgumentExpression, Super);
5020
5021 ReceiverType = Context.getObjCObjectPointerType(
5022 Context.getObjCInterfaceType(IFace));
5023 }
5024
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005025 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005026 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005027 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregorea777402011-07-26 15:24:30 +00005028 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005029
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005030 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005031
Douglas Gregor6fc04132010-08-27 15:10:57 +00005032 // If this is a send-to-super, try to add the special "super" send
5033 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005034 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005035 if (ObjCMethodDecl *SuperMethod
5036 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5037 Results))
5038 Results.Ignore(SuperMethod);
5039 }
5040
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005041 // If we're inside an Objective-C method definition, prefer its selector to
5042 // others.
5043 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5044 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005045
Douglas Gregor1154e272010-09-16 16:06:31 +00005046 // Keep track of the selectors we've already added.
5047 VisitedSelectorSet Selectors;
5048
Douglas Gregora3329fa2009-11-18 00:06:18 +00005049 // Handle messages to Class. This really isn't a message to an instance
5050 // method, so we treat it the same way we would treat a message send to a
5051 // class method.
5052 if (ReceiverType->isObjCClassType() ||
5053 ReceiverType->isObjCQualifiedClassType()) {
5054 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5055 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005056 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005057 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005058 }
5059 }
5060 // Handle messages to a qualified ID ("id<foo>").
5061 else if (const ObjCObjectPointerType *QualID
5062 = ReceiverType->getAsObjCQualifiedIdType()) {
5063 // Search protocols for instance methods.
5064 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5065 E = QualID->qual_end();
5066 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005067 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005068 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005069 }
5070 // Handle messages to a pointer to interface type.
5071 else if (const ObjCObjectPointerType *IFacePtr
5072 = ReceiverType->getAsObjCInterfacePointerType()) {
5073 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005074 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005075 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5076 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005077
5078 // Search protocols for instance methods.
5079 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5080 E = IFacePtr->qual_end();
5081 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005082 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005083 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005084 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005085 // Handle messages to "id".
5086 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005087 // We're messaging "id", so provide all instance methods we know
5088 // about as code-completion results.
5089
5090 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005091 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005092 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005093 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5094 I != N; ++I) {
5095 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005096 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005097 continue;
5098
Sebastian Redl75d8a322010-08-02 23:18:59 +00005099 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005100 }
5101 }
5102
Sebastian Redl75d8a322010-08-02 23:18:59 +00005103 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5104 MEnd = MethodPool.end();
5105 M != MEnd; ++M) {
5106 for (ObjCMethodList *MethList = &M->second.first;
5107 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00005108 MethList = MethList->Next) {
5109 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5110 NumSelIdents))
5111 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005112
5113 if (!Selectors.insert(MethList->Method->getSelector()))
5114 continue;
5115
Douglas Gregor6285f752010-04-06 16:40:00 +00005116 Result R(MethList->Method, 0);
5117 R.StartParameter = NumSelIdents;
5118 R.AllParametersAreInformative = false;
5119 Results.MaybeAddResult(R, CurContext);
5120 }
5121 }
5122 }
Steve Naroffeae65032009-11-07 02:08:14 +00005123 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005124
5125
5126 // If we're actually at the argument expression (rather than prior to the
5127 // selector), we're actually performing code completion for an expression.
5128 // Determine whether we have a single, best method. If so, we can
5129 // code-complete the expression using the corresponding parameter type as
5130 // our preferred type, improving completion results.
5131 if (AtArgumentExpression) {
5132 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5133 NumSelIdents);
5134 if (PreferredType.isNull())
5135 CodeCompleteOrdinaryName(S, PCC_Expression);
5136 else
5137 CodeCompleteExpression(S, PreferredType);
5138 return;
5139 }
5140
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005141 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005142 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005143 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005144}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005145
Douglas Gregor68762e72010-08-23 21:17:50 +00005146void Sema::CodeCompleteObjCForCollection(Scope *S,
5147 DeclGroupPtrTy IterationVar) {
5148 CodeCompleteExpressionData Data;
5149 Data.ObjCCollection = true;
5150
5151 if (IterationVar.getAsOpaquePtr()) {
5152 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5153 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5154 if (*I)
5155 Data.IgnoreDecls.push_back(*I);
5156 }
5157 }
5158
5159 CodeCompleteExpression(S, Data);
5160}
5161
Douglas Gregor67c692c2010-08-26 15:07:07 +00005162void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5163 unsigned NumSelIdents) {
5164 // If we have an external source, load the entire class method
5165 // pool from the AST file.
5166 if (ExternalSource) {
5167 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5168 I != N; ++I) {
5169 Selector Sel = ExternalSource->GetExternalSelector(I);
5170 if (Sel.isNull() || MethodPool.count(Sel))
5171 continue;
5172
5173 ReadMethodPool(Sel);
5174 }
5175 }
5176
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005177 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5178 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005179 Results.EnterNewScope();
5180 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5181 MEnd = MethodPool.end();
5182 M != MEnd; ++M) {
5183
5184 Selector Sel = M->first;
5185 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5186 continue;
5187
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005188 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005189 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005190 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005191 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005192 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005193 continue;
5194 }
5195
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005196 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005197 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005198 if (I == NumSelIdents) {
5199 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005200 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005201 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005202 Accumulator.clear();
5203 }
5204 }
5205
Benjamin Kramer632500c2011-07-26 16:59:25 +00005206 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005207 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005208 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005209 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005210 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005211 }
5212 Results.ExitScope();
5213
5214 HandleCodeCompleteResults(this, CodeCompleter,
5215 CodeCompletionContext::CCC_SelectorName,
5216 Results.data(), Results.size());
5217}
5218
Douglas Gregorbaf69612009-11-18 04:19:12 +00005219/// \brief Add all of the protocol declarations that we find in the given
5220/// (translation unit) context.
5221static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005222 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005223 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005224 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005225
5226 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5227 DEnd = Ctx->decls_end();
5228 D != DEnd; ++D) {
5229 // Record any protocols we find.
5230 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005231 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005232 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005233
5234 // Record any forward-declared protocols we find.
5235 if (ObjCForwardProtocolDecl *Forward
5236 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5237 for (ObjCForwardProtocolDecl::protocol_iterator
5238 P = Forward->protocol_begin(),
5239 PEnd = Forward->protocol_end();
5240 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005241 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005242 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005243 }
5244 }
5245}
5246
5247void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5248 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005249 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5250 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005251
Douglas Gregora3b23b02010-12-09 21:44:02 +00005252 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5253 Results.EnterNewScope();
5254
5255 // Tell the result set to ignore all of the protocols we have
5256 // already seen.
5257 // FIXME: This doesn't work when caching code-completion results.
5258 for (unsigned I = 0; I != NumProtocols; ++I)
5259 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5260 Protocols[I].second))
5261 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005262
Douglas Gregora3b23b02010-12-09 21:44:02 +00005263 // Add all protocols.
5264 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5265 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005266
Douglas Gregora3b23b02010-12-09 21:44:02 +00005267 Results.ExitScope();
5268 }
5269
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005270 HandleCodeCompleteResults(this, CodeCompleter,
5271 CodeCompletionContext::CCC_ObjCProtocolName,
5272 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005273}
5274
5275void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005276 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5277 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005278
Douglas Gregora3b23b02010-12-09 21:44:02 +00005279 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5280 Results.EnterNewScope();
5281
5282 // Add all protocols.
5283 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5284 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005285
Douglas Gregora3b23b02010-12-09 21:44:02 +00005286 Results.ExitScope();
5287 }
5288
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005289 HandleCodeCompleteResults(this, CodeCompleter,
5290 CodeCompletionContext::CCC_ObjCProtocolName,
5291 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005292}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005293
5294/// \brief Add all of the Objective-C interface declarations that we find in
5295/// the given (translation unit) context.
5296static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5297 bool OnlyForwardDeclarations,
5298 bool OnlyUnimplemented,
5299 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005300 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005301
5302 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5303 DEnd = Ctx->decls_end();
5304 D != DEnd; ++D) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005305 // Record any interfaces we find.
5306 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5307 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5308 (!OnlyUnimplemented || !Class->getImplementation()))
5309 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005310
5311 // Record any forward-declared interfaces we find.
5312 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5313 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregor1c283312010-08-11 12:19:30 +00005314 C != CEnd; ++C)
5315 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5316 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5317 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005318 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005319 }
5320 }
5321}
5322
5323void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005324 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5325 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005326 Results.EnterNewScope();
5327
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005328 if (CodeCompleter->includeGlobals()) {
5329 // Add all classes.
5330 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5331 false, Results);
5332 }
5333
Douglas Gregor49c22a72009-11-18 16:26:39 +00005334 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005335
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005336 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005337 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005338 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005339}
5340
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005341void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5342 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005343 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005344 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005345 Results.EnterNewScope();
5346
5347 // Make sure that we ignore the class we're currently defining.
5348 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005349 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005350 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00005351 Results.Ignore(CurClass);
5352
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005353 if (CodeCompleter->includeGlobals()) {
5354 // Add all classes.
5355 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5356 false, Results);
5357 }
5358
Douglas Gregor49c22a72009-11-18 16:26:39 +00005359 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005360
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005361 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005362 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005363 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005364}
5365
5366void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005367 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5368 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005369 Results.EnterNewScope();
5370
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005371 if (CodeCompleter->includeGlobals()) {
5372 // Add all unimplemented classes.
5373 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5374 true, Results);
5375 }
5376
Douglas Gregor49c22a72009-11-18 16:26:39 +00005377 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005378
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005379 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005380 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005381 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005382}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005383
5384void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005385 IdentifierInfo *ClassName,
5386 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005387 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005388
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005389 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00005390 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005391
5392 // Ignore any categories we find that have already been implemented by this
5393 // interface.
5394 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5395 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005396 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005397 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5398 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5399 Category = Category->getNextClassCategory())
5400 CategoryNames.insert(Category->getIdentifier());
5401
5402 // Add all of the categories we know about.
5403 Results.EnterNewScope();
5404 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5405 for (DeclContext::decl_iterator D = TU->decls_begin(),
5406 DEnd = TU->decls_end();
5407 D != DEnd; ++D)
5408 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5409 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005410 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005411 Results.ExitScope();
5412
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005413 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005414 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005415 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005416}
5417
5418void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005419 IdentifierInfo *ClassName,
5420 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005421 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005422
5423 // Find the corresponding interface. If we couldn't find the interface, the
5424 // program itself is ill-formed. However, we'll try to be helpful still by
5425 // providing the list of all of the categories we know about.
5426 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005427 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005428 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5429 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005430 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005431
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005432 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00005433 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005434
5435 // Add all of the categories that have have corresponding interface
5436 // declarations in this class and any of its superclasses, except for
5437 // already-implemented categories in the class itself.
5438 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5439 Results.EnterNewScope();
5440 bool IgnoreImplemented = true;
5441 while (Class) {
5442 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5443 Category = Category->getNextClassCategory())
5444 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5445 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005446 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005447
5448 Class = Class->getSuperClass();
5449 IgnoreImplemented = false;
5450 }
5451 Results.ExitScope();
5452
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005453 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005454 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005455 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005456}
Douglas Gregor5d649882009-11-18 22:32:06 +00005457
John McCall48871652010-08-21 09:40:31 +00005458void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall276321a2010-08-25 06:19:51 +00005459 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005460 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5461 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00005462
5463 // Figure out where this @synthesize lives.
5464 ObjCContainerDecl *Container
John McCall48871652010-08-21 09:40:31 +00005465 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor5d649882009-11-18 22:32:06 +00005466 if (!Container ||
5467 (!isa<ObjCImplementationDecl>(Container) &&
5468 !isa<ObjCCategoryImplDecl>(Container)))
5469 return;
5470
5471 // Ignore any properties that have already been implemented.
5472 for (DeclContext::decl_iterator D = Container->decls_begin(),
5473 DEnd = Container->decls_end();
5474 D != DEnd; ++D)
5475 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5476 Results.Ignore(PropertyImpl->getPropertyDecl());
5477
5478 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00005479 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00005480 Results.EnterNewScope();
5481 if (ObjCImplementationDecl *ClassImpl
5482 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor95147142011-05-05 15:50:42 +00005483 AddObjCProperties(ClassImpl->getClassInterface(), false,
5484 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00005485 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00005486 else
5487 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00005488 false, /*AllowNullaryMethods=*/false, CurContext,
5489 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00005490 Results.ExitScope();
5491
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005492 HandleCodeCompleteResults(this, CodeCompleter,
5493 CodeCompletionContext::CCC_Other,
5494 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00005495}
5496
5497void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5498 IdentifierInfo *PropertyName,
John McCall48871652010-08-21 09:40:31 +00005499 Decl *ObjCImpDecl) {
John McCall276321a2010-08-25 06:19:51 +00005500 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005501 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5502 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00005503
5504 // Figure out where this @synthesize lives.
5505 ObjCContainerDecl *Container
John McCall48871652010-08-21 09:40:31 +00005506 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor5d649882009-11-18 22:32:06 +00005507 if (!Container ||
5508 (!isa<ObjCImplementationDecl>(Container) &&
5509 !isa<ObjCCategoryImplDecl>(Container)))
5510 return;
5511
5512 // Figure out which interface we're looking into.
5513 ObjCInterfaceDecl *Class = 0;
5514 if (ObjCImplementationDecl *ClassImpl
5515 = dyn_cast<ObjCImplementationDecl>(Container))
5516 Class = ClassImpl->getClassInterface();
5517 else
5518 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5519 ->getClassInterface();
5520
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005521 // Determine the type of the property we're synthesizing.
5522 QualType PropertyType = Context.getObjCIdType();
5523 if (Class) {
5524 if (ObjCPropertyDecl *Property
5525 = Class->FindPropertyDeclaration(PropertyName)) {
5526 PropertyType
5527 = Property->getType().getNonReferenceType().getUnqualifiedType();
5528
5529 // Give preference to ivars
5530 Results.setPreferredType(PropertyType);
5531 }
5532 }
5533
Douglas Gregor5d649882009-11-18 22:32:06 +00005534 // Add all of the instance variables in this class and its superclasses.
5535 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00005536 bool SawSimilarlyNamedIvar = false;
5537 std::string NameWithPrefix;
5538 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00005539 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00005540 std::string NameWithSuffix = PropertyName->getName().str();
5541 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00005542 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00005543 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5544 Ivar = Ivar->getNextIvar()) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005545 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5546
Douglas Gregor331faa02011-04-18 14:13:53 +00005547 // Determine whether we've seen an ivar with a name similar to the
5548 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005549 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00005550 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005551 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00005552 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005553
5554 // Reduce the priority of this result by one, to give it a slight
5555 // advantage over other results whose names don't match so closely.
5556 if (Results.size() &&
5557 Results.data()[Results.size() - 1].Kind
5558 == CodeCompletionResult::RK_Declaration &&
5559 Results.data()[Results.size() - 1].Declaration == Ivar)
5560 Results.data()[Results.size() - 1].Priority--;
5561 }
Douglas Gregor331faa02011-04-18 14:13:53 +00005562 }
Douglas Gregor5d649882009-11-18 22:32:06 +00005563 }
Douglas Gregor331faa02011-04-18 14:13:53 +00005564
5565 if (!SawSimilarlyNamedIvar) {
5566 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005567 // an ivar of the appropriate type.
5568 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00005569 typedef CodeCompletionResult Result;
5570 CodeCompletionAllocator &Allocator = Results.getAllocator();
5571 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5572
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005573 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5574 Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00005575 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5576 Results.AddResult(Result(Builder.TakeString(), Priority,
5577 CXCursor_ObjCIvarDecl));
5578 }
5579
Douglas Gregor5d649882009-11-18 22:32:06 +00005580 Results.ExitScope();
5581
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005582 HandleCodeCompleteResults(this, CodeCompleter,
5583 CodeCompletionContext::CCC_Other,
5584 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00005585}
Douglas Gregor636a61e2010-04-07 00:21:17 +00005586
Douglas Gregor416b5752010-08-25 01:08:01 +00005587// Mapping from selectors to the methods that implement that selector, along
5588// with the "in original class" flag.
5589typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5590 KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00005591
5592/// \brief Find all of the methods that reside in the given container
5593/// (and its superclasses, protocols, etc.) that meet the given
5594/// criteria. Insert those methods into the map of known methods,
5595/// indexed by selector so they can be easily found.
5596static void FindImplementableMethods(ASTContext &Context,
5597 ObjCContainerDecl *Container,
5598 bool WantInstanceMethods,
5599 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00005600 KnownMethodsMap &KnownMethods,
5601 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00005602 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5603 // Recurse into protocols.
5604 const ObjCList<ObjCProtocolDecl> &Protocols
5605 = IFace->getReferencedProtocols();
5606 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005607 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00005608 I != E; ++I)
5609 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005610 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005611
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005612 // Add methods from any class extensions and categories.
5613 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5614 Cat = Cat->getNextClassCategory())
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00005615 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5616 WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005617 KnownMethods, false);
5618
5619 // Visit the superclass.
5620 if (IFace->getSuperClass())
5621 FindImplementableMethods(Context, IFace->getSuperClass(),
5622 WantInstanceMethods, ReturnType,
5623 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005624 }
5625
5626 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5627 // Recurse into protocols.
5628 const ObjCList<ObjCProtocolDecl> &Protocols
5629 = Category->getReferencedProtocols();
5630 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005631 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00005632 I != E; ++I)
5633 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005634 KnownMethods, InOriginalClass);
5635
5636 // If this category is the original class, jump to the interface.
5637 if (InOriginalClass && Category->getClassInterface())
5638 FindImplementableMethods(Context, Category->getClassInterface(),
5639 WantInstanceMethods, ReturnType, KnownMethods,
5640 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005641 }
5642
5643 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5644 // Recurse into protocols.
5645 const ObjCList<ObjCProtocolDecl> &Protocols
5646 = Protocol->getReferencedProtocols();
5647 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5648 E = Protocols.end();
5649 I != E; ++I)
5650 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005651 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005652 }
5653
5654 // Add methods in this container. This operation occurs last because
5655 // we want the methods from this container to override any methods
5656 // we've previously seen with the same selector.
5657 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5658 MEnd = Container->meth_end();
5659 M != MEnd; ++M) {
5660 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5661 if (!ReturnType.isNull() &&
5662 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5663 continue;
5664
Douglas Gregor416b5752010-08-25 01:08:01 +00005665 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005666 }
5667 }
5668}
5669
Douglas Gregor669a25a2011-02-17 00:22:45 +00005670/// \brief Add the parenthesized return or parameter type chunk to a code
5671/// completion string.
5672static void AddObjCPassingTypeChunk(QualType Type,
5673 ASTContext &Context,
5674 CodeCompletionBuilder &Builder) {
5675 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5676 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5677 Builder.getAllocator()));
5678 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5679}
5680
5681/// \brief Determine whether the given class is or inherits from a class by
5682/// the given name.
5683static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005684 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005685 if (!Class)
5686 return false;
5687
5688 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5689 return true;
5690
5691 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5692}
5693
5694/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5695/// Key-Value Observing (KVO).
5696static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5697 bool IsInstanceMethod,
5698 QualType ReturnType,
5699 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005700 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00005701 ResultBuilder &Results) {
5702 IdentifierInfo *PropName = Property->getIdentifier();
5703 if (!PropName || PropName->getLength() == 0)
5704 return;
5705
5706
5707 // Builder that will create each code completion.
5708 typedef CodeCompletionResult Result;
5709 CodeCompletionAllocator &Allocator = Results.getAllocator();
5710 CodeCompletionBuilder Builder(Allocator);
5711
5712 // The selector table.
5713 SelectorTable &Selectors = Context.Selectors;
5714
5715 // The property name, copied into the code completion allocation region
5716 // on demand.
5717 struct KeyHolder {
5718 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005719 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00005720 const char *CopiedKey;
5721
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005722 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor669a25a2011-02-17 00:22:45 +00005723 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5724
5725 operator const char *() {
5726 if (CopiedKey)
5727 return CopiedKey;
5728
5729 return CopiedKey = Allocator.CopyString(Key);
5730 }
5731 } Key(Allocator, PropName->getName());
5732
5733 // The uppercased name of the property name.
5734 std::string UpperKey = PropName->getName();
5735 if (!UpperKey.empty())
5736 UpperKey[0] = toupper(UpperKey[0]);
5737
5738 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5739 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5740 Property->getType());
5741 bool ReturnTypeMatchesVoid
5742 = ReturnType.isNull() || ReturnType->isVoidType();
5743
5744 // Add the normal accessor -(type)key.
5745 if (IsInstanceMethod &&
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005746 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00005747 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5748 if (ReturnType.isNull())
5749 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5750
5751 Builder.AddTypedTextChunk(Key);
5752 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5753 CXCursor_ObjCInstanceMethodDecl));
5754 }
5755
5756 // If we have an integral or boolean property (or the user has provided
5757 // an integral or boolean return type), add the accessor -(type)isKey.
5758 if (IsInstanceMethod &&
5759 ((!ReturnType.isNull() &&
5760 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5761 (ReturnType.isNull() &&
5762 (Property->getType()->isIntegerType() ||
5763 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005764 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005765 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005766 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005767 if (ReturnType.isNull()) {
5768 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5769 Builder.AddTextChunk("BOOL");
5770 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5771 }
5772
5773 Builder.AddTypedTextChunk(
5774 Allocator.CopyString(SelectorId->getName()));
5775 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5776 CXCursor_ObjCInstanceMethodDecl));
5777 }
5778 }
5779
5780 // Add the normal mutator.
5781 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5782 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005783 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005784 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005785 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005786 if (ReturnType.isNull()) {
5787 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5788 Builder.AddTextChunk("void");
5789 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5790 }
5791
5792 Builder.AddTypedTextChunk(
5793 Allocator.CopyString(SelectorId->getName()));
5794 Builder.AddTypedTextChunk(":");
5795 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5796 Builder.AddTextChunk(Key);
5797 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5798 CXCursor_ObjCInstanceMethodDecl));
5799 }
5800 }
5801
5802 // Indexed and unordered accessors
5803 unsigned IndexedGetterPriority = CCP_CodePattern;
5804 unsigned IndexedSetterPriority = CCP_CodePattern;
5805 unsigned UnorderedGetterPriority = CCP_CodePattern;
5806 unsigned UnorderedSetterPriority = CCP_CodePattern;
5807 if (const ObjCObjectPointerType *ObjCPointer
5808 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5809 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5810 // If this interface type is not provably derived from a known
5811 // collection, penalize the corresponding completions.
5812 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5813 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5814 if (!InheritsFromClassNamed(IFace, "NSArray"))
5815 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5816 }
5817
5818 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5819 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5820 if (!InheritsFromClassNamed(IFace, "NSSet"))
5821 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5822 }
5823 }
5824 } else {
5825 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5826 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5827 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5828 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5829 }
5830
5831 // Add -(NSUInteger)countOf<key>
5832 if (IsInstanceMethod &&
5833 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005834 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005835 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005836 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005837 if (ReturnType.isNull()) {
5838 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5839 Builder.AddTextChunk("NSUInteger");
5840 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5841 }
5842
5843 Builder.AddTypedTextChunk(
5844 Allocator.CopyString(SelectorId->getName()));
5845 Results.AddResult(Result(Builder.TakeString(),
5846 std::min(IndexedGetterPriority,
5847 UnorderedGetterPriority),
5848 CXCursor_ObjCInstanceMethodDecl));
5849 }
5850 }
5851
5852 // Indexed getters
5853 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5854 if (IsInstanceMethod &&
5855 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005856 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005857 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005858 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005859 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005860 if (ReturnType.isNull()) {
5861 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5862 Builder.AddTextChunk("id");
5863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5864 }
5865
5866 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5867 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5868 Builder.AddTextChunk("NSUInteger");
5869 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5870 Builder.AddTextChunk("index");
5871 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5872 CXCursor_ObjCInstanceMethodDecl));
5873 }
5874 }
5875
5876 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5877 if (IsInstanceMethod &&
5878 (ReturnType.isNull() ||
5879 (ReturnType->isObjCObjectPointerType() &&
5880 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5881 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5882 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005883 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005884 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005885 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005886 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005887 if (ReturnType.isNull()) {
5888 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5889 Builder.AddTextChunk("NSArray *");
5890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5891 }
5892
5893 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5894 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5895 Builder.AddTextChunk("NSIndexSet *");
5896 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5897 Builder.AddTextChunk("indexes");
5898 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5899 CXCursor_ObjCInstanceMethodDecl));
5900 }
5901 }
5902
5903 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5904 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005905 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00005906 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005907 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00005908 &Context.Idents.get("range")
5909 };
5910
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005911 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005912 if (ReturnType.isNull()) {
5913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5914 Builder.AddTextChunk("void");
5915 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5916 }
5917
5918 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5919 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5920 Builder.AddPlaceholderChunk("object-type");
5921 Builder.AddTextChunk(" **");
5922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5923 Builder.AddTextChunk("buffer");
5924 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5925 Builder.AddTypedTextChunk("range:");
5926 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5927 Builder.AddTextChunk("NSRange");
5928 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5929 Builder.AddTextChunk("inRange");
5930 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5931 CXCursor_ObjCInstanceMethodDecl));
5932 }
5933 }
5934
5935 // Mutable indexed accessors
5936
5937 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5938 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005939 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00005940 IdentifierInfo *SelectorIds[2] = {
5941 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005942 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00005943 };
5944
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005945 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-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("insertObject:");
5953 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5954 Builder.AddPlaceholderChunk("object-type");
5955 Builder.AddTextChunk(" *");
5956 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5957 Builder.AddTextChunk("object");
5958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5959 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5960 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5961 Builder.AddPlaceholderChunk("NSUInteger");
5962 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5963 Builder.AddTextChunk("index");
5964 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5965 CXCursor_ObjCInstanceMethodDecl));
5966 }
5967 }
5968
5969 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5970 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005971 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00005972 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005973 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00005974 &Context.Idents.get("atIndexes")
5975 };
5976
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005977 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005978 if (ReturnType.isNull()) {
5979 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5980 Builder.AddTextChunk("void");
5981 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5982 }
5983
5984 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5986 Builder.AddTextChunk("NSArray *");
5987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5988 Builder.AddTextChunk("array");
5989 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5990 Builder.AddTypedTextChunk("atIndexes:");
5991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5992 Builder.AddPlaceholderChunk("NSIndexSet *");
5993 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5994 Builder.AddTextChunk("indexes");
5995 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5996 CXCursor_ObjCInstanceMethodDecl));
5997 }
5998 }
5999
6000 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6001 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006002 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006003 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006004 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006005 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006006 if (ReturnType.isNull()) {
6007 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6008 Builder.AddTextChunk("void");
6009 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6010 }
6011
6012 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6013 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6014 Builder.AddTextChunk("NSUInteger");
6015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6016 Builder.AddTextChunk("index");
6017 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6018 CXCursor_ObjCInstanceMethodDecl));
6019 }
6020 }
6021
6022 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6023 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006024 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006025 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006026 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006027 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006028 if (ReturnType.isNull()) {
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddTextChunk("void");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 }
6033
6034 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6035 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6036 Builder.AddTextChunk("NSIndexSet *");
6037 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6038 Builder.AddTextChunk("indexes");
6039 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6040 CXCursor_ObjCInstanceMethodDecl));
6041 }
6042 }
6043
6044 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6045 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006046 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006047 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006048 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006049 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006050 &Context.Idents.get("withObject")
6051 };
6052
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006053 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006054 if (ReturnType.isNull()) {
6055 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6056 Builder.AddTextChunk("void");
6057 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6058 }
6059
6060 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6061 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6062 Builder.AddPlaceholderChunk("NSUInteger");
6063 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6064 Builder.AddTextChunk("index");
6065 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6066 Builder.AddTypedTextChunk("withObject:");
6067 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6068 Builder.AddTextChunk("id");
6069 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6070 Builder.AddTextChunk("object");
6071 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6072 CXCursor_ObjCInstanceMethodDecl));
6073 }
6074 }
6075
6076 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6077 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006078 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006079 = (Twine("replace") + UpperKey + "AtIndexes").str();
6080 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006081 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006082 &Context.Idents.get(SelectorName1),
6083 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006084 };
6085
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006086 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006087 if (ReturnType.isNull()) {
6088 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6089 Builder.AddTextChunk("void");
6090 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6091 }
6092
6093 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6094 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6095 Builder.AddPlaceholderChunk("NSIndexSet *");
6096 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6097 Builder.AddTextChunk("indexes");
6098 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6099 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6100 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6101 Builder.AddTextChunk("NSArray *");
6102 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6103 Builder.AddTextChunk("array");
6104 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6105 CXCursor_ObjCInstanceMethodDecl));
6106 }
6107 }
6108
6109 // Unordered getters
6110 // - (NSEnumerator *)enumeratorOfKey
6111 if (IsInstanceMethod &&
6112 (ReturnType.isNull() ||
6113 (ReturnType->isObjCObjectPointerType() &&
6114 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6115 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6116 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006117 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006118 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006119 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006120 if (ReturnType.isNull()) {
6121 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6122 Builder.AddTextChunk("NSEnumerator *");
6123 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6124 }
6125
6126 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6127 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6128 CXCursor_ObjCInstanceMethodDecl));
6129 }
6130 }
6131
6132 // - (type *)memberOfKey:(type *)object
6133 if (IsInstanceMethod &&
6134 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006135 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006136 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006137 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006138 if (ReturnType.isNull()) {
6139 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6140 Builder.AddPlaceholderChunk("object-type");
6141 Builder.AddTextChunk(" *");
6142 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6143 }
6144
6145 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6146 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6147 if (ReturnType.isNull()) {
6148 Builder.AddPlaceholderChunk("object-type");
6149 Builder.AddTextChunk(" *");
6150 } else {
6151 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6152 Builder.getAllocator()));
6153 }
6154 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6155 Builder.AddTextChunk("object");
6156 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6157 CXCursor_ObjCInstanceMethodDecl));
6158 }
6159 }
6160
6161 // Mutable unordered accessors
6162 // - (void)addKeyObject:(type *)object
6163 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006164 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006165 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006166 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006167 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006168 if (ReturnType.isNull()) {
6169 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6170 Builder.AddTextChunk("void");
6171 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6172 }
6173
6174 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6175 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6176 Builder.AddPlaceholderChunk("object-type");
6177 Builder.AddTextChunk(" *");
6178 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6179 Builder.AddTextChunk("object");
6180 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6181 CXCursor_ObjCInstanceMethodDecl));
6182 }
6183 }
6184
6185 // - (void)addKey:(NSSet *)objects
6186 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006187 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006188 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006189 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006190 if (ReturnType.isNull()) {
6191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6192 Builder.AddTextChunk("void");
6193 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6194 }
6195
6196 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6198 Builder.AddTextChunk("NSSet *");
6199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6200 Builder.AddTextChunk("objects");
6201 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6202 CXCursor_ObjCInstanceMethodDecl));
6203 }
6204 }
6205
6206 // - (void)removeKeyObject:(type *)object
6207 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006208 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006209 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006210 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006211 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006212 if (ReturnType.isNull()) {
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddTextChunk("void");
6215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6216 }
6217
6218 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddPlaceholderChunk("object-type");
6221 Builder.AddTextChunk(" *");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 Builder.AddTextChunk("object");
6224 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6225 CXCursor_ObjCInstanceMethodDecl));
6226 }
6227 }
6228
6229 // - (void)removeKey:(NSSet *)objects
6230 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006231 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006232 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006233 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006234 if (ReturnType.isNull()) {
6235 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6236 Builder.AddTextChunk("void");
6237 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6238 }
6239
6240 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6241 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6242 Builder.AddTextChunk("NSSet *");
6243 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6244 Builder.AddTextChunk("objects");
6245 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6246 CXCursor_ObjCInstanceMethodDecl));
6247 }
6248 }
6249
6250 // - (void)intersectKey:(NSSet *)objects
6251 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006252 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006253 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006254 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006255 if (ReturnType.isNull()) {
6256 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6257 Builder.AddTextChunk("void");
6258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6259 }
6260
6261 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6262 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6263 Builder.AddTextChunk("NSSet *");
6264 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6265 Builder.AddTextChunk("objects");
6266 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6267 CXCursor_ObjCInstanceMethodDecl));
6268 }
6269 }
6270
6271 // Key-Value Observing
6272 // + (NSSet *)keyPathsForValuesAffectingKey
6273 if (!IsInstanceMethod &&
6274 (ReturnType.isNull() ||
6275 (ReturnType->isObjCObjectPointerType() &&
6276 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6277 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6278 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006279 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006280 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006281 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006282 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006283 if (ReturnType.isNull()) {
6284 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6285 Builder.AddTextChunk("NSSet *");
6286 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6287 }
6288
6289 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6290 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006291 CXCursor_ObjCClassMethodDecl));
6292 }
6293 }
6294
6295 // + (BOOL)automaticallyNotifiesObserversForKey
6296 if (!IsInstanceMethod &&
6297 (ReturnType.isNull() ||
6298 ReturnType->isIntegerType() ||
6299 ReturnType->isBooleanType())) {
6300 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006301 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00006302 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6303 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6304 if (ReturnType.isNull()) {
6305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6306 Builder.AddTextChunk("BOOL");
6307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6308 }
6309
6310 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6311 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6312 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00006313 }
6314 }
6315}
6316
Douglas Gregor636a61e2010-04-07 00:21:17 +00006317void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6318 bool IsInstanceMethod,
John McCallba7bf592010-08-24 05:47:05 +00006319 ParsedType ReturnTy,
John McCall48871652010-08-21 09:40:31 +00006320 Decl *IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006321 // Determine the return type of the method we're declaring, if
6322 // provided.
6323 QualType ReturnType = GetTypeFromParser(ReturnTy);
6324
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006325 // Determine where we should start searching for methods.
6326 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006327 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00006328 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006329 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6330 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006331 IsInImplementation = true;
6332 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006333 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006334 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006335 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006336 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00006337 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006338 }
6339
6340 if (!SearchDecl && S) {
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006341 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006342 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006343 }
6344
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006345 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006346 HandleCodeCompleteResults(this, CodeCompleter,
6347 CodeCompletionContext::CCC_Other,
6348 0, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006349 return;
6350 }
6351
6352 // Find all of the methods that we could declare/implement here.
6353 KnownMethodsMap KnownMethods;
6354 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006355 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006356
Douglas Gregor636a61e2010-04-07 00:21:17 +00006357 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00006358 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006359 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6360 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006361 Results.EnterNewScope();
6362 PrintingPolicy Policy(Context.PrintingPolicy);
6363 Policy.AnonymousTagLocations = false;
John McCall31168b02011-06-15 23:02:42 +00006364 Policy.SuppressStrongLifetime = true;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006365 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6366 MEnd = KnownMethods.end();
6367 M != MEnd; ++M) {
Douglas Gregor416b5752010-08-25 01:08:01 +00006368 ObjCMethodDecl *Method = M->second.first;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006369 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006370
6371 // If the result type was not already provided, add it to the
6372 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00006373 if (ReturnType.isNull())
6374 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006375
6376 Selector Sel = Method->getSelector();
6377
6378 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006379 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006380 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006381
6382 // Add parameters to the pattern.
6383 unsigned I = 0;
6384 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6385 PEnd = Method->param_end();
6386 P != PEnd; (void)++P, ++I) {
6387 // Add the part of the selector name.
6388 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006389 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006390 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6392 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006393 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006394 } else
6395 break;
6396
6397 // Add the parameter type.
Douglas Gregor669a25a2011-02-17 00:22:45 +00006398 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006399
6400 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006401 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006402 }
6403
6404 if (Method->isVariadic()) {
6405 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006406 Builder.AddChunk(CodeCompletionString::CK_Comma);
6407 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00006408 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00006409
Douglas Gregord37c59d2010-05-28 00:57:46 +00006410 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006411 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6413 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6414 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006415 if (!Method->getResultType()->isVoidType()) {
6416 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006417 Builder.AddTextChunk("return");
6418 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6419 Builder.AddPlaceholderChunk("expression");
6420 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006421 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006422 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006423
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006424 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6425 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006426 }
6427
Douglas Gregor416b5752010-08-25 01:08:01 +00006428 unsigned Priority = CCP_CodePattern;
6429 if (!M->second.second)
6430 Priority += CCD_InBaseClass;
6431
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006432 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor7116a8c2010-08-17 16:06:07 +00006433 Method->isInstanceMethod()
6434 ? CXCursor_ObjCInstanceMethodDecl
6435 : CXCursor_ObjCClassMethodDecl));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006436 }
6437
Douglas Gregor669a25a2011-02-17 00:22:45 +00006438 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6439 // the properties in this class and its categories.
6440 if (Context.getLangOptions().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006441 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006442 Containers.push_back(SearchDecl);
6443
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006444 VisitedSelectorSet KnownSelectors;
6445 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6446 MEnd = KnownMethods.end();
6447 M != MEnd; ++M)
6448 KnownSelectors.insert(M->first);
6449
6450
Douglas Gregor669a25a2011-02-17 00:22:45 +00006451 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6452 if (!IFace)
6453 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6454 IFace = Category->getClassInterface();
6455
6456 if (IFace) {
6457 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6458 Category = Category->getNextClassCategory())
6459 Containers.push_back(Category);
6460 }
6461
6462 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6463 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6464 PEnd = Containers[I]->prop_end();
6465 P != PEnd; ++P) {
6466 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006467 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006468 }
6469 }
6470 }
6471
Douglas Gregor636a61e2010-04-07 00:21:17 +00006472 Results.ExitScope();
6473
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006474 HandleCodeCompleteResults(this, CodeCompleter,
6475 CodeCompletionContext::CCC_Other,
6476 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006477}
Douglas Gregor95887f92010-07-08 23:20:03 +00006478
6479void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6480 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00006481 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00006482 ParsedType ReturnTy,
Douglas Gregor95887f92010-07-08 23:20:03 +00006483 IdentifierInfo **SelIdents,
6484 unsigned NumSelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00006485 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006486 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00006487 if (ExternalSource) {
6488 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6489 I != N; ++I) {
6490 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006491 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00006492 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00006493
6494 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00006495 }
6496 }
6497
6498 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00006499 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006500 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6501 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00006502
6503 if (ReturnTy)
6504 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00006505
Douglas Gregor95887f92010-07-08 23:20:03 +00006506 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00006507 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6508 MEnd = MethodPool.end();
6509 M != MEnd; ++M) {
6510 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6511 &M->second.second;
6512 MethList && MethList->Method;
Douglas Gregor95887f92010-07-08 23:20:03 +00006513 MethList = MethList->Next) {
6514 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6515 NumSelIdents))
6516 continue;
6517
Douglas Gregor45879692010-07-08 23:37:41 +00006518 if (AtParameterName) {
6519 // Suggest parameter names we've seen before.
6520 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6521 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6522 if (Param->getIdentifier()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006523 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006524 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006525 Param->getIdentifier()->getName()));
6526 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00006527 }
6528 }
6529
6530 continue;
6531 }
6532
Douglas Gregor95887f92010-07-08 23:20:03 +00006533 Result R(MethList->Method, 0);
6534 R.StartParameter = NumSelIdents;
6535 R.AllParametersAreInformative = false;
6536 R.DeclaringEntity = true;
6537 Results.MaybeAddResult(R, CurContext);
6538 }
6539 }
6540
6541 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006542 HandleCodeCompleteResults(this, CodeCompleter,
6543 CodeCompletionContext::CCC_Other,
6544 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00006545}
Douglas Gregorb14904c2010-08-13 22:48:40 +00006546
Douglas Gregorec00a262010-08-24 22:20:20 +00006547void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006548 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006549 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006550 Results.EnterNewScope();
6551
6552 // #if <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006553 CodeCompletionBuilder Builder(Results.getAllocator());
6554 Builder.AddTypedTextChunk("if");
6555 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6556 Builder.AddPlaceholderChunk("condition");
6557 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006558
6559 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006560 Builder.AddTypedTextChunk("ifdef");
6561 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6562 Builder.AddPlaceholderChunk("macro");
6563 Results.AddResult(Builder.TakeString());
6564
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006565 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006566 Builder.AddTypedTextChunk("ifndef");
6567 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6568 Builder.AddPlaceholderChunk("macro");
6569 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006570
6571 if (InConditional) {
6572 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006573 Builder.AddTypedTextChunk("elif");
6574 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6575 Builder.AddPlaceholderChunk("condition");
6576 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006577
6578 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006579 Builder.AddTypedTextChunk("else");
6580 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006581
6582 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006583 Builder.AddTypedTextChunk("endif");
6584 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006585 }
6586
6587 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006588 Builder.AddTypedTextChunk("include");
6589 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6590 Builder.AddTextChunk("\"");
6591 Builder.AddPlaceholderChunk("header");
6592 Builder.AddTextChunk("\"");
6593 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006594
6595 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006596 Builder.AddTypedTextChunk("include");
6597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6598 Builder.AddTextChunk("<");
6599 Builder.AddPlaceholderChunk("header");
6600 Builder.AddTextChunk(">");
6601 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006602
6603 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006604 Builder.AddTypedTextChunk("define");
6605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6606 Builder.AddPlaceholderChunk("macro");
6607 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006608
6609 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006610 Builder.AddTypedTextChunk("define");
6611 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6612 Builder.AddPlaceholderChunk("macro");
6613 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6614 Builder.AddPlaceholderChunk("args");
6615 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6616 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006617
6618 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006619 Builder.AddTypedTextChunk("undef");
6620 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6621 Builder.AddPlaceholderChunk("macro");
6622 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006623
6624 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006625 Builder.AddTypedTextChunk("line");
6626 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6627 Builder.AddPlaceholderChunk("number");
6628 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006629
6630 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006631 Builder.AddTypedTextChunk("line");
6632 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6633 Builder.AddPlaceholderChunk("number");
6634 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6635 Builder.AddTextChunk("\"");
6636 Builder.AddPlaceholderChunk("filename");
6637 Builder.AddTextChunk("\"");
6638 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006639
6640 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006641 Builder.AddTypedTextChunk("error");
6642 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6643 Builder.AddPlaceholderChunk("message");
6644 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006645
6646 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006647 Builder.AddTypedTextChunk("pragma");
6648 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6649 Builder.AddPlaceholderChunk("arguments");
6650 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006651
6652 if (getLangOptions().ObjC1) {
6653 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006654 Builder.AddTypedTextChunk("import");
6655 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6656 Builder.AddTextChunk("\"");
6657 Builder.AddPlaceholderChunk("header");
6658 Builder.AddTextChunk("\"");
6659 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006660
6661 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006662 Builder.AddTypedTextChunk("import");
6663 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6664 Builder.AddTextChunk("<");
6665 Builder.AddPlaceholderChunk("header");
6666 Builder.AddTextChunk(">");
6667 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006668 }
6669
6670 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006671 Builder.AddTypedTextChunk("include_next");
6672 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6673 Builder.AddTextChunk("\"");
6674 Builder.AddPlaceholderChunk("header");
6675 Builder.AddTextChunk("\"");
6676 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006677
6678 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006679 Builder.AddTypedTextChunk("include_next");
6680 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6681 Builder.AddTextChunk("<");
6682 Builder.AddPlaceholderChunk("header");
6683 Builder.AddTextChunk(">");
6684 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006685
6686 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006687 Builder.AddTypedTextChunk("warning");
6688 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6689 Builder.AddPlaceholderChunk("message");
6690 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006691
6692 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6693 // completions for them. And __include_macros is a Clang-internal extension
6694 // that we don't want to encourage anyone to use.
6695
6696 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6697 Results.ExitScope();
6698
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006699 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00006700 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006701 Results.data(), Results.size());
6702}
6703
6704void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00006705 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00006706 S->getFnParent()? Sema::PCC_RecoveryInFunction
6707 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006708}
6709
Douglas Gregorec00a262010-08-24 22:20:20 +00006710void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006711 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006712 IsDefinition? CodeCompletionContext::CCC_MacroName
6713 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00006714 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6715 // Add just the names of macros, not their arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006716 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor12785102010-08-24 20:21:13 +00006717 Results.EnterNewScope();
6718 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6719 MEnd = PP.macro_end();
6720 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006721 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006722 M->first->getName()));
6723 Results.AddResult(Builder.TakeString());
Douglas Gregor12785102010-08-24 20:21:13 +00006724 }
6725 Results.ExitScope();
6726 } else if (IsDefinition) {
6727 // FIXME: Can we detect when the user just wrote an include guard above?
6728 }
6729
Douglas Gregor0ac41382010-09-23 23:01:17 +00006730 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00006731 Results.data(), Results.size());
6732}
6733
Douglas Gregorec00a262010-08-24 22:20:20 +00006734void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006735 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006736 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00006737
6738 if (!CodeCompleter || CodeCompleter->includeMacros())
6739 AddMacroResults(PP, Results);
6740
6741 // defined (<macro>)
6742 Results.EnterNewScope();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006743 CodeCompletionBuilder Builder(Results.getAllocator());
6744 Builder.AddTypedTextChunk("defined");
6745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6746 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6747 Builder.AddPlaceholderChunk("macro");
6748 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6749 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00006750 Results.ExitScope();
6751
6752 HandleCodeCompleteResults(this, CodeCompleter,
6753 CodeCompletionContext::CCC_PreprocessorExpression,
6754 Results.data(), Results.size());
6755}
6756
6757void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6758 IdentifierInfo *Macro,
6759 MacroInfo *MacroInfo,
6760 unsigned Argument) {
6761 // FIXME: In the future, we could provide "overload" results, much like we
6762 // do for function calls.
6763
6764 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00006765 S->getFnParent()? Sema::PCC_RecoveryInFunction
6766 : Sema::PCC_Namespace);
Douglas Gregorec00a262010-08-24 22:20:20 +00006767}
6768
Douglas Gregor11583702010-08-25 17:04:25 +00006769void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00006770 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00006771 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor11583702010-08-25 17:04:25 +00006772 0, 0);
6773}
6774
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006775void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006777 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00006778 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6779 CodeCompletionDeclConsumer Consumer(Builder,
6780 Context.getTranslationUnitDecl());
6781 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6782 Consumer);
6783 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00006784
6785 if (!CodeCompleter || CodeCompleter->includeMacros())
6786 AddMacroResults(PP, Builder);
6787
6788 Results.clear();
6789 Results.insert(Results.end(),
6790 Builder.data(), Builder.data() + Builder.size());
6791}