blob: e4c2bdd031c79406bfb33a505970e927d12a36c6 [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 }
David Blaikie8a40f702012-01-17 06:56:22 +0000599
Douglas Gregor95887f92010-07-08 23:20:03 +0000600 case Type::Complex:
601 return STC_Arithmetic;
602
603 case Type::Pointer:
604 return STC_Pointer;
605
606 case Type::BlockPointer:
607 return STC_Block;
608
609 case Type::LValueReference:
610 case Type::RValueReference:
611 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
612
613 case Type::ConstantArray:
614 case Type::IncompleteArray:
615 case Type::VariableArray:
616 case Type::DependentSizedArray:
617 return STC_Array;
618
619 case Type::DependentSizedExtVector:
620 case Type::Vector:
621 case Type::ExtVector:
622 return STC_Arithmetic;
623
624 case Type::FunctionProto:
625 case Type::FunctionNoProto:
626 return STC_Function;
627
628 case Type::Record:
629 return STC_Record;
630
631 case Type::Enum:
632 return STC_Arithmetic;
633
634 case Type::ObjCObject:
635 case Type::ObjCInterface:
636 case Type::ObjCObjectPointer:
637 return STC_ObjectiveC;
638
639 default:
640 return STC_Other;
641 }
642}
643
644/// \brief Get the type that a given expression will have if this declaration
645/// is used as an expression in its "typical" code-completion form.
Douglas Gregor6e240332010-08-16 16:18:59 +0000646QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000647 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
648
649 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
650 return C.getTypeDeclType(Type);
651 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
652 return C.getObjCInterfaceType(Iface);
653
654 QualType T;
655 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000656 T = Function->getCallResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000657 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000658 T = Method->getSendResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000659 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000660 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000661 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
662 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
663 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
664 T = Property->getType();
665 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
666 T = Value->getType();
667 else
668 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000669
670 // Dig through references, function pointers, and block pointers to
671 // get down to the likely type of an expression when the entity is
672 // used.
673 do {
674 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
675 T = Ref->getPointeeType();
676 continue;
677 }
678
679 if (const PointerType *Pointer = T->getAs<PointerType>()) {
680 if (Pointer->getPointeeType()->isFunctionType()) {
681 T = Pointer->getPointeeType();
682 continue;
683 }
684
685 break;
686 }
687
688 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
689 T = Block->getPointeeType();
690 continue;
691 }
692
693 if (const FunctionType *Function = T->getAs<FunctionType>()) {
694 T = Function->getResultType();
695 continue;
696 }
697
698 break;
699 } while (true);
700
701 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000702}
703
Douglas Gregor50832e02010-09-20 22:39:41 +0000704void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
705 // If this is an Objective-C method declaration whose selector matches our
706 // preferred selector, give it a priority boost.
707 if (!PreferredSelector.isNull())
708 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
709 if (PreferredSelector == Method->getSelector())
710 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000711
Douglas Gregor50832e02010-09-20 22:39:41 +0000712 // If we have a preferred type, adjust the priority for results with exactly-
713 // matching or nearly-matching types.
714 if (!PreferredType.isNull()) {
715 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
716 if (!T.isNull()) {
717 CanQualType TC = SemaRef.Context.getCanonicalType(T);
718 // Check for exactly-matching types (modulo qualifiers).
719 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
720 R.Priority /= CCF_ExactTypeMatch;
721 // Check for nearly-matching types, based on classification of each.
722 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000723 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000724 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
725 R.Priority /= CCF_SimilarTypeMatch;
726 }
727 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000728}
729
Douglas Gregor0212fd72010-09-21 16:06:22 +0000730void ResultBuilder::MaybeAddConstructorResults(Result R) {
731 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
732 !CompletionContext.wantConstructorResults())
733 return;
734
735 ASTContext &Context = SemaRef.Context;
736 NamedDecl *D = R.Declaration;
737 CXXRecordDecl *Record = 0;
738 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
739 Record = ClassTemplate->getTemplatedDecl();
740 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
741 // Skip specializations and partial specializations.
742 if (isa<ClassTemplateSpecializationDecl>(Record))
743 return;
744 } else {
745 // There are no constructors here.
746 return;
747 }
748
749 Record = Record->getDefinition();
750 if (!Record)
751 return;
752
753
754 QualType RecordTy = Context.getTypeDeclType(Record);
755 DeclarationName ConstructorName
756 = Context.DeclarationNames.getCXXConstructorName(
757 Context.getCanonicalType(RecordTy));
758 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
759 Ctors.first != Ctors.second; ++Ctors.first) {
760 R.Declaration = *Ctors.first;
761 R.CursorKind = getCursorKindForDecl(R.Declaration);
762 Results.push_back(R);
763 }
764}
765
Douglas Gregor7c208612010-01-14 00:20:49 +0000766void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
767 assert(!ShadowMaps.empty() && "Must enter into a results scope");
768
769 if (R.Kind != Result::RK_Declaration) {
770 // For non-declaration results, just add the result.
771 Results.push_back(R);
772 return;
773 }
774
775 // Look through using declarations.
776 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
777 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
778 return;
779 }
780
781 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
782 unsigned IDNS = CanonDecl->getIdentifierNamespace();
783
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000784 bool AsNestedNameSpecifier = false;
785 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000786 return;
787
Douglas Gregor0212fd72010-09-21 16:06:22 +0000788 // C++ constructors are never found by name lookup.
789 if (isa<CXXConstructorDecl>(R.Declaration))
790 return;
791
Douglas Gregor3545ff42009-09-21 16:56:56 +0000792 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000793 ShadowMapEntry::iterator I, IEnd;
794 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
795 if (NamePos != SMap.end()) {
796 I = NamePos->second.begin();
797 IEnd = NamePos->second.end();
798 }
799
800 for (; I != IEnd; ++I) {
801 NamedDecl *ND = I->first;
802 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000803 if (ND->getCanonicalDecl() == CanonDecl) {
804 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000805 Results[Index].Declaration = R.Declaration;
806
Douglas Gregor3545ff42009-09-21 16:56:56 +0000807 // We're done.
808 return;
809 }
810 }
811
812 // This is a new declaration in this scope. However, check whether this
813 // declaration name is hidden by a similarly-named declaration in an outer
814 // scope.
815 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
816 --SMEnd;
817 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000818 ShadowMapEntry::iterator I, IEnd;
819 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
820 if (NamePos != SM->end()) {
821 I = NamePos->second.begin();
822 IEnd = NamePos->second.end();
823 }
824 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000825 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000826 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor3545ff42009-09-21 16:56:56 +0000827 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
828 Decl::IDNS_ObjCProtocol)))
829 continue;
830
831 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000832 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000833 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000834 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000835 continue;
836
837 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000838 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000839 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000840
841 break;
842 }
843 }
844
845 // Make sure that any given declaration only shows up in the result set once.
846 if (!AllDeclsFound.insert(CanonDecl))
847 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000848
Douglas Gregore412a5a2009-09-23 22:26:46 +0000849 // If the filter is for nested-name-specifiers, then this result starts a
850 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000851 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000852 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000853 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000854 } else
855 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000856
Douglas Gregor5bf52692009-09-22 23:15:58 +0000857 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000858 if (R.QualifierIsInformative && !R.Qualifier &&
859 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000860 DeclContext *Ctx = R.Declaration->getDeclContext();
861 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
862 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
863 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
864 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
865 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
866 else
867 R.QualifierIsInformative = false;
868 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000869
Douglas Gregor3545ff42009-09-21 16:56:56 +0000870 // Insert this result into the set of results and into the current shadow
871 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000872 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000873 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000874
875 if (!AsNestedNameSpecifier)
876 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000877}
878
Douglas Gregorc580c522010-01-14 01:09:38 +0000879void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000880 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000881 if (R.Kind != Result::RK_Declaration) {
882 // For non-declaration results, just add the result.
883 Results.push_back(R);
884 return;
885 }
886
Douglas Gregorc580c522010-01-14 01:09:38 +0000887 // Look through using declarations.
888 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
889 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
890 return;
891 }
892
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000893 bool AsNestedNameSpecifier = false;
894 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000895 return;
896
Douglas Gregor0212fd72010-09-21 16:06:22 +0000897 // C++ constructors are never found by name lookup.
898 if (isa<CXXConstructorDecl>(R.Declaration))
899 return;
900
Douglas Gregorc580c522010-01-14 01:09:38 +0000901 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
902 return;
903
904 // Make sure that any given declaration only shows up in the result set once.
905 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
906 return;
907
908 // If the filter is for nested-name-specifiers, then this result starts a
909 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000910 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000911 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000912 R.Priority = CCP_NestedNameSpecifier;
913 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000914 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
915 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000916 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000917 R.QualifierIsInformative = true;
918
Douglas Gregorc580c522010-01-14 01:09:38 +0000919 // If this result is supposed to have an informative qualifier, add one.
920 if (R.QualifierIsInformative && !R.Qualifier &&
921 !R.StartsNestedNameSpecifier) {
922 DeclContext *Ctx = R.Declaration->getDeclContext();
923 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
924 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
925 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
926 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000927 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000928 else
929 R.QualifierIsInformative = false;
930 }
931
Douglas Gregora2db7932010-05-26 22:00:08 +0000932 // Adjust the priority if this result comes from a base class.
933 if (InBaseClass)
934 R.Priority += CCD_InBaseClass;
935
Douglas Gregor50832e02010-09-20 22:39:41 +0000936 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000937
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000938 if (HasObjectTypeQualifiers)
939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
940 if (Method->isInstance()) {
941 Qualifiers MethodQuals
942 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
943 if (ObjectTypeQualifiers == MethodQuals)
944 R.Priority += CCD_ObjectQualifierMatch;
945 else if (ObjectTypeQualifiers - MethodQuals) {
946 // The method cannot be invoked, because doing so would drop
947 // qualifiers.
948 return;
949 }
950 }
951
Douglas Gregorc580c522010-01-14 01:09:38 +0000952 // Insert this result into the set of results.
953 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000954
955 if (!AsNestedNameSpecifier)
956 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +0000957}
958
Douglas Gregor78a21012010-01-14 16:01:26 +0000959void ResultBuilder::AddResult(Result R) {
960 assert(R.Kind != Result::RK_Declaration &&
961 "Declaration results need more context");
962 Results.push_back(R);
963}
964
Douglas Gregor3545ff42009-09-21 16:56:56 +0000965/// \brief Enter into a new scope.
966void ResultBuilder::EnterNewScope() {
967 ShadowMaps.push_back(ShadowMap());
968}
969
970/// \brief Exit from the current scope.
971void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000972 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
973 EEnd = ShadowMaps.back().end();
974 E != EEnd;
975 ++E)
976 E->second.Destroy();
977
Douglas Gregor3545ff42009-09-21 16:56:56 +0000978 ShadowMaps.pop_back();
979}
980
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000981/// \brief Determines whether this given declaration will be found by
982/// ordinary name lookup.
983bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +0000984 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
985
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000986 unsigned IDNS = Decl::IDNS_Ordinary;
987 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +0000988 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor05fcf842010-11-02 20:36:02 +0000989 else if (SemaRef.getLangOptions().ObjC1) {
990 if (isa<ObjCIvarDecl>(ND))
991 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +0000992 }
993
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000994 return ND->getIdentifierNamespace() & IDNS;
995}
996
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000997/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +0000998/// ordinary name lookup but is not a type name.
999bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1000 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1001 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1002 return false;
1003
1004 unsigned IDNS = Decl::IDNS_Ordinary;
1005 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001006 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001007 else if (SemaRef.getLangOptions().ObjC1) {
1008 if (isa<ObjCIvarDecl>(ND))
1009 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001010 }
1011
Douglas Gregor70febae2010-05-28 00:49:12 +00001012 return ND->getIdentifierNamespace() & IDNS;
1013}
1014
Douglas Gregor85b50632010-07-28 21:50:18 +00001015bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1016 if (!IsOrdinaryNonTypeName(ND))
1017 return 0;
1018
1019 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1020 if (VD->getType()->isIntegralOrEnumerationType())
1021 return true;
1022
1023 return false;
1024}
1025
Douglas Gregor70febae2010-05-28 00:49:12 +00001026/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001027/// ordinary name lookup.
1028bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001029 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1030
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001031 unsigned IDNS = Decl::IDNS_Ordinary;
1032 if (SemaRef.getLangOptions().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001033 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001034
1035 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001036 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1037 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001038}
1039
Douglas Gregor3545ff42009-09-21 16:56:56 +00001040/// \brief Determines whether the given declaration is suitable as the
1041/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1042bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1043 // Allow us to find class templates, too.
1044 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1045 ND = ClassTemplate->getTemplatedDecl();
1046
1047 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1048}
1049
1050/// \brief Determines whether the given declaration is an enumeration.
1051bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1052 return isa<EnumDecl>(ND);
1053}
1054
1055/// \brief Determines whether the given declaration is a class or struct.
1056bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1057 // Allow us to find class templates, too.
1058 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1059 ND = ClassTemplate->getTemplatedDecl();
1060
1061 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001062 return RD->getTagKind() == TTK_Class ||
1063 RD->getTagKind() == TTK_Struct;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001064
1065 return false;
1066}
1067
1068/// \brief Determines whether the given declaration is a union.
1069bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1070 // Allow us to find class templates, too.
1071 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1072 ND = ClassTemplate->getTemplatedDecl();
1073
1074 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001075 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001076
1077 return false;
1078}
1079
1080/// \brief Determines whether the given declaration is a namespace.
1081bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1082 return isa<NamespaceDecl>(ND);
1083}
1084
1085/// \brief Determines whether the given declaration is a namespace or
1086/// namespace alias.
1087bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1088 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1089}
1090
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001091/// \brief Determines whether the given declaration is a type.
Douglas Gregor3545ff42009-09-21 16:56:56 +00001092bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregor99fa2642010-08-24 01:06:58 +00001093 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1094 ND = Using->getTargetDecl();
1095
1096 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001097}
1098
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001099/// \brief Determines which members of a class should be visible via
1100/// "." or "->". Only value declarations, nested name specifiers, and
1101/// using declarations thereof should show up.
Douglas Gregore412a5a2009-09-23 22:26:46 +00001102bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001103 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1104 ND = Using->getTargetDecl();
1105
Douglas Gregor70788392009-12-11 18:14:22 +00001106 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1107 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001108}
1109
Douglas Gregora817a192010-05-27 23:06:34 +00001110static bool isObjCReceiverType(ASTContext &C, QualType T) {
1111 T = C.getCanonicalType(T);
1112 switch (T->getTypeClass()) {
1113 case Type::ObjCObject:
1114 case Type::ObjCInterface:
1115 case Type::ObjCObjectPointer:
1116 return true;
1117
1118 case Type::Builtin:
1119 switch (cast<BuiltinType>(T)->getKind()) {
1120 case BuiltinType::ObjCId:
1121 case BuiltinType::ObjCClass:
1122 case BuiltinType::ObjCSel:
1123 return true;
1124
1125 default:
1126 break;
1127 }
1128 return false;
1129
1130 default:
1131 break;
1132 }
1133
1134 if (!C.getLangOptions().CPlusPlus)
1135 return false;
1136
1137 // FIXME: We could perform more analysis here to determine whether a
1138 // particular class type has any conversions to Objective-C types. For now,
1139 // just accept all class types.
1140 return T->isDependentType() || T->isRecordType();
1141}
1142
1143bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1144 QualType T = getDeclUsageType(SemaRef.Context, ND);
1145 if (T.isNull())
1146 return false;
1147
1148 T = SemaRef.Context.getBaseElementType(T);
1149 return isObjCReceiverType(SemaRef.Context, T);
1150}
1151
Douglas Gregor68762e72010-08-23 21:17:50 +00001152bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1153 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1154 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1155 return false;
1156
1157 QualType T = getDeclUsageType(SemaRef.Context, ND);
1158 if (T.isNull())
1159 return false;
1160
1161 T = SemaRef.Context.getBaseElementType(T);
1162 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1163 T->isObjCIdType() ||
1164 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1165}
Douglas Gregora817a192010-05-27 23:06:34 +00001166
Douglas Gregor0ac41382010-09-23 23:01:17 +00001167bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1168 return false;
1169}
1170
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001171/// \rief Determines whether the given declaration is an Objective-C
1172/// instance variable.
1173bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1174 return isa<ObjCIvarDecl>(ND);
1175}
1176
Douglas Gregorc580c522010-01-14 01:09:38 +00001177namespace {
1178 /// \brief Visible declaration consumer that adds a code-completion result
1179 /// for each visible declaration.
1180 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1181 ResultBuilder &Results;
1182 DeclContext *CurContext;
1183
1184 public:
1185 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1186 : Results(Results), CurContext(CurContext) { }
1187
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001188 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1189 bool InBaseClass) {
1190 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001191 if (Ctx)
1192 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1193
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001194 ResultBuilder::Result Result(ND, 0, false, Accessible);
1195 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001196 }
1197 };
1198}
1199
Douglas Gregor3545ff42009-09-21 16:56:56 +00001200/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001201static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001202 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001203 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001204 Results.AddResult(Result("short", CCP_Type));
1205 Results.AddResult(Result("long", CCP_Type));
1206 Results.AddResult(Result("signed", CCP_Type));
1207 Results.AddResult(Result("unsigned", CCP_Type));
1208 Results.AddResult(Result("void", CCP_Type));
1209 Results.AddResult(Result("char", CCP_Type));
1210 Results.AddResult(Result("int", CCP_Type));
1211 Results.AddResult(Result("float", CCP_Type));
1212 Results.AddResult(Result("double", CCP_Type));
1213 Results.AddResult(Result("enum", CCP_Type));
1214 Results.AddResult(Result("struct", CCP_Type));
1215 Results.AddResult(Result("union", CCP_Type));
1216 Results.AddResult(Result("const", CCP_Type));
1217 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001218
Douglas Gregor3545ff42009-09-21 16:56:56 +00001219 if (LangOpts.C99) {
1220 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001221 Results.AddResult(Result("_Complex", CCP_Type));
1222 Results.AddResult(Result("_Imaginary", CCP_Type));
1223 Results.AddResult(Result("_Bool", CCP_Type));
1224 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001225 }
1226
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001227 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001228 if (LangOpts.CPlusPlus) {
1229 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001230 Results.AddResult(Result("bool", CCP_Type +
1231 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001232 Results.AddResult(Result("class", CCP_Type));
1233 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001234
Douglas Gregorf4c33342010-05-28 00:22:41 +00001235 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001236 Builder.AddTypedTextChunk("typename");
1237 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1238 Builder.AddPlaceholderChunk("qualifier");
1239 Builder.AddTextChunk("::");
1240 Builder.AddPlaceholderChunk("name");
1241 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001242
Douglas Gregor3545ff42009-09-21 16:56:56 +00001243 if (LangOpts.CPlusPlus0x) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001244 Results.AddResult(Result("auto", CCP_Type));
1245 Results.AddResult(Result("char16_t", CCP_Type));
1246 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001247
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001248 Builder.AddTypedTextChunk("decltype");
1249 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1250 Builder.AddPlaceholderChunk("expression");
1251 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1252 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001253 }
1254 }
1255
1256 // GNU extensions
1257 if (LangOpts.GNUMode) {
1258 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001259 // Results.AddResult(Result("_Decimal32"));
1260 // Results.AddResult(Result("_Decimal64"));
1261 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001262
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001263 Builder.AddTypedTextChunk("typeof");
1264 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1265 Builder.AddPlaceholderChunk("expression");
1266 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001267
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001268 Builder.AddTypedTextChunk("typeof");
1269 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1270 Builder.AddPlaceholderChunk("type");
1271 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1272 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001273 }
1274}
1275
John McCallfaf5fb42010-08-26 23:41:50 +00001276static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001277 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001278 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001279 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001280 // Note: we don't suggest either "auto" or "register", because both
1281 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1282 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001283 Results.AddResult(Result("extern"));
1284 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001285}
1286
John McCallfaf5fb42010-08-26 23:41:50 +00001287static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001288 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001289 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001290 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001291 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001292 case Sema::PCC_Class:
1293 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001294 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001295 Results.AddResult(Result("explicit"));
1296 Results.AddResult(Result("friend"));
1297 Results.AddResult(Result("mutable"));
1298 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001299 }
1300 // Fall through
1301
John McCallfaf5fb42010-08-26 23:41:50 +00001302 case Sema::PCC_ObjCInterface:
1303 case Sema::PCC_ObjCImplementation:
1304 case Sema::PCC_Namespace:
1305 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001306 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001307 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001308 break;
1309
John McCallfaf5fb42010-08-26 23:41:50 +00001310 case Sema::PCC_ObjCInstanceVariableList:
1311 case Sema::PCC_Expression:
1312 case Sema::PCC_Statement:
1313 case Sema::PCC_ForInit:
1314 case Sema::PCC_Condition:
1315 case Sema::PCC_RecoveryInFunction:
1316 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001317 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001318 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001319 break;
1320 }
1321}
1322
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001323static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1324static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001326 ResultBuilder &Results,
1327 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001328static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001329 ResultBuilder &Results,
1330 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001331static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001332 ResultBuilder &Results,
1333 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001334static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001335
Douglas Gregorf4c33342010-05-28 00:22:41 +00001336static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001337 CodeCompletionBuilder Builder(Results.getAllocator());
1338 Builder.AddTypedTextChunk("typedef");
1339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1340 Builder.AddPlaceholderChunk("type");
1341 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1342 Builder.AddPlaceholderChunk("name");
1343 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001344}
1345
John McCallfaf5fb42010-08-26 23:41:50 +00001346static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001347 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001348 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001349 case Sema::PCC_Namespace:
1350 case Sema::PCC_Class:
1351 case Sema::PCC_ObjCInstanceVariableList:
1352 case Sema::PCC_Template:
1353 case Sema::PCC_MemberTemplate:
1354 case Sema::PCC_Statement:
1355 case Sema::PCC_RecoveryInFunction:
1356 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001357 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001358 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001359 return true;
1360
John McCallfaf5fb42010-08-26 23:41:50 +00001361 case Sema::PCC_Expression:
1362 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001363 return LangOpts.CPlusPlus;
1364
1365 case Sema::PCC_ObjCInterface:
1366 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001367 return false;
1368
John McCallfaf5fb42010-08-26 23:41:50 +00001369 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001370 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001371 }
David Blaikie8a40f702012-01-17 06:56:22 +00001372
1373 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001374}
1375
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001376static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1377 const Preprocessor &PP) {
1378 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001379 Policy.AnonymousTagLocations = false;
1380 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001381 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001382 return Policy;
1383}
1384
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001385/// \brief Retrieve a printing policy suitable for code completion.
1386static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1387 return getCompletionPrintingPolicy(S.Context, S.PP);
1388}
1389
Douglas Gregore5c79d52011-10-18 21:20:17 +00001390/// \brief Retrieve the string representation of the given type as a string
1391/// that has the appropriate lifetime for code completion.
1392///
1393/// This routine provides a fast path where we provide constant strings for
1394/// common type names.
1395static const char *GetCompletionTypeString(QualType T,
1396 ASTContext &Context,
1397 const PrintingPolicy &Policy,
1398 CodeCompletionAllocator &Allocator) {
1399 if (!T.getLocalQualifiers()) {
1400 // Built-in type names are constant strings.
1401 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1402 return BT->getName(Policy);
1403
1404 // Anonymous tag types are constant strings.
1405 if (const TagType *TagT = dyn_cast<TagType>(T))
1406 if (TagDecl *Tag = TagT->getDecl())
1407 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1408 switch (Tag->getTagKind()) {
1409 case TTK_Struct: return "struct <anonymous>";
1410 case TTK_Class: return "class <anonymous>";
1411 case TTK_Union: return "union <anonymous>";
1412 case TTK_Enum: return "enum <anonymous>";
1413 }
1414 }
1415 }
1416
1417 // Slow path: format the type as a string.
1418 std::string Result;
1419 T.getAsStringInternal(Result, Policy);
1420 return Allocator.CopyString(Result);
1421}
1422
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001423/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001424static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001425 Scope *S,
1426 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001427 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001428 CodeCompletionAllocator &Allocator = Results.getAllocator();
1429 CodeCompletionBuilder Builder(Allocator);
1430 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001431
John McCall276321a2010-08-25 06:19:51 +00001432 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001433 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001434 case Sema::PCC_Namespace:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001435 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001436 if (Results.includeCodePatterns()) {
1437 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001438 Builder.AddTypedTextChunk("namespace");
1439 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1440 Builder.AddPlaceholderChunk("identifier");
1441 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1442 Builder.AddPlaceholderChunk("declarations");
1443 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1444 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1445 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001446 }
1447
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001448 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001449 Builder.AddTypedTextChunk("namespace");
1450 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1451 Builder.AddPlaceholderChunk("name");
1452 Builder.AddChunk(CodeCompletionString::CK_Equal);
1453 Builder.AddPlaceholderChunk("namespace");
1454 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001455
1456 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001457 Builder.AddTypedTextChunk("using");
1458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1459 Builder.AddTextChunk("namespace");
1460 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1461 Builder.AddPlaceholderChunk("identifier");
1462 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001463
1464 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001465 Builder.AddTypedTextChunk("asm");
1466 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1467 Builder.AddPlaceholderChunk("string-literal");
1468 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1469 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001470
Douglas Gregorf4c33342010-05-28 00:22:41 +00001471 if (Results.includeCodePatterns()) {
1472 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001473 Builder.AddTypedTextChunk("template");
1474 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1475 Builder.AddPlaceholderChunk("declaration");
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001477 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001478 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001479
1480 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001481 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001482
Douglas Gregorf4c33342010-05-28 00:22:41 +00001483 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001484 // Fall through
1485
John McCallfaf5fb42010-08-26 23:41:50 +00001486 case Sema::PCC_Class:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001487 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001488 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001489 Builder.AddTypedTextChunk("using");
1490 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1491 Builder.AddPlaceholderChunk("qualifier");
1492 Builder.AddTextChunk("::");
1493 Builder.AddPlaceholderChunk("name");
1494 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001495
Douglas Gregorf4c33342010-05-28 00:22:41 +00001496 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001497 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001498 Builder.AddTypedTextChunk("using");
1499 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1500 Builder.AddTextChunk("typename");
1501 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1502 Builder.AddPlaceholderChunk("qualifier");
1503 Builder.AddTextChunk("::");
1504 Builder.AddPlaceholderChunk("name");
1505 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001506 }
1507
John McCallfaf5fb42010-08-26 23:41:50 +00001508 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001509 AddTypedefResult(Results);
1510
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001511 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001512 Builder.AddTypedTextChunk("public");
1513 Builder.AddChunk(CodeCompletionString::CK_Colon);
1514 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001515
1516 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001517 Builder.AddTypedTextChunk("protected");
1518 Builder.AddChunk(CodeCompletionString::CK_Colon);
1519 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001520
1521 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001522 Builder.AddTypedTextChunk("private");
1523 Builder.AddChunk(CodeCompletionString::CK_Colon);
1524 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001525 }
1526 }
1527 // Fall through
1528
John McCallfaf5fb42010-08-26 23:41:50 +00001529 case Sema::PCC_Template:
1530 case Sema::PCC_MemberTemplate:
Douglas Gregorf64acca2010-05-25 21:41:55 +00001531 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001532 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001533 Builder.AddTypedTextChunk("template");
1534 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1535 Builder.AddPlaceholderChunk("parameters");
1536 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1537 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001538 }
1539
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001540 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1541 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001542 break;
1543
John McCallfaf5fb42010-08-26 23:41:50 +00001544 case Sema::PCC_ObjCInterface:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001545 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1546 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1547 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001548 break;
1549
John McCallfaf5fb42010-08-26 23:41:50 +00001550 case Sema::PCC_ObjCImplementation:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001551 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1552 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1553 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001554 break;
1555
John McCallfaf5fb42010-08-26 23:41:50 +00001556 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001557 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001558 break;
1559
John McCallfaf5fb42010-08-26 23:41:50 +00001560 case Sema::PCC_RecoveryInFunction:
1561 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001562 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001563
Douglas Gregorc05f6572011-04-12 02:47:21 +00001564 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1565 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001566 Builder.AddTypedTextChunk("try");
1567 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1568 Builder.AddPlaceholderChunk("statements");
1569 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1570 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1571 Builder.AddTextChunk("catch");
1572 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1573 Builder.AddPlaceholderChunk("declaration");
1574 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1575 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1576 Builder.AddPlaceholderChunk("statements");
1577 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1578 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1579 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001580 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001581 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001582 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001583
Douglas Gregorf64acca2010-05-25 21:41:55 +00001584 if (Results.includeCodePatterns()) {
1585 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001586 Builder.AddTypedTextChunk("if");
1587 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001588 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001589 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001590 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001591 Builder.AddPlaceholderChunk("expression");
1592 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1593 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1594 Builder.AddPlaceholderChunk("statements");
1595 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1596 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1597 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001598
Douglas Gregorf64acca2010-05-25 21:41:55 +00001599 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001600 Builder.AddTypedTextChunk("switch");
1601 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001602 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001603 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001604 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001605 Builder.AddPlaceholderChunk("expression");
1606 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1607 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1608 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1609 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1610 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001611 }
1612
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001613 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001614 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001615 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001616 Builder.AddTypedTextChunk("case");
1617 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1618 Builder.AddPlaceholderChunk("expression");
1619 Builder.AddChunk(CodeCompletionString::CK_Colon);
1620 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001621
1622 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001623 Builder.AddTypedTextChunk("default");
1624 Builder.AddChunk(CodeCompletionString::CK_Colon);
1625 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626 }
1627
Douglas Gregorf64acca2010-05-25 21:41:55 +00001628 if (Results.includeCodePatterns()) {
1629 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001630 Builder.AddTypedTextChunk("while");
1631 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001632 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001633 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001634 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001635 Builder.AddPlaceholderChunk("expression");
1636 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1637 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1638 Builder.AddPlaceholderChunk("statements");
1639 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1640 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1641 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001642
1643 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001644 Builder.AddTypedTextChunk("do");
1645 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1646 Builder.AddPlaceholderChunk("statements");
1647 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1648 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1649 Builder.AddTextChunk("while");
1650 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1651 Builder.AddPlaceholderChunk("expression");
1652 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1653 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001654
Douglas Gregorf64acca2010-05-25 21:41:55 +00001655 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001656 Builder.AddTypedTextChunk("for");
1657 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf64acca2010-05-25 21:41:55 +00001658 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001659 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001660 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001661 Builder.AddPlaceholderChunk("init-expression");
1662 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1663 Builder.AddPlaceholderChunk("condition");
1664 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1665 Builder.AddPlaceholderChunk("inc-expression");
1666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1667 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1668 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1669 Builder.AddPlaceholderChunk("statements");
1670 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1671 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1672 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001673 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674
1675 if (S->getContinueParent()) {
1676 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001677 Builder.AddTypedTextChunk("continue");
1678 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001679 }
1680
1681 if (S->getBreakParent()) {
1682 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddTypedTextChunk("break");
1684 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001685 }
1686
1687 // "return expression ;" or "return ;", depending on whether we
1688 // know the function is void or not.
1689 bool isVoid = false;
1690 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1691 isVoid = Function->getResultType()->isVoidType();
1692 else if (ObjCMethodDecl *Method
1693 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1694 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001695 else if (SemaRef.getCurBlock() &&
1696 !SemaRef.getCurBlock()->ReturnType.isNull())
1697 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001698 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001699 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1701 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001702 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001703 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001704
Douglas Gregorf4c33342010-05-28 00:22:41 +00001705 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001706 Builder.AddTypedTextChunk("goto");
1707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1708 Builder.AddPlaceholderChunk("label");
1709 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001710
Douglas Gregorf4c33342010-05-28 00:22:41 +00001711 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001712 Builder.AddTypedTextChunk("using");
1713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1714 Builder.AddTextChunk("namespace");
1715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1716 Builder.AddPlaceholderChunk("identifier");
1717 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001718 }
1719
1720 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001721 case Sema::PCC_ForInit:
1722 case Sema::PCC_Condition:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001723 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001724 // Fall through: conditions and statements can have expressions.
1725
Douglas Gregor5e35d592010-09-14 23:59:36 +00001726 case Sema::PCC_ParenthesizedExpression:
John McCall31168b02011-06-15 23:02:42 +00001727 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1728 CCC == Sema::PCC_ParenthesizedExpression) {
1729 // (__bridge <type>)<expression>
1730 Builder.AddTypedTextChunk("__bridge");
1731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1732 Builder.AddPlaceholderChunk("type");
1733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1734 Builder.AddPlaceholderChunk("expression");
1735 Results.AddResult(Result(Builder.TakeString()));
1736
1737 // (__bridge_transfer <Objective-C type>)<expression>
1738 Builder.AddTypedTextChunk("__bridge_transfer");
1739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1740 Builder.AddPlaceholderChunk("Objective-C type");
1741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1742 Builder.AddPlaceholderChunk("expression");
1743 Results.AddResult(Result(Builder.TakeString()));
1744
1745 // (__bridge_retained <CF type>)<expression>
1746 Builder.AddTypedTextChunk("__bridge_retained");
1747 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1748 Builder.AddPlaceholderChunk("CF type");
1749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1750 Builder.AddPlaceholderChunk("expression");
1751 Results.AddResult(Result(Builder.TakeString()));
1752 }
1753 // Fall through
1754
John McCallfaf5fb42010-08-26 23:41:50 +00001755 case Sema::PCC_Expression: {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001756 if (SemaRef.getLangOptions().CPlusPlus) {
1757 // 'this', if we're in a non-static member function.
Eli Friedman73a04092012-01-07 04:59:52 +00001758 QualType ThisTy = SemaRef.getCurrentThisType();
Douglas Gregore5c79d52011-10-18 21:20:17 +00001759 if (!ThisTy.isNull()) {
1760 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1761 SemaRef.Context,
1762 Policy,
1763 Allocator));
1764 Builder.AddTypedTextChunk("this");
1765 Results.AddResult(Result(Builder.TakeString()));
1766 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001767
Douglas Gregore5c79d52011-10-18 21:20:17 +00001768 // true
1769 Builder.AddResultTypeChunk("bool");
1770 Builder.AddTypedTextChunk("true");
1771 Results.AddResult(Result(Builder.TakeString()));
1772
1773 // false
1774 Builder.AddResultTypeChunk("bool");
1775 Builder.AddTypedTextChunk("false");
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001777
Douglas Gregorc05f6572011-04-12 02:47:21 +00001778 if (SemaRef.getLangOptions().RTTI) {
1779 // dynamic_cast < type-id > ( expression )
1780 Builder.AddTypedTextChunk("dynamic_cast");
1781 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1782 Builder.AddPlaceholderChunk("type");
1783 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1784 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1785 Builder.AddPlaceholderChunk("expression");
1786 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1787 Results.AddResult(Result(Builder.TakeString()));
1788 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001789
1790 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("static_cast");
1792 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1793 Builder.AddPlaceholderChunk("type");
1794 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1796 Builder.AddPlaceholderChunk("expression");
1797 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1798 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001799
Douglas Gregorf4c33342010-05-28 00:22:41 +00001800 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001801 Builder.AddTypedTextChunk("reinterpret_cast");
1802 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1803 Builder.AddPlaceholderChunk("type");
1804 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1805 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1806 Builder.AddPlaceholderChunk("expression");
1807 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1808 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001809
Douglas Gregorf4c33342010-05-28 00:22:41 +00001810 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001811 Builder.AddTypedTextChunk("const_cast");
1812 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1813 Builder.AddPlaceholderChunk("type");
1814 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1815 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1816 Builder.AddPlaceholderChunk("expression");
1817 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1818 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001819
Douglas Gregorc05f6572011-04-12 02:47:21 +00001820 if (SemaRef.getLangOptions().RTTI) {
1821 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001822 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001823 Builder.AddTypedTextChunk("typeid");
1824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1825 Builder.AddPlaceholderChunk("expression-or-type");
1826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1827 Results.AddResult(Result(Builder.TakeString()));
1828 }
1829
Douglas Gregorf4c33342010-05-28 00:22:41 +00001830 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001831 Builder.AddTypedTextChunk("new");
1832 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1833 Builder.AddPlaceholderChunk("type");
1834 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1835 Builder.AddPlaceholderChunk("expressions");
1836 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1837 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001838
Douglas Gregorf4c33342010-05-28 00:22:41 +00001839 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001840 Builder.AddTypedTextChunk("new");
1841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1842 Builder.AddPlaceholderChunk("type");
1843 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1844 Builder.AddPlaceholderChunk("size");
1845 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1846 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1847 Builder.AddPlaceholderChunk("expressions");
1848 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1849 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001850
Douglas Gregorf4c33342010-05-28 00:22:41 +00001851 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001852 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001853 Builder.AddTypedTextChunk("delete");
1854 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1855 Builder.AddPlaceholderChunk("expression");
1856 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001857
Douglas Gregorf4c33342010-05-28 00:22:41 +00001858 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001859 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001860 Builder.AddTypedTextChunk("delete");
1861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1862 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1863 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1864 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1865 Builder.AddPlaceholderChunk("expression");
1866 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001867
Douglas Gregorc05f6572011-04-12 02:47:21 +00001868 if (SemaRef.getLangOptions().CXXExceptions) {
1869 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001870 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001871 Builder.AddTypedTextChunk("throw");
1872 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1873 Builder.AddPlaceholderChunk("expression");
1874 Results.AddResult(Result(Builder.TakeString()));
1875 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001876
Douglas Gregora2db7932010-05-26 22:00:08 +00001877 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001878
1879 if (SemaRef.getLangOptions().CPlusPlus0x) {
1880 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001881 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001882 Builder.AddTypedTextChunk("nullptr");
1883 Results.AddResult(Result(Builder.TakeString()));
1884
1885 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001886 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001887 Builder.AddTypedTextChunk("alignof");
1888 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1889 Builder.AddPlaceholderChunk("type");
1890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1891 Results.AddResult(Result(Builder.TakeString()));
1892
1893 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001894 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001895 Builder.AddTypedTextChunk("noexcept");
1896 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1897 Builder.AddPlaceholderChunk("expression");
1898 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1899 Results.AddResult(Result(Builder.TakeString()));
1900
1901 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001902 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001903 Builder.AddTypedTextChunk("sizeof...");
1904 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1905 Builder.AddPlaceholderChunk("parameter-pack");
1906 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1907 Results.AddResult(Result(Builder.TakeString()));
1908 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001909 }
1910
1911 if (SemaRef.getLangOptions().ObjC1) {
1912 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001913 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1914 // The interface can be NULL.
1915 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00001916 if (ID->getSuperClass()) {
1917 std::string SuperType;
1918 SuperType = ID->getSuperClass()->getNameAsString();
1919 if (Method->isInstanceMethod())
1920 SuperType += " *";
1921
1922 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1923 Builder.AddTypedTextChunk("super");
1924 Results.AddResult(Result(Builder.TakeString()));
1925 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00001926 }
1927
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001928 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001929 }
1930
Douglas Gregorf4c33342010-05-28 00:22:41 +00001931 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001932 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001933 Builder.AddTypedTextChunk("sizeof");
1934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935 Builder.AddPlaceholderChunk("expression-or-type");
1936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001938 break;
1939 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00001940
John McCallfaf5fb42010-08-26 23:41:50 +00001941 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00001942 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00001943 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001944 }
1945
Douglas Gregor70febae2010-05-28 00:49:12 +00001946 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1947 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001948
John McCallfaf5fb42010-08-26 23:41:50 +00001949 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00001950 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001951}
1952
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001953/// \brief If the given declaration has an associated type, add it as a result
1954/// type chunk.
1955static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00001956 const PrintingPolicy &Policy,
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001957 NamedDecl *ND,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001958 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001959 if (!ND)
1960 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00001961
1962 // Skip constructors and conversion functions, which have their return types
1963 // built into their names.
1964 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1965 return;
1966
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001967 // Determine the type of the declaration (if it has a type).
Douglas Gregor0212fd72010-09-21 16:06:22 +00001968 QualType T;
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001969 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1970 T = Function->getResultType();
1971 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1972 T = Method->getResultType();
1973 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1974 T = FunTmpl->getTemplatedDecl()->getResultType();
1975 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1976 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1977 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1978 /* Do nothing: ignore unresolved using declarations*/
John McCall31168b02011-06-15 23:02:42 +00001979 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001980 T = Value->getType();
John McCall31168b02011-06-15 23:02:42 +00001981 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001982 T = Property->getType();
1983
1984 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1985 return;
1986
Douglas Gregor75acd922011-09-27 23:30:47 +00001987 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00001988 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001989}
1990
Douglas Gregordbb71db2010-08-23 23:51:41 +00001991static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001992 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00001993 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1994 if (Sentinel->getSentinel() == 0) {
1995 if (Context.getLangOptions().ObjC1 &&
1996 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001997 Result.AddTextChunk(", nil");
Douglas Gregordbb71db2010-08-23 23:51:41 +00001998 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001999 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002000 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002001 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002002 }
2003}
2004
Douglas Gregor8f08d742011-07-30 07:55:26 +00002005static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2006 std::string Result;
2007 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002008 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002009 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002010 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002011 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002012 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002013 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002014 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002015 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002016 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002017 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002018 Result += "oneway ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002019 return Result;
2020}
2021
Douglas Gregore90dd002010-08-24 16:15:59 +00002022static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002023 const PrintingPolicy &Policy,
Douglas Gregor981a0c42010-08-29 19:47:46 +00002024 ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002025 bool SuppressName = false,
2026 bool SuppressBlock = false) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002027 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2028 if (Param->getType()->isDependentType() ||
2029 !Param->getType()->isBlockPointerType()) {
2030 // The argument for a dependent or non-block parameter is a placeholder
2031 // containing that parameter's type.
2032 std::string Result;
2033
Douglas Gregor981a0c42010-08-29 19:47:46 +00002034 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002035 Result = Param->getIdentifier()->getName();
2036
John McCall31168b02011-06-15 23:02:42 +00002037 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002038
2039 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002040 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2041 + Result + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002042 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002043 Result += Param->getIdentifier()->getName();
2044 }
2045 return Result;
2046 }
2047
2048 // The argument for a block pointer parameter is a block literal with
2049 // the appropriate type.
Douglas Gregor24bbc462011-02-15 22:37:09 +00002050 FunctionTypeLoc *Block = 0;
2051 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregore90dd002010-08-24 16:15:59 +00002052 TypeLoc TL;
2053 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2054 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2055 while (true) {
2056 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002057 if (!SuppressBlock) {
2058 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2059 if (TypeSourceInfo *InnerTSInfo
2060 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2061 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2062 continue;
2063 }
2064 }
2065
2066 // Look through qualified types
2067 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2068 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002069 continue;
2070 }
2071 }
2072
Douglas Gregore90dd002010-08-24 16:15:59 +00002073 // Try to get the function prototype behind the block pointer type,
2074 // then we're done.
2075 if (BlockPointerTypeLoc *BlockPtr
2076 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara6d810632010-12-14 22:11:44 +00002077 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor24bbc462011-02-15 22:37:09 +00002078 Block = dyn_cast<FunctionTypeLoc>(&TL);
2079 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregore90dd002010-08-24 16:15:59 +00002080 }
2081 break;
2082 }
2083 }
2084
2085 if (!Block) {
2086 // We were unable to find a FunctionProtoTypeLoc with parameter names
2087 // for the block; just use the parameter type as a placeholder.
2088 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002089 if (!ObjCMethodParam && Param->getIdentifier())
2090 Result = Param->getIdentifier()->getName();
2091
John McCall31168b02011-06-15 23:02:42 +00002092 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002093
2094 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002095 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2096 + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002097 if (Param->getIdentifier())
2098 Result += Param->getIdentifier()->getName();
2099 }
2100
2101 return Result;
2102 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002103
Douglas Gregore90dd002010-08-24 16:15:59 +00002104 // We have the function prototype behind the block pointer type, as it was
2105 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002106 std::string Result;
2107 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002108 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002109 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002110
2111 // Format the parameter list.
2112 std::string Params;
Douglas Gregor24bbc462011-02-15 22:37:09 +00002113 if (!BlockProto || Block->getNumArgs() == 0) {
2114 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002115 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002116 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002117 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002118 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002119 Params += "(";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002120 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2121 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002122 Params += ", ";
2123 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2124 /*SuppressName=*/false,
2125 /*SuppressBlock=*/true);
Douglas Gregor67da50e2010-09-08 22:47:51 +00002126
Douglas Gregor24bbc462011-02-15 22:37:09 +00002127 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002128 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002129 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002130 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002131 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002132
Douglas Gregord793e7c2011-10-18 04:23:19 +00002133 if (SuppressBlock) {
2134 // Format as a parameter.
2135 Result = Result + " (^";
2136 if (Param->getIdentifier())
2137 Result += Param->getIdentifier()->getName();
2138 Result += ")";
2139 Result += Params;
2140 } else {
2141 // Format as a block literal argument.
2142 Result = '^' + Result;
2143 Result += Params;
2144
2145 if (Param->getIdentifier())
2146 Result += Param->getIdentifier()->getName();
2147 }
2148
Douglas Gregore90dd002010-08-24 16:15:59 +00002149 return Result;
2150}
2151
Douglas Gregor3545ff42009-09-21 16:56:56 +00002152/// \brief Add function parameter chunks to the given code completion string.
2153static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002154 const PrintingPolicy &Policy,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002155 FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002156 CodeCompletionBuilder &Result,
2157 unsigned Start = 0,
2158 bool InOptional = false) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002159 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002160 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002161
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002162 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002163 ParmVarDecl *Param = Function->getParamDecl(P);
2164
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002165 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002166 // When we see an optional default argument, put that argument and
2167 // the remaining default arguments into a new, optional string.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002168 CodeCompletionBuilder Opt(Result.getAllocator());
2169 if (!FirstParameter)
2170 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor75acd922011-09-27 23:30:47 +00002171 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002172 Result.AddOptionalChunk(Opt.TakeString());
2173 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002174 }
2175
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002176 if (FirstParameter)
2177 FirstParameter = false;
2178 else
2179 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2180
2181 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002182
2183 // Format the placeholder string.
Douglas Gregor75acd922011-09-27 23:30:47 +00002184 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2185 Param);
Douglas Gregore90dd002010-08-24 16:15:59 +00002186
Douglas Gregor400f5972010-08-31 05:13:43 +00002187 if (Function->isVariadic() && P == N - 1)
2188 PlaceholderStr += ", ...";
2189
Douglas Gregor3545ff42009-09-21 16:56:56 +00002190 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002191 Result.AddPlaceholderChunk(
2192 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002193 }
Douglas Gregorba449032009-09-22 21:42:17 +00002194
2195 if (const FunctionProtoType *Proto
2196 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002197 if (Proto->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002198 if (Proto->getNumArgs() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002199 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002200
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002201 MaybeAddSentinel(Context, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002202 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002203}
2204
2205/// \brief Add template parameter chunks to the given code completion string.
2206static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002207 const PrintingPolicy &Policy,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002208 TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002209 CodeCompletionBuilder &Result,
2210 unsigned MaxParameters = 0,
2211 unsigned Start = 0,
2212 bool InDefaultArg = false) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002213 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002214 bool FirstParameter = true;
2215
2216 TemplateParameterList *Params = Template->getTemplateParameters();
2217 TemplateParameterList::iterator PEnd = Params->end();
2218 if (MaxParameters)
2219 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002220 for (TemplateParameterList::iterator P = Params->begin() + Start;
2221 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002222 bool HasDefaultArg = false;
2223 std::string PlaceholderStr;
2224 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2225 if (TTP->wasDeclaredWithTypename())
2226 PlaceholderStr = "typename";
2227 else
2228 PlaceholderStr = "class";
2229
2230 if (TTP->getIdentifier()) {
2231 PlaceholderStr += ' ';
2232 PlaceholderStr += TTP->getIdentifier()->getName();
2233 }
2234
2235 HasDefaultArg = TTP->hasDefaultArgument();
2236 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002237 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002238 if (NTTP->getIdentifier())
2239 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002240 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002241 HasDefaultArg = NTTP->hasDefaultArgument();
2242 } else {
2243 assert(isa<TemplateTemplateParmDecl>(*P));
2244 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2245
2246 // Since putting the template argument list into the placeholder would
2247 // be very, very long, we just use an abbreviation.
2248 PlaceholderStr = "template<...> class";
2249 if (TTP->getIdentifier()) {
2250 PlaceholderStr += ' ';
2251 PlaceholderStr += TTP->getIdentifier()->getName();
2252 }
2253
2254 HasDefaultArg = TTP->hasDefaultArgument();
2255 }
2256
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002257 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002258 // When we see an optional default argument, put that argument and
2259 // the remaining default arguments into a new, optional string.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002260 CodeCompletionBuilder Opt(Result.getAllocator());
2261 if (!FirstParameter)
2262 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor75acd922011-09-27 23:30:47 +00002263 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002264 P - Params->begin(), true);
2265 Result.AddOptionalChunk(Opt.TakeString());
2266 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002267 }
2268
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002269 InDefaultArg = false;
2270
Douglas Gregor3545ff42009-09-21 16:56:56 +00002271 if (FirstParameter)
2272 FirstParameter = false;
2273 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002274 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002275
2276 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002277 Result.AddPlaceholderChunk(
2278 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002279 }
2280}
2281
Douglas Gregorf2510672009-09-21 19:57:38 +00002282/// \brief Add a qualifier to the given code-completion string, if the
2283/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002284static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002285AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002286 NestedNameSpecifier *Qualifier,
2287 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002288 ASTContext &Context,
2289 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002290 if (!Qualifier)
2291 return;
2292
2293 std::string PrintedNNS;
2294 {
2295 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002296 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002297 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002298 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002299 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002300 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002301 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002302}
2303
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002304static void
2305AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2306 FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002307 const FunctionProtoType *Proto
2308 = Function->getType()->getAs<FunctionProtoType>();
2309 if (!Proto || !Proto->getTypeQuals())
2310 return;
2311
Douglas Gregor304f9b02011-02-01 21:15:40 +00002312 // FIXME: Add ref-qualifier!
2313
2314 // Handle single qualifiers without copying
2315 if (Proto->getTypeQuals() == Qualifiers::Const) {
2316 Result.AddInformativeChunk(" const");
2317 return;
2318 }
2319
2320 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2321 Result.AddInformativeChunk(" volatile");
2322 return;
2323 }
2324
2325 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2326 Result.AddInformativeChunk(" restrict");
2327 return;
2328 }
2329
2330 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002331 std::string QualsStr;
2332 if (Proto->getTypeQuals() & Qualifiers::Const)
2333 QualsStr += " const";
2334 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2335 QualsStr += " volatile";
2336 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2337 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002338 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002339}
2340
Douglas Gregor0212fd72010-09-21 16:06:22 +00002341/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002342static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2343 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002344 typedef CodeCompletionString::Chunk Chunk;
2345
2346 DeclarationName Name = ND->getDeclName();
2347 if (!Name)
2348 return;
2349
2350 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002351 case DeclarationName::CXXOperatorName: {
2352 const char *OperatorName = 0;
2353 switch (Name.getCXXOverloadedOperator()) {
2354 case OO_None:
2355 case OO_Conditional:
2356 case NUM_OVERLOADED_OPERATORS:
2357 OperatorName = "operator";
2358 break;
2359
2360#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2361 case OO_##Name: OperatorName = "operator" Spelling; break;
2362#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2363#include "clang/Basic/OperatorKinds.def"
2364
2365 case OO_New: OperatorName = "operator new"; break;
2366 case OO_Delete: OperatorName = "operator delete"; break;
2367 case OO_Array_New: OperatorName = "operator new[]"; break;
2368 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2369 case OO_Call: OperatorName = "operator()"; break;
2370 case OO_Subscript: OperatorName = "operator[]"; break;
2371 }
2372 Result.AddTypedTextChunk(OperatorName);
2373 break;
2374 }
2375
Douglas Gregor0212fd72010-09-21 16:06:22 +00002376 case DeclarationName::Identifier:
2377 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002378 case DeclarationName::CXXDestructorName:
2379 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002382 break;
2383
2384 case DeclarationName::CXXUsingDirective:
2385 case DeclarationName::ObjCZeroArgSelector:
2386 case DeclarationName::ObjCOneArgSelector:
2387 case DeclarationName::ObjCMultiArgSelector:
2388 break;
2389
2390 case DeclarationName::CXXConstructorName: {
2391 CXXRecordDecl *Record = 0;
2392 QualType Ty = Name.getCXXNameType();
2393 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2394 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2395 else if (const InjectedClassNameType *InjectedTy
2396 = Ty->getAs<InjectedClassNameType>())
2397 Record = InjectedTy->getDecl();
2398 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002399 Result.AddTypedTextChunk(
2400 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002401 break;
2402 }
2403
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002404 Result.AddTypedTextChunk(
2405 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002406 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002407 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor75acd922011-09-27 23:30:47 +00002408 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002409 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002410 }
2411 break;
2412 }
2413 }
2414}
2415
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002416CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2417 CodeCompletionAllocator &Allocator) {
2418 return CreateCodeCompletionString(S.Context, S.PP, Allocator);
2419}
2420
Douglas Gregor3545ff42009-09-21 16:56:56 +00002421/// \brief If possible, create a new code completion string for the given
2422/// result.
2423///
2424/// \returns Either a new, heap-allocated code completion string describing
2425/// how to use this result, or NULL to indicate that the string or name of the
2426/// result is all that is needed.
2427CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002428CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2429 Preprocessor &PP,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002430 CodeCompletionAllocator &Allocator) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002431 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002432 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002433
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002434 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002435 if (Kind == RK_Pattern) {
2436 Pattern->Priority = Priority;
2437 Pattern->Availability = Availability;
2438 return Pattern;
2439 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002440
Douglas Gregorf09935f2009-12-01 05:55:20 +00002441 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002442 Result.AddTypedTextChunk(Keyword);
2443 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002444 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002445
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002446 if (Kind == RK_Macro) {
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002447 MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002448 assert(MI && "Not a macro?");
2449
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002450 Result.AddTypedTextChunk(
2451 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002452
2453 if (!MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002454 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002455
2456 // Format a function-like macro with placeholders for the arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002457 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor0c505312011-07-30 08:17:44 +00002458 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002459
2460 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2461 if (MI->isC99Varargs()) {
2462 --AEnd;
2463
2464 if (A == AEnd) {
2465 Result.AddPlaceholderChunk("...");
2466 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002467 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002468
Douglas Gregor0c505312011-07-30 08:17:44 +00002469 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002470 if (A != MI->arg_begin())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002471 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002472
2473 if (MI->isVariadic() && (A+1) == AEnd) {
2474 llvm::SmallString<32> Arg = (*A)->getName();
2475 if (MI->isC99Varargs())
2476 Arg += ", ...";
2477 else
2478 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002479 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002480 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002481 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002482
2483 // Non-variadic macros are simple.
2484 Result.AddPlaceholderChunk(
2485 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002486 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002487 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2488 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002489 }
2490
Douglas Gregorf64acca2010-05-25 21:41:55 +00002491 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +00002492 NamedDecl *ND = Declaration;
2493
Douglas Gregor9eb77012009-11-07 00:00:49 +00002494 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002495 Result.AddTypedTextChunk(
2496 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002497 Result.AddTextChunk("::");
2498 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002499 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002500
2501 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2502 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2503 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2504 }
2505 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00002506
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002507 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002508
Douglas Gregor3545ff42009-09-21 16:56:56 +00002509 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002510 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002511 Ctx, Policy);
2512 AddTypedNameChunk(Ctx, Policy, ND, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002513 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002514 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002515 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00002516 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002517 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002518 }
2519
2520 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002521 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002522 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002523 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002524 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002525
Douglas Gregor3545ff42009-09-21 16:56:56 +00002526 // Figure out which template parameters are deduced (or have default
2527 // arguments).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002528 SmallVector<bool, 16> Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002529 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002530 unsigned LastDeducibleArgument;
2531 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2532 --LastDeducibleArgument) {
2533 if (!Deduced[LastDeducibleArgument - 1]) {
2534 // C++0x: Figure out if the template argument has a default. If so,
2535 // the user doesn't need to type this argument.
2536 // FIXME: We need to abstract template parameters better!
2537 bool HasDefaultArg = false;
2538 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002539 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002540 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2541 HasDefaultArg = TTP->hasDefaultArgument();
2542 else if (NonTypeTemplateParmDecl *NTTP
2543 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2544 HasDefaultArg = NTTP->hasDefaultArgument();
2545 else {
2546 assert(isa<TemplateTemplateParmDecl>(Param));
2547 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002548 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002549 }
2550
2551 if (!HasDefaultArg)
2552 break;
2553 }
2554 }
2555
2556 if (LastDeducibleArgument) {
2557 // Some of the function template arguments cannot be deduced from a
2558 // function call, so we introduce an explicit template argument list
2559 // containing all of the arguments up to the first deducible argument.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002560 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002561 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002562 LastDeducibleArgument);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002563 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002564 }
2565
2566 // Add the function parameters
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002567 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002568 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002569 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00002570 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002571 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002572 }
2573
2574 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002575 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002576 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002577 Result.AddTypedTextChunk(
2578 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002579 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002580 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002581 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2582 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002583 }
2584
Douglas Gregord3c5d792009-11-17 16:44:22 +00002585 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002586 Selector Sel = Method->getSelector();
2587 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002588 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002589 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002590 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002591 }
2592
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002593 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002594 SelName += ':';
2595 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002596 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002597 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002598 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002599
2600 // If there is only one parameter, and we're past it, add an empty
2601 // typed-text chunk since there is nothing to type.
2602 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002603 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002604 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002605 unsigned Idx = 0;
2606 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2607 PEnd = Method->param_end();
2608 P != PEnd; (void)++P, ++Idx) {
2609 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002610 std::string Keyword;
2611 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002612 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002613 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002614 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002615 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002616 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002617 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002618 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002619 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002620 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002621
2622 // If we're before the starting parameter, skip the placeholder.
2623 if (Idx < StartParameter)
2624 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002625
2626 std::string Arg;
Douglas Gregore90dd002010-08-24 16:15:59 +00002627
2628 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002629 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregore90dd002010-08-24 16:15:59 +00002630 else {
John McCall31168b02011-06-15 23:02:42 +00002631 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor8f08d742011-07-30 07:55:26 +00002632 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2633 + Arg + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002634 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002635 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002636 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002637 }
2638
Douglas Gregor400f5972010-08-31 05:13:43 +00002639 if (Method->isVariadic() && (P + 1) == PEnd)
2640 Arg += ", ...";
2641
Douglas Gregor95887f92010-07-08 23:20:03 +00002642 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002643 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002644 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002645 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002646 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002647 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002648 }
2649
Douglas Gregor04c5f972009-12-23 00:21:46 +00002650 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002651 if (Method->param_size() == 0) {
2652 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002653 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002654 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002655 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002656 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002657 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002658 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002659
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002660 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002661 }
2662
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002663 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002664 }
2665
Douglas Gregorf09935f2009-12-01 05:55:20 +00002666 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002667 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002668 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002669
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002670 Result.AddTypedTextChunk(
2671 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002672 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002673}
2674
Douglas Gregorf0f51982009-09-23 00:34:09 +00002675CodeCompletionString *
2676CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2677 unsigned CurrentArg,
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002678 Sema &S,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002679 CodeCompletionAllocator &Allocator) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002680 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor75acd922011-09-27 23:30:47 +00002681 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002682
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002683 // FIXME: Set priority, availability appropriately.
2684 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002685 FunctionDecl *FDecl = getFunction();
Douglas Gregor75acd922011-09-27 23:30:47 +00002686 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002687 const FunctionProtoType *Proto
2688 = dyn_cast<FunctionProtoType>(getFunctionType());
2689 if (!FDecl && !Proto) {
2690 // Function without a prototype. Just give the return type and a
2691 // highlighted ellipsis.
2692 const FunctionType *FT = getFunctionType();
Douglas Gregor304f9b02011-02-01 21:15:40 +00002693 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00002694 S.Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002695 Result.getAllocator()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002696 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2697 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2698 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2699 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002700 }
2701
2702 if (FDecl)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002703 Result.AddTextChunk(
2704 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002705 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002706 Result.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002707 Result.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00002708 Proto->getResultType().getAsString(Policy)));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002709
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002710 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002711 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2712 for (unsigned I = 0; I != NumParams; ++I) {
2713 if (I)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002714 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002715
2716 std::string ArgString;
2717 QualType ArgType;
2718
2719 if (FDecl) {
2720 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2721 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2722 } else {
2723 ArgType = Proto->getArgType(I);
2724 }
2725
John McCall31168b02011-06-15 23:02:42 +00002726 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002727
2728 if (I == CurrentArg)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002729 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002730 Result.getAllocator().CopyString(ArgString)));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002731 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002732 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002733 }
2734
2735 if (Proto && Proto->isVariadic()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002736 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002737 if (CurrentArg < NumParams)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002738 Result.AddTextChunk("...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002739 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002740 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002741 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002742 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002743
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002744 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002745}
2746
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002747unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002748 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002749 bool PreferredTypeIsPointer) {
2750 unsigned Priority = CCP_Macro;
2751
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002752 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2753 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2754 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002755 Priority = CCP_Constant;
2756 if (PreferredTypeIsPointer)
2757 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002758 }
2759 // Treat "YES", "NO", "true", and "false" as constants.
2760 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2761 MacroName.equals("true") || MacroName.equals("false"))
2762 Priority = CCP_Constant;
2763 // Treat "bool" as a type.
2764 else if (MacroName.equals("bool"))
2765 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2766
Douglas Gregor6e240332010-08-16 16:18:59 +00002767
2768 return Priority;
2769}
2770
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002771CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2772 if (!D)
2773 return CXCursor_UnexposedDecl;
2774
2775 switch (D->getKind()) {
2776 case Decl::Enum: return CXCursor_EnumDecl;
2777 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2778 case Decl::Field: return CXCursor_FieldDecl;
2779 case Decl::Function:
2780 return CXCursor_FunctionDecl;
2781 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2782 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002783 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002784
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002785 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002786 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2787 case Decl::ObjCMethod:
2788 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2789 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2790 case Decl::CXXMethod: return CXCursor_CXXMethod;
2791 case Decl::CXXConstructor: return CXCursor_Constructor;
2792 case Decl::CXXDestructor: return CXCursor_Destructor;
2793 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2794 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002795 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002796 case Decl::ParmVar: return CXCursor_ParmDecl;
2797 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00002798 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002799 case Decl::Var: return CXCursor_VarDecl;
2800 case Decl::Namespace: return CXCursor_Namespace;
2801 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2802 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2803 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2804 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2805 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2806 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00002807 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002808 case Decl::ClassTemplatePartialSpecialization:
2809 return CXCursor_ClassTemplatePartialSpecialization;
2810 case Decl::UsingDirective: return CXCursor_UsingDirective;
2811
2812 case Decl::Using:
2813 case Decl::UnresolvedUsingValue:
2814 case Decl::UnresolvedUsingTypename:
2815 return CXCursor_UsingDeclaration;
2816
Douglas Gregor4cd65962011-06-03 23:08:58 +00002817 case Decl::ObjCPropertyImpl:
2818 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2819 case ObjCPropertyImplDecl::Dynamic:
2820 return CXCursor_ObjCDynamicDecl;
2821
2822 case ObjCPropertyImplDecl::Synthesize:
2823 return CXCursor_ObjCSynthesizeDecl;
2824 }
Douglas Gregor4cd65962011-06-03 23:08:58 +00002825
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002826 default:
2827 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2828 switch (TD->getTagKind()) {
2829 case TTK_Struct: return CXCursor_StructDecl;
2830 case TTK_Class: return CXCursor_ClassDecl;
2831 case TTK_Union: return CXCursor_UnionDecl;
2832 case TTK_Enum: return CXCursor_EnumDecl;
2833 }
2834 }
2835 }
2836
2837 return CXCursor_UnexposedDecl;
2838}
2839
Douglas Gregor55b037b2010-07-08 20:55:51 +00002840static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2841 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00002842 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00002843
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002844 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002845
Douglas Gregor9eb77012009-11-07 00:00:49 +00002846 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2847 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00002848 M != MEnd; ++M) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002849 Results.AddResult(Result(M->first,
2850 getMacroUsagePriority(M->first->getName(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002851 PP.getLangOptions(),
Douglas Gregor6e240332010-08-16 16:18:59 +00002852 TargetTypeIsPointer)));
Douglas Gregor55b037b2010-07-08 20:55:51 +00002853 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002854
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002855 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002856
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002857}
2858
Douglas Gregorce0e8562010-08-23 21:54:33 +00002859static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2860 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00002861 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00002862
2863 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002864
Douglas Gregorce0e8562010-08-23 21:54:33 +00002865 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2866 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2867 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2868 Results.AddResult(Result("__func__", CCP_Constant));
2869 Results.ExitScope();
2870}
2871
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002872static void HandleCodeCompleteResults(Sema *S,
2873 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002874 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002875 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002876 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002877 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002878 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002879}
2880
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002881static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2882 Sema::ParserCompletionContext PCC) {
2883 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00002884 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002885 return CodeCompletionContext::CCC_TopLevel;
2886
John McCallfaf5fb42010-08-26 23:41:50 +00002887 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002888 return CodeCompletionContext::CCC_ClassStructUnion;
2889
John McCallfaf5fb42010-08-26 23:41:50 +00002890 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002891 return CodeCompletionContext::CCC_ObjCInterface;
2892
John McCallfaf5fb42010-08-26 23:41:50 +00002893 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002894 return CodeCompletionContext::CCC_ObjCImplementation;
2895
John McCallfaf5fb42010-08-26 23:41:50 +00002896 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002897 return CodeCompletionContext::CCC_ObjCIvarList;
2898
John McCallfaf5fb42010-08-26 23:41:50 +00002899 case Sema::PCC_Template:
2900 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002901 if (S.CurContext->isFileContext())
2902 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00002903 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00002904 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00002905 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00002906
John McCallfaf5fb42010-08-26 23:41:50 +00002907 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002908 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00002909
John McCallfaf5fb42010-08-26 23:41:50 +00002910 case Sema::PCC_ForInit:
Douglas Gregorc769d6e2010-10-18 22:01:46 +00002911 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2912 S.getLangOptions().ObjC1)
2913 return CodeCompletionContext::CCC_ParenthesizedExpression;
2914 else
2915 return CodeCompletionContext::CCC_Expression;
2916
2917 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00002918 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002919 return CodeCompletionContext::CCC_Expression;
2920
John McCallfaf5fb42010-08-26 23:41:50 +00002921 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002922 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00002923
John McCallfaf5fb42010-08-26 23:41:50 +00002924 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00002925 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00002926
2927 case Sema::PCC_ParenthesizedExpression:
2928 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00002929
2930 case Sema::PCC_LocalDeclarationSpecifiers:
2931 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002932 }
David Blaikie8a40f702012-01-17 06:56:22 +00002933
2934 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002935}
2936
Douglas Gregorac322ec2010-08-27 21:18:54 +00002937/// \brief If we're in a C++ virtual member function, add completion results
2938/// that invoke the functions we override, since it's common to invoke the
2939/// overridden function as well as adding new functionality.
2940///
2941/// \param S The semantic analysis object for which we are generating results.
2942///
2943/// \param InContext This context in which the nested-name-specifier preceding
2944/// the code-completion point
2945static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2946 ResultBuilder &Results) {
2947 // Look through blocks.
2948 DeclContext *CurContext = S.CurContext;
2949 while (isa<BlockDecl>(CurContext))
2950 CurContext = CurContext->getParent();
2951
2952
2953 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2954 if (!Method || !Method->isVirtual())
2955 return;
2956
2957 // We need to have names for all of the parameters, if we're going to
2958 // generate a forwarding call.
2959 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2960 PEnd = Method->param_end();
2961 P != PEnd;
2962 ++P) {
2963 if (!(*P)->getDeclName())
2964 return;
2965 }
2966
Douglas Gregor75acd922011-09-27 23:30:47 +00002967 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00002968 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2969 MEnd = Method->end_overridden_methods();
2970 M != MEnd; ++M) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002971 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorac322ec2010-08-27 21:18:54 +00002972 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2973 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2974 continue;
2975
2976 // If we need a nested-name-specifier, add one now.
2977 if (!InContext) {
2978 NestedNameSpecifier *NNS
2979 = getRequiredQualification(S.Context, CurContext,
2980 Overridden->getDeclContext());
2981 if (NNS) {
2982 std::string Str;
2983 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00002984 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002985 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00002986 }
2987 } else if (!InContext->Equals(Overridden->getDeclContext()))
2988 continue;
2989
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002990 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002991 Overridden->getNameAsString()));
2992 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00002993 bool FirstParam = true;
2994 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2995 PEnd = Method->param_end();
2996 P != PEnd; ++P) {
2997 if (FirstParam)
2998 FirstParam = false;
2999 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003000 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003001
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003002 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003003 (*P)->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003004 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003005 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3006 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003007 CCP_SuperCompletion,
3008 CXCursor_CXXMethod));
3009 Results.Ignore(Overridden);
3010 }
3011}
3012
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003013void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003014 ParserCompletionContext CompletionContext) {
John McCall276321a2010-08-25 06:19:51 +00003015 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003016 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003017 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003018 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003019
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003020 // Determine how to filter results, e.g., so that the names of
3021 // values (functions, enumerators, function templates, etc.) are
3022 // only allowed where we can have an expression.
3023 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003024 case PCC_Namespace:
3025 case PCC_Class:
3026 case PCC_ObjCInterface:
3027 case PCC_ObjCImplementation:
3028 case PCC_ObjCInstanceVariableList:
3029 case PCC_Template:
3030 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003031 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003032 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003033 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3034 break;
3035
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003036 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003037 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003038 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003039 case PCC_ForInit:
3040 case PCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00003041 if (WantTypesInContext(CompletionContext, getLangOptions()))
3042 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3043 else
3044 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003045
3046 if (getLangOptions().CPlusPlus)
3047 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003048 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003049
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003050 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003051 // Unfiltered
3052 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003053 }
3054
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003055 // If we are in a C++ non-static member function, check the qualifiers on
3056 // the member function to filter/prioritize the results list.
3057 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3058 if (CurMethod->isInstance())
3059 Results.setObjectTypeQualifiers(
3060 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3061
Douglas Gregorc580c522010-01-14 01:09:38 +00003062 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003063 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3064 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003065
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003066 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003067 Results.ExitScope();
3068
Douglas Gregorce0e8562010-08-23 21:54:33 +00003069 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003070 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003071 case PCC_Expression:
3072 case PCC_Statement:
3073 case PCC_RecoveryInFunction:
3074 if (S->getFnParent())
3075 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3076 break;
3077
3078 case PCC_Namespace:
3079 case PCC_Class:
3080 case PCC_ObjCInterface:
3081 case PCC_ObjCImplementation:
3082 case PCC_ObjCInstanceVariableList:
3083 case PCC_Template:
3084 case PCC_MemberTemplate:
3085 case PCC_ForInit:
3086 case PCC_Condition:
3087 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003088 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003089 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003090 }
3091
Douglas Gregor9eb77012009-11-07 00:00:49 +00003092 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003093 AddMacroResults(PP, Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003094
Douglas Gregor50832e02010-09-20 22:39:41 +00003095 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003096 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003097}
3098
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003099static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3100 ParsedType Receiver,
3101 IdentifierInfo **SelIdents,
3102 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003103 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003104 bool IsSuper,
3105 ResultBuilder &Results);
3106
3107void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3108 bool AllowNonIdentifiers,
3109 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003110 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003111 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003112 AllowNestedNameSpecifiers
3113 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3114 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003115 Results.EnterNewScope();
3116
3117 // Type qualifiers can come after names.
3118 Results.AddResult(Result("const"));
3119 Results.AddResult(Result("volatile"));
3120 if (getLangOptions().C99)
3121 Results.AddResult(Result("restrict"));
3122
3123 if (getLangOptions().CPlusPlus) {
3124 if (AllowNonIdentifiers) {
3125 Results.AddResult(Result("operator"));
3126 }
3127
3128 // Add nested-name-specifiers.
3129 if (AllowNestedNameSpecifiers) {
3130 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003131 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003132 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3133 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3134 CodeCompleter->includeGlobals());
Douglas Gregor0ac41382010-09-23 23:01:17 +00003135 Results.setFilter(0);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003136 }
3137 }
3138 Results.ExitScope();
3139
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003140 // If we're in a context where we might have an expression (rather than a
3141 // declaration), and what we've seen so far is an Objective-C type that could
3142 // be a receiver of a class message, this may be a class message send with
3143 // the initial opening bracket '[' missing. Add appropriate completions.
3144 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3145 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3146 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3147 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3148 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3149 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3150 DS.getTypeQualifiers() == 0 &&
3151 S &&
3152 (S->getFlags() & Scope::DeclScope) != 0 &&
3153 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3154 Scope::FunctionPrototypeScope |
3155 Scope::AtCatchScope)) == 0) {
3156 ParsedType T = DS.getRepAsType();
3157 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003158 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003159 }
3160
Douglas Gregor56ccce02010-08-24 04:59:56 +00003161 // Note that we intentionally suppress macro results here, since we do not
3162 // encourage using macros to produce the names of entities.
3163
Douglas Gregor0ac41382010-09-23 23:01:17 +00003164 HandleCodeCompleteResults(this, CodeCompleter,
3165 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003166 Results.data(), Results.size());
3167}
3168
Douglas Gregor68762e72010-08-23 21:17:50 +00003169struct Sema::CodeCompleteExpressionData {
3170 CodeCompleteExpressionData(QualType PreferredType = QualType())
3171 : PreferredType(PreferredType), IntegralConstantExpression(false),
3172 ObjCCollection(false) { }
3173
3174 QualType PreferredType;
3175 bool IntegralConstantExpression;
3176 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003177 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003178};
3179
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003180/// \brief Perform code-completion in an expression context when we know what
3181/// type we're looking for.
Douglas Gregor85b50632010-07-28 21:50:18 +00003182///
3183/// \param IntegralConstantExpression Only permit integral constant
3184/// expressions.
Douglas Gregor68762e72010-08-23 21:17:50 +00003185void Sema::CodeCompleteExpression(Scope *S,
3186 const CodeCompleteExpressionData &Data) {
John McCall276321a2010-08-25 06:19:51 +00003187 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003188 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3189 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003190 if (Data.ObjCCollection)
3191 Results.setFilter(&ResultBuilder::IsObjCCollection);
3192 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003193 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003194 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003195 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3196 else
3197 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003198
3199 if (!Data.PreferredType.isNull())
3200 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3201
3202 // Ignore any declarations that we were told that we don't care about.
3203 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3204 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003205
3206 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003207 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3208 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003209
3210 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003211 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003212 Results.ExitScope();
3213
Douglas Gregor55b037b2010-07-08 20:55:51 +00003214 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003215 if (!Data.PreferredType.isNull())
3216 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3217 || Data.PreferredType->isMemberPointerType()
3218 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003219
Douglas Gregorce0e8562010-08-23 21:54:33 +00003220 if (S->getFnParent() &&
3221 !Data.ObjCCollection &&
3222 !Data.IntegralConstantExpression)
3223 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3224
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003225 if (CodeCompleter->includeMacros())
Douglas Gregor55b037b2010-07-08 20:55:51 +00003226 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003227 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003228 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3229 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003230 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003231}
3232
Douglas Gregoreda7e542010-09-18 01:28:11 +00003233void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3234 if (E.isInvalid())
3235 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3236 else if (getLangOptions().ObjC1)
3237 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003238}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003239
Douglas Gregorb888acf2010-12-09 23:01:55 +00003240/// \brief The set of properties that have already been added, referenced by
3241/// property name.
3242typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3243
Douglas Gregor9291bad2009-11-18 01:29:26 +00003244static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003245 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003246 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003247 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003248 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003249 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003250 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003251
3252 // Add properties in this container.
3253 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3254 PEnd = Container->prop_end();
3255 P != PEnd;
Douglas Gregorb888acf2010-12-09 23:01:55 +00003256 ++P) {
3257 if (AddedProperties.insert(P->getIdentifier()))
3258 Results.MaybeAddResult(Result(*P, 0), CurContext);
3259 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003260
Douglas Gregor95147142011-05-05 15:50:42 +00003261 // Add nullary methods
3262 if (AllowNullaryMethods) {
3263 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003264 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor95147142011-05-05 15:50:42 +00003265 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3266 MEnd = Container->meth_end();
3267 M != MEnd; ++M) {
3268 if (M->getSelector().isUnarySelector())
3269 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3270 if (AddedProperties.insert(Name)) {
3271 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor75acd922011-09-27 23:30:47 +00003272 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003273 Builder.AddTypedTextChunk(
3274 Results.getAllocator().CopyString(Name->getName()));
3275
3276 CXAvailabilityKind Availability = CXAvailability_Available;
3277 switch (M->getAvailability()) {
3278 case AR_Available:
3279 case AR_NotYetIntroduced:
3280 Availability = CXAvailability_Available;
3281 break;
3282
3283 case AR_Deprecated:
3284 Availability = CXAvailability_Deprecated;
3285 break;
3286
3287 case AR_Unavailable:
3288 Availability = CXAvailability_NotAvailable;
3289 break;
3290 }
3291
3292 Results.MaybeAddResult(Result(Builder.TakeString(),
3293 CCP_MemberDeclaration + CCD_MethodAsProperty,
3294 M->isInstanceMethod()
3295 ? CXCursor_ObjCInstanceMethodDecl
3296 : CXCursor_ObjCClassMethodDecl,
3297 Availability),
3298 CurContext);
3299 }
3300 }
3301 }
3302
3303
Douglas Gregor9291bad2009-11-18 01:29:26 +00003304 // Add properties in referenced protocols.
3305 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3306 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3307 PEnd = Protocol->protocol_end();
3308 P != PEnd; ++P)
Douglas Gregor95147142011-05-05 15:50:42 +00003309 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3310 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003311 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003312 if (AllowCategories) {
3313 // Look through categories.
3314 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3315 Category; Category = Category->getNextClassCategory())
Douglas Gregor95147142011-05-05 15:50:42 +00003316 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3317 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003318 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003319
3320 // Look through protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00003321 for (ObjCInterfaceDecl::all_protocol_iterator
3322 I = IFace->all_referenced_protocol_begin(),
3323 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor95147142011-05-05 15:50:42 +00003324 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3325 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003326
3327 // Look in the superclass.
3328 if (IFace->getSuperClass())
Douglas Gregor95147142011-05-05 15:50:42 +00003329 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3330 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003331 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003332 } else if (const ObjCCategoryDecl *Category
3333 = dyn_cast<ObjCCategoryDecl>(Container)) {
3334 // Look through protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00003335 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3336 PEnd = Category->protocol_end();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003337 P != PEnd; ++P)
Douglas Gregor95147142011-05-05 15:50:42 +00003338 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3339 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003340 }
3341}
3342
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003343void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003344 SourceLocation OpLoc,
3345 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003346 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003347 return;
3348
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003349 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3350 if (ConvertedBase.isInvalid())
3351 return;
3352 Base = ConvertedBase.get();
3353
John McCall276321a2010-08-25 06:19:51 +00003354 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003355
Douglas Gregor2436e712009-09-17 21:32:03 +00003356 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003357
3358 if (IsArrow) {
3359 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3360 BaseType = Ptr->getPointeeType();
3361 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003362 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003363 else
3364 return;
3365 }
3366
Douglas Gregor21325842011-07-07 16:03:39 +00003367 enum CodeCompletionContext::Kind contextKind;
3368
3369 if (IsArrow) {
3370 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3371 }
3372 else {
3373 if (BaseType->isObjCObjectPointerType() ||
3374 BaseType->isObjCObjectOrInterfaceType()) {
3375 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3376 }
3377 else {
3378 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3379 }
3380 }
3381
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00003383 CodeCompletionContext(contextKind,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003384 BaseType),
3385 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003386 Results.EnterNewScope();
3387 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003388 // Indicate that we are performing a member access, and the cv-qualifiers
3389 // for the base object type.
3390 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3391
Douglas Gregor9291bad2009-11-18 01:29:26 +00003392 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003393 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003394 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003395 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3396 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003397
Douglas Gregor9291bad2009-11-18 01:29:26 +00003398 if (getLangOptions().CPlusPlus) {
3399 if (!Results.empty()) {
3400 // The "template" keyword can follow "->" or "." in the grammar.
3401 // However, we only want to suggest the template keyword if something
3402 // is dependent.
3403 bool IsDependent = BaseType->isDependentType();
3404 if (!IsDependent) {
3405 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3406 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3407 IsDependent = Ctx->isDependentContext();
3408 break;
3409 }
3410 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003411
Douglas Gregor9291bad2009-11-18 01:29:26 +00003412 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003413 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003414 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003415 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003416 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3417 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003418 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003419
3420 // Add property results based on our interface.
3421 const ObjCObjectPointerType *ObjCPtr
3422 = BaseType->getAsObjCInterfacePointerType();
3423 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor95147142011-05-05 15:50:42 +00003424 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3425 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003426 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003427
3428 // Add properties from the protocols in a qualified interface.
3429 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3430 E = ObjCPtr->qual_end();
3431 I != E; ++I)
Douglas Gregor95147142011-05-05 15:50:42 +00003432 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3433 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003434 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003435 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003436 // Objective-C instance variable access.
3437 ObjCInterfaceDecl *Class = 0;
3438 if (const ObjCObjectPointerType *ObjCPtr
3439 = BaseType->getAs<ObjCObjectPointerType>())
3440 Class = ObjCPtr->getInterfaceDecl();
3441 else
John McCall8b07ec22010-05-15 11:32:37 +00003442 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003443
3444 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003445 if (Class) {
3446 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3447 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003448 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3449 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003450 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003451 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003452
3453 // FIXME: How do we cope with isa?
3454
3455 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003456
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003457 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003458 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003459 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003460 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003461}
3462
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003463void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3464 if (!CodeCompleter)
3465 return;
3466
John McCall276321a2010-08-25 06:19:51 +00003467 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003468 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003469 enum CodeCompletionContext::Kind ContextKind
3470 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003471 switch ((DeclSpec::TST)TagSpec) {
3472 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003473 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003474 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003475 break;
3476
3477 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003478 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003479 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003480 break;
3481
3482 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003483 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003484 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003485 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003486 break;
3487
3488 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003489 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003490 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003491
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003492 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003493 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003494
3495 // First pass: look for tags.
3496 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003497 LookupVisibleDecls(S, LookupTagName, Consumer,
3498 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003499
Douglas Gregor39982192010-08-15 06:18:01 +00003500 if (CodeCompleter->includeGlobals()) {
3501 // Second pass: look for nested name specifiers.
3502 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3503 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3504 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003505
Douglas Gregor0ac41382010-09-23 23:01:17 +00003506 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003507 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003508}
3509
Douglas Gregor28c78432010-08-27 17:35:51 +00003510void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003511 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3512 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003513 Results.EnterNewScope();
3514 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3515 Results.AddResult("const");
3516 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3517 Results.AddResult("volatile");
3518 if (getLangOptions().C99 &&
3519 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3520 Results.AddResult("restrict");
3521 Results.ExitScope();
3522 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003523 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003524 Results.data(), Results.size());
3525}
3526
Douglas Gregord328d572009-09-21 18:10:23 +00003527void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003528 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003529 return;
John McCall5939b162011-08-06 07:30:58 +00003530
John McCallaab3e412010-08-25 08:40:02 +00003531 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003532 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3533 if (!type->isEnumeralType()) {
3534 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003535 Data.IntegralConstantExpression = true;
3536 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003537 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003538 }
Douglas Gregord328d572009-09-21 18:10:23 +00003539
3540 // Code-complete the cases of a switch statement over an enumeration type
3541 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003542 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregord328d572009-09-21 18:10:23 +00003543
3544 // Determine which enumerators we have already seen in the switch statement.
3545 // FIXME: Ideally, we would also be able to look *past* the code-completion
3546 // token, in case we are code-completing in the middle of the switch and not
3547 // at the end. However, we aren't able to do so at the moment.
3548 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00003549 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00003550 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3551 SC = SC->getNextSwitchCase()) {
3552 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3553 if (!Case)
3554 continue;
3555
3556 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3557 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3558 if (EnumConstantDecl *Enumerator
3559 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3560 // We look into the AST of the case statement to determine which
3561 // enumerator was named. Alternatively, we could compute the value of
3562 // the integral constant expression, then compare it against the
3563 // values of each enumerator. However, value-based approach would not
3564 // work as well with C++ templates where enumerators declared within a
3565 // template are type- and value-dependent.
3566 EnumeratorsSeen.insert(Enumerator);
3567
Douglas Gregorf2510672009-09-21 19:57:38 +00003568 // If this is a qualified-id, keep track of the nested-name-specifier
3569 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003570 //
3571 // switch (TagD.getKind()) {
3572 // case TagDecl::TK_enum:
3573 // break;
3574 // case XXX
3575 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003576 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003577 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3578 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003579 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003580 }
3581 }
3582
Douglas Gregorf2510672009-09-21 19:57:38 +00003583 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3584 // If there are no prior enumerators in C++, check whether we have to
3585 // qualify the names of the enumerators that we suggest, because they
3586 // may not be visible in this scope.
3587 Qualifier = getRequiredQualification(Context, CurContext,
3588 Enum->getDeclContext());
3589
3590 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3591 }
3592
Douglas Gregord328d572009-09-21 18:10:23 +00003593 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003594 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3595 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003596 Results.EnterNewScope();
3597 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3598 EEnd = Enum->enumerator_end();
3599 E != EEnd; ++E) {
3600 if (EnumeratorsSeen.count(*E))
3601 continue;
3602
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00003603 CodeCompletionResult R(*E, Qualifier);
3604 R.Priority = CCP_EnumInCase;
3605 Results.AddResult(R, CurContext, 0, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003606 }
3607 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003608
Douglas Gregor21325842011-07-07 16:03:39 +00003609 //We need to make sure we're setting the right context,
3610 //so only say we include macros if the code completer says we do
3611 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3612 if (CodeCompleter->includeMacros()) {
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003613 AddMacroResults(PP, Results);
Douglas Gregor21325842011-07-07 16:03:39 +00003614 kind = CodeCompletionContext::CCC_OtherWithMacros;
3615 }
3616
3617
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003618 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003619 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003620 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003621}
3622
Douglas Gregorcabea402009-09-22 15:41:20 +00003623namespace {
3624 struct IsBetterOverloadCandidate {
3625 Sema &S;
John McCallbc077cf2010-02-08 23:07:23 +00003626 SourceLocation Loc;
Douglas Gregorcabea402009-09-22 15:41:20 +00003627
3628 public:
John McCallbc077cf2010-02-08 23:07:23 +00003629 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3630 : S(S), Loc(Loc) { }
Douglas Gregorcabea402009-09-22 15:41:20 +00003631
3632 bool
3633 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall5c32be02010-08-24 20:38:10 +00003634 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregorcabea402009-09-22 15:41:20 +00003635 }
3636 };
3637}
3638
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003639static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3640 if (NumArgs && !Args)
3641 return true;
3642
3643 for (unsigned I = 0; I != NumArgs; ++I)
3644 if (!Args[I])
3645 return true;
3646
3647 return false;
3648}
3649
Richard Trieu2bd04012011-09-09 02:00:50 +00003650void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3651 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003652 if (!CodeCompleter)
3653 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003654
3655 // When we're code-completing for a call, we fall back to ordinary
3656 // name code-completion whenever we can't produce specific
3657 // results. We may want to revisit this strategy in the future,
3658 // e.g., by merging the two kinds of results.
3659
Douglas Gregorcabea402009-09-22 15:41:20 +00003660 Expr *Fn = (Expr *)FnIn;
3661 Expr **Args = (Expr **)ArgsIn;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003662
Douglas Gregorcabea402009-09-22 15:41:20 +00003663 // Ignore type-dependent call expressions entirely.
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003664 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregor3ef59522009-12-11 19:06:04 +00003665 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003666 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00003667 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003668 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003669
John McCall57500772009-12-16 12:17:52 +00003670 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00003671 SourceLocation Loc = Fn->getExprLoc();
3672 OverloadCandidateSet CandidateSet(Loc);
John McCall57500772009-12-16 12:17:52 +00003673
Douglas Gregorcabea402009-09-22 15:41:20 +00003674 // FIXME: What if we're calling something that isn't a function declaration?
3675 // FIXME: What if we're calling a pseudo-destructor?
3676 // FIXME: What if we're calling a member function?
3677
Douglas Gregorff59f672010-01-21 15:46:19 +00003678 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003679 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00003680
John McCall57500772009-12-16 12:17:52 +00003681 Expr *NakedFn = Fn->IgnoreParenCasts();
3682 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3683 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3684 /*PartialOverloading=*/ true);
3685 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3686 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorff59f672010-01-21 15:46:19 +00003687 if (FDecl) {
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003688 if (!getLangOptions().CPlusPlus ||
3689 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorff59f672010-01-21 15:46:19 +00003690 Results.push_back(ResultCandidate(FDecl));
3691 else
John McCallb89836b2010-01-26 01:37:31 +00003692 // FIXME: access?
John McCalla0296f72010-03-19 07:35:19 +00003693 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3694 Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003695 false, /*PartialOverloading*/true);
Douglas Gregorff59f672010-01-21 15:46:19 +00003696 }
John McCall57500772009-12-16 12:17:52 +00003697 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003698
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003699 QualType ParamType;
3700
Douglas Gregorff59f672010-01-21 15:46:19 +00003701 if (!CandidateSet.empty()) {
3702 // Sort the overload candidate set by placing the best overloads first.
3703 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCallbc077cf2010-02-08 23:07:23 +00003704 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregorcabea402009-09-22 15:41:20 +00003705
Douglas Gregorff59f672010-01-21 15:46:19 +00003706 // Add the remaining viable overload candidates as code-completion reslults.
3707 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3708 CandEnd = CandidateSet.end();
3709 Cand != CandEnd; ++Cand) {
3710 if (Cand->Viable)
3711 Results.push_back(ResultCandidate(Cand->Function));
3712 }
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003713
3714 // From the viable candidates, try to determine the type of this parameter.
3715 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3716 if (const FunctionType *FType = Results[I].getFunctionType())
3717 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3718 if (NumArgs < Proto->getNumArgs()) {
3719 if (ParamType.isNull())
3720 ParamType = Proto->getArgType(NumArgs);
3721 else if (!Context.hasSameUnqualifiedType(
3722 ParamType.getNonReferenceType(),
3723 Proto->getArgType(NumArgs).getNonReferenceType())) {
3724 ParamType = QualType();
3725 break;
3726 }
3727 }
3728 }
3729 } else {
3730 // Try to determine the parameter type from the type of the expression
3731 // being called.
3732 QualType FunctionType = Fn->getType();
3733 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3734 FunctionType = Ptr->getPointeeType();
3735 else if (const BlockPointerType *BlockPtr
3736 = FunctionType->getAs<BlockPointerType>())
3737 FunctionType = BlockPtr->getPointeeType();
3738 else if (const MemberPointerType *MemPtr
3739 = FunctionType->getAs<MemberPointerType>())
3740 FunctionType = MemPtr->getPointeeType();
3741
3742 if (const FunctionProtoType *Proto
3743 = FunctionType->getAs<FunctionProtoType>()) {
3744 if (NumArgs < Proto->getNumArgs())
3745 ParamType = Proto->getArgType(NumArgs);
3746 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003747 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00003748
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003749 if (ParamType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003750 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003751 else
3752 CodeCompleteExpression(S, ParamType);
3753
Douglas Gregorc01890e2010-04-06 20:19:47 +00003754 if (!Results.empty())
Douglas Gregor3ef59522009-12-11 19:06:04 +00003755 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3756 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00003757}
3758
John McCall48871652010-08-21 09:40:31 +00003759void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3760 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003761 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003762 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003763 return;
3764 }
3765
3766 CodeCompleteExpression(S, VD->getType());
3767}
3768
3769void Sema::CodeCompleteReturn(Scope *S) {
3770 QualType ResultType;
3771 if (isa<BlockDecl>(CurContext)) {
3772 if (BlockScopeInfo *BSI = getCurBlock())
3773 ResultType = BSI->ReturnType;
3774 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3775 ResultType = Function->getResultType();
3776 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3777 ResultType = Method->getResultType();
3778
3779 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003780 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003781 else
3782 CodeCompleteExpression(S, ResultType);
3783}
3784
Douglas Gregor4ecb7202011-07-30 08:36:53 +00003785void Sema::CodeCompleteAfterIf(Scope *S) {
3786 typedef CodeCompletionResult Result;
3787 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3788 mapCodeCompletionContext(*this, PCC_Statement));
3789 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3790 Results.EnterNewScope();
3791
3792 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3793 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3794 CodeCompleter->includeGlobals());
3795
3796 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3797
3798 // "else" block
3799 CodeCompletionBuilder Builder(Results.getAllocator());
3800 Builder.AddTypedTextChunk("else");
3801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3802 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3803 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3804 Builder.AddPlaceholderChunk("statements");
3805 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3806 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3807 Results.AddResult(Builder.TakeString());
3808
3809 // "else if" block
3810 Builder.AddTypedTextChunk("else");
3811 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3812 Builder.AddTextChunk("if");
3813 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3814 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3815 if (getLangOptions().CPlusPlus)
3816 Builder.AddPlaceholderChunk("condition");
3817 else
3818 Builder.AddPlaceholderChunk("expression");
3819 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3821 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3822 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3823 Builder.AddPlaceholderChunk("statements");
3824 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3825 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3826 Results.AddResult(Builder.TakeString());
3827
3828 Results.ExitScope();
3829
3830 if (S->getFnParent())
3831 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3832
3833 if (CodeCompleter->includeMacros())
3834 AddMacroResults(PP, Results);
3835
3836 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3837 Results.data(),Results.size());
3838}
3839
Richard Trieu2bd04012011-09-09 02:00:50 +00003840void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003841 if (LHS)
3842 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3843 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003844 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003845}
3846
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003847void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00003848 bool EnteringContext) {
3849 if (!SS.getScopeRep() || !CodeCompleter)
3850 return;
3851
Douglas Gregor3545ff42009-09-21 16:56:56 +00003852 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3853 if (!Ctx)
3854 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00003855
3856 // Try to instantiate any non-dependent declaration contexts before
3857 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00003858 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00003859 return;
3860
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003861 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3862 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003863 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003864
Douglas Gregor3545ff42009-09-21 16:56:56 +00003865 // The "template" keyword can follow "::" in the grammar, but only
3866 // put it into the grammar if the nested-name-specifier is dependent.
3867 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3868 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00003869 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00003870
3871 // Add calls to overridden virtual functions, if there are any.
3872 //
3873 // FIXME: This isn't wonderful, because we don't know whether we're actually
3874 // in a context that permits expressions. This is a general issue with
3875 // qualified-id completions.
3876 if (!EnteringContext)
3877 MaybeAddOverrideCalls(*this, Ctx, Results);
3878 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003879
Douglas Gregorac322ec2010-08-27 21:18:54 +00003880 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3881 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3882
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003883 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00003884 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003885 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003886}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003887
3888void Sema::CodeCompleteUsing(Scope *S) {
3889 if (!CodeCompleter)
3890 return;
3891
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003892 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003893 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3894 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003895 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003896
3897 // If we aren't in class scope, we could see the "namespace" keyword.
3898 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00003899 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00003900
3901 // After "using", we can see anything that would start a
3902 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003903 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003904 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3905 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00003906 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003907
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003908 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003909 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003910 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003911}
3912
3913void Sema::CodeCompleteUsingDirective(Scope *S) {
3914 if (!CodeCompleter)
3915 return;
3916
Douglas Gregor3545ff42009-09-21 16:56:56 +00003917 // After "using namespace", we expect to see a namespace name or namespace
3918 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003919 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3920 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003921 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003922 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003923 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003924 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3925 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00003926 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003927 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00003928 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003929 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003930}
3931
3932void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3933 if (!CodeCompleter)
3934 return;
3935
Douglas Gregor3545ff42009-09-21 16:56:56 +00003936 DeclContext *Ctx = (DeclContext *)S->getEntity();
3937 if (!S->getParent())
3938 Ctx = Context.getTranslationUnitDecl();
3939
Douglas Gregor0ac41382010-09-23 23:01:17 +00003940 bool SuppressedGlobalResults
3941 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3942
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003943 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003944 SuppressedGlobalResults
3945 ? CodeCompletionContext::CCC_Namespace
3946 : CodeCompletionContext::CCC_Other,
3947 &ResultBuilder::IsNamespace);
3948
3949 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003950 // We only want to see those namespaces that have already been defined
3951 // within this scope, because its likely that the user is creating an
3952 // extended namespace declaration. Keep track of the most recent
3953 // definition of each namespace.
3954 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3955 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3956 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3957 NS != NSEnd; ++NS)
3958 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3959
3960 // Add the most recent definition (or extended definition) of each
3961 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00003962 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003963 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3964 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3965 NS != NSEnd; ++NS)
John McCall276321a2010-08-25 06:19:51 +00003966 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003967 CurContext, 0, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00003968 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003969 }
3970
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003971 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003972 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003973 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003974}
3975
3976void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3977 if (!CodeCompleter)
3978 return;
3979
Douglas Gregor3545ff42009-09-21 16:56:56 +00003980 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003981 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3982 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003983 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003984 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003985 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3986 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003987 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003988 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003989 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00003990}
3991
Douglas Gregorc811ede2009-09-18 20:05:18 +00003992void Sema::CodeCompleteOperatorName(Scope *S) {
3993 if (!CodeCompleter)
3994 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003995
John McCall276321a2010-08-25 06:19:51 +00003996 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003997 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3998 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003999 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004000 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004001
Douglas Gregor3545ff42009-09-21 16:56:56 +00004002 // Add the names of overloadable operators.
4003#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4004 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004005 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004006#include "clang/Basic/OperatorKinds.def"
4007
4008 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004009 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004010 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004011 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4012 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004013
4014 // Add any type specifiers
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004015 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004016 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004017
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004018 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004019 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004020 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004021}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004022
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004023void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Alexis Hunt1d792652011-01-08 20:30:50 +00004024 CXXCtorInitializer** Initializers,
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004025 unsigned NumInitializers) {
Douglas Gregor75acd922011-09-27 23:30:47 +00004026 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004027 CXXConstructorDecl *Constructor
4028 = static_cast<CXXConstructorDecl *>(ConstructorD);
4029 if (!Constructor)
4030 return;
4031
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004032 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004033 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004034 Results.EnterNewScope();
4035
4036 // Fill in any already-initialized fields or base classes.
4037 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4038 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4039 for (unsigned I = 0; I != NumInitializers; ++I) {
4040 if (Initializers[I]->isBaseInitializer())
4041 InitializedBases.insert(
4042 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4043 else
Francois Pichetd583da02010-12-04 09:14:42 +00004044 InitializedFields.insert(cast<FieldDecl>(
4045 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004046 }
4047
4048 // Add completions for base classes.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004049 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor99129ef2010-08-29 19:27:27 +00004050 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004051 CXXRecordDecl *ClassDecl = Constructor->getParent();
4052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4053 BaseEnd = ClassDecl->bases_end();
4054 Base != BaseEnd; ++Base) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004055 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4056 SawLastInitializer
4057 = NumInitializers > 0 &&
4058 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4059 Context.hasSameUnqualifiedType(Base->getType(),
4060 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004061 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004062 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004063
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004064 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004065 Results.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00004066 Base->getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004067 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4068 Builder.AddPlaceholderChunk("args");
4069 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4070 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004071 SawLastInitializer? CCP_NextInitializer
4072 : CCP_MemberDeclaration));
4073 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004074 }
4075
4076 // Add completions for virtual base classes.
4077 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4078 BaseEnd = ClassDecl->vbases_end();
4079 Base != BaseEnd; ++Base) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004080 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4081 SawLastInitializer
4082 = NumInitializers > 0 &&
4083 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4084 Context.hasSameUnqualifiedType(Base->getType(),
4085 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004086 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004087 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004088
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004089 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004090 Builder.getAllocator().CopyString(
John McCall31168b02011-06-15 23:02:42 +00004091 Base->getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004092 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4093 Builder.AddPlaceholderChunk("args");
4094 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4095 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004096 SawLastInitializer? CCP_NextInitializer
4097 : CCP_MemberDeclaration));
4098 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004099 }
4100
4101 // Add completions for members.
4102 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4103 FieldEnd = ClassDecl->field_end();
4104 Field != FieldEnd; ++Field) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004105 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4106 SawLastInitializer
4107 = NumInitializers > 0 &&
Francois Pichetd583da02010-12-04 09:14:42 +00004108 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4109 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004110 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004111 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004112
4113 if (!Field->getDeclName())
4114 continue;
4115
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004116 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004117 Field->getIdentifier()->getName()));
4118 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4119 Builder.AddPlaceholderChunk("args");
4120 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4121 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004122 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004123 : CCP_MemberDeclaration,
4124 CXCursor_MemberRef));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004125 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004126 }
4127 Results.ExitScope();
4128
Douglas Gregor0ac41382010-09-23 23:01:17 +00004129 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004130 Results.data(), Results.size());
4131}
4132
Douglas Gregorf1934162010-01-13 21:24:21 +00004133// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4134// true or false.
4135#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004136static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004137 ResultBuilder &Results,
4138 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004139 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004140 // Since we have an implementation, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00004141 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004142
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004143 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00004144 if (LangOpts.ObjC2) {
4145 // @dynamic
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004146 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4147 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4148 Builder.AddPlaceholderChunk("property");
4149 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004150
4151 // @synthesize
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004152 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4153 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4154 Builder.AddPlaceholderChunk("property");
4155 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004156 }
4157}
4158
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004159static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004160 ResultBuilder &Results,
4161 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004162 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004163
4164 // Since we have an interface or protocol, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00004165 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004166
4167 if (LangOpts.ObjC2) {
4168 // @property
Douglas Gregor78a21012010-01-14 16:01:26 +00004169 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004170
4171 // @required
Douglas Gregor78a21012010-01-14 16:01:26 +00004172 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004173
4174 // @optional
Douglas Gregor78a21012010-01-14 16:01:26 +00004175 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorf1934162010-01-13 21:24:21 +00004176 }
4177}
4178
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004179static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004180 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004181 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00004182
4183 // @class name ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004184 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4185 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4186 Builder.AddPlaceholderChunk("name");
4187 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004188
Douglas Gregorf4c33342010-05-28 00:22:41 +00004189 if (Results.includeCodePatterns()) {
4190 // @interface name
4191 // FIXME: Could introduce the whole pattern, including superclasses and
4192 // such.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004193 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4194 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4195 Builder.AddPlaceholderChunk("class");
4196 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004197
Douglas Gregorf4c33342010-05-28 00:22:41 +00004198 // @protocol name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004199 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4200 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4201 Builder.AddPlaceholderChunk("protocol");
4202 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004203
4204 // @implementation name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004205 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4206 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4207 Builder.AddPlaceholderChunk("class");
4208 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004209 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004210
4211 // @compatibility_alias name
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004212 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4213 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4214 Builder.AddPlaceholderChunk("alias");
4215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4216 Builder.AddPlaceholderChunk("class");
4217 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004218}
4219
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004220void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00004221 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004222 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4223 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004224 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004225 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004226 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004227 else if (CurContext->isObjCContainer())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004228 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004229 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004230 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004231 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004232 HandleCodeCompleteResults(this, CodeCompleter,
4233 CodeCompletionContext::CCC_Other,
4234 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004235}
4236
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004237static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004238 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004239 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004240
4241 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004242 const char *EncodeType = "char[]";
4243 if (Results.getSema().getLangOptions().CPlusPlus ||
4244 Results.getSema().getLangOptions().ConstStrings)
4245 EncodeType = " const char[]";
4246 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004247 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4248 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4249 Builder.AddPlaceholderChunk("type-name");
4250 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4251 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004252
4253 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004254 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004255 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4256 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4257 Builder.AddPlaceholderChunk("protocol-name");
4258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4259 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004260
4261 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004262 Builder.AddResultTypeChunk("SEL");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004263 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4265 Builder.AddPlaceholderChunk("selector");
4266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004268}
4269
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004270static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004271 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004272 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf1934162010-01-13 21:24:21 +00004273
Douglas Gregorf4c33342010-05-28 00:22:41 +00004274 if (Results.includeCodePatterns()) {
4275 // @try { statements } @catch ( declaration ) { statements } @finally
4276 // { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004277 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4278 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4279 Builder.AddPlaceholderChunk("statements");
4280 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4281 Builder.AddTextChunk("@catch");
4282 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4283 Builder.AddPlaceholderChunk("parameter");
4284 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4285 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4286 Builder.AddPlaceholderChunk("statements");
4287 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4288 Builder.AddTextChunk("@finally");
4289 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4290 Builder.AddPlaceholderChunk("statements");
4291 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4292 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004293 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004294
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004295 // @throw
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004296 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4297 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4298 Builder.AddPlaceholderChunk("expression");
4299 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004300
Douglas Gregorf4c33342010-05-28 00:22:41 +00004301 if (Results.includeCodePatterns()) {
4302 // @synchronized ( expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004303 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4304 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4306 Builder.AddPlaceholderChunk("expression");
4307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4308 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4309 Builder.AddPlaceholderChunk("statements");
4310 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4311 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004312 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004313}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004314
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004315static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004316 ResultBuilder &Results,
4317 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004318 typedef CodeCompletionResult Result;
Douglas Gregor78a21012010-01-14 16:01:26 +00004319 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4320 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4321 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregor48d46252010-01-13 21:54:15 +00004322 if (LangOpts.ObjC2)
Douglas Gregor78a21012010-01-14 16:01:26 +00004323 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregor48d46252010-01-13 21:54:15 +00004324}
4325
4326void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004327 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4328 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004329 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004330 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004331 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004332 HandleCodeCompleteResults(this, CodeCompleter,
4333 CodeCompletionContext::CCC_Other,
4334 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004335}
4336
4337void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004338 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4339 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004340 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004341 AddObjCStatementResults(Results, false);
4342 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004343 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004344 HandleCodeCompleteResults(this, CodeCompleter,
4345 CodeCompletionContext::CCC_Other,
4346 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004347}
4348
4349void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004350 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4351 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004352 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004353 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004354 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004355 HandleCodeCompleteResults(this, CodeCompleter,
4356 CodeCompletionContext::CCC_Other,
4357 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004358}
4359
Douglas Gregore6078da2009-11-19 00:14:45 +00004360/// \brief Determine whether the addition of the given flag to an Objective-C
4361/// property's attributes will cause a conflict.
4362static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4363 // Check if we've already added this flag.
4364 if (Attributes & NewFlag)
4365 return true;
4366
4367 Attributes |= NewFlag;
4368
4369 // Check for collisions with "readonly".
4370 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4371 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4372 ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004373 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004374 ObjCDeclSpec::DQ_PR_copy |
John McCall31168b02011-06-15 23:02:42 +00004375 ObjCDeclSpec::DQ_PR_retain |
4376 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregore6078da2009-11-19 00:14:45 +00004377 return true;
4378
John McCall31168b02011-06-15 23:02:42 +00004379 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregore6078da2009-11-19 00:14:45 +00004380 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004381 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004382 ObjCDeclSpec::DQ_PR_copy |
John McCall31168b02011-06-15 23:02:42 +00004383 ObjCDeclSpec::DQ_PR_retain|
4384 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregore6078da2009-11-19 00:14:45 +00004385 if (AssignCopyRetMask &&
4386 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004387 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004388 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004389 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4390 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregore6078da2009-11-19 00:14:45 +00004391 return true;
4392
4393 return false;
4394}
4395
Douglas Gregor36029f42009-11-18 23:08:07 +00004396void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004397 if (!CodeCompleter)
4398 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004399
Steve Naroff936354c2009-10-08 21:55:05 +00004400 unsigned Attributes = ODS.getPropertyAttributes();
4401
John McCall276321a2010-08-25 06:19:51 +00004402 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004403 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4404 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004405 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00004406 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004407 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004408 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004409 Results.AddResult(CodeCompletionResult("assign"));
John McCall31168b02011-06-15 23:02:42 +00004410 if (!ObjCPropertyFlagConflicts(Attributes,
4411 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4412 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004413 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004414 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004415 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004416 Results.AddResult(CodeCompletionResult("retain"));
John McCall31168b02011-06-15 23:02:42 +00004417 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4418 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004419 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004420 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004421 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004422 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004423 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4424 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregore6078da2009-11-19 00:14:45 +00004425 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004426 CodeCompletionBuilder Setter(Results.getAllocator());
4427 Setter.AddTypedTextChunk("setter");
4428 Setter.AddTextChunk(" = ");
4429 Setter.AddPlaceholderChunk("method");
4430 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004431 }
Douglas Gregore6078da2009-11-19 00:14:45 +00004432 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004433 CodeCompletionBuilder Getter(Results.getAllocator());
4434 Getter.AddTypedTextChunk("getter");
4435 Getter.AddTextChunk(" = ");
4436 Getter.AddPlaceholderChunk("method");
4437 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004438 }
Steve Naroff936354c2009-10-08 21:55:05 +00004439 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004440 HandleCodeCompleteResults(this, CodeCompleter,
4441 CodeCompletionContext::CCC_Other,
4442 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004443}
Steve Naroffeae65032009-11-07 02:08:14 +00004444
Douglas Gregorc8537c52009-11-19 07:41:15 +00004445/// \brief Descripts the kind of Objective-C method that we want to find
4446/// via code completion.
4447enum ObjCMethodKind {
4448 MK_Any, //< Any kind of method, provided it means other specified criteria.
4449 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4450 MK_OneArgSelector //< One-argument selector.
4451};
4452
Douglas Gregor67c692c2010-08-26 15:07:07 +00004453static bool isAcceptableObjCSelector(Selector Sel,
4454 ObjCMethodKind WantKind,
4455 IdentifierInfo **SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004456 unsigned NumSelIdents,
4457 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004458 if (NumSelIdents > Sel.getNumArgs())
4459 return false;
4460
4461 switch (WantKind) {
4462 case MK_Any: break;
4463 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4464 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4465 }
4466
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004467 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4468 return false;
4469
Douglas Gregor67c692c2010-08-26 15:07:07 +00004470 for (unsigned I = 0; I != NumSelIdents; ++I)
4471 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4472 return false;
4473
4474 return true;
4475}
4476
Douglas Gregorc8537c52009-11-19 07:41:15 +00004477static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4478 ObjCMethodKind WantKind,
4479 IdentifierInfo **SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004480 unsigned NumSelIdents,
4481 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004482 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004483 NumSelIdents, AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004484}
Douglas Gregor1154e272010-09-16 16:06:31 +00004485
4486namespace {
4487 /// \brief A set of selectors, which is used to avoid introducing multiple
4488 /// completions with the same selector into the result set.
4489 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4490}
4491
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004492/// \brief Add all of the Objective-C methods in the given Objective-C
4493/// container to the set of results.
4494///
4495/// The container will be a class, protocol, category, or implementation of
4496/// any of the above. This mether will recurse to include methods from
4497/// the superclasses of classes along with their categories, protocols, and
4498/// implementations.
4499///
4500/// \param Container the container in which we'll look to find methods.
4501///
4502/// \param WantInstance whether to add instance methods (only); if false, this
4503/// routine will add factory methods (only).
4504///
4505/// \param CurContext the context in which we're performing the lookup that
4506/// finds methods.
4507///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004508/// \param AllowSameLength Whether we allow a method to be added to the list
4509/// when it has the same number of parameters as we have selector identifiers.
4510///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004511/// \param Results the structure into which we'll add results.
4512static void AddObjCMethods(ObjCContainerDecl *Container,
4513 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00004514 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00004515 IdentifierInfo **SelIdents,
4516 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004517 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00004518 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004519 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00004520 ResultBuilder &Results,
4521 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00004522 typedef CodeCompletionResult Result;
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004523 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4524 MEnd = Container->meth_end();
4525 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00004526 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4527 // Check whether the selector identifiers we've been given are a
4528 // subset of the identifiers for this particular method.
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004529 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4530 AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00004531 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004532
Douglas Gregor1154e272010-09-16 16:06:31 +00004533 if (!Selectors.insert((*M)->getSelector()))
4534 continue;
4535
Douglas Gregor1b605f72009-11-19 01:08:35 +00004536 Result R = Result(*M, 0);
4537 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004538 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00004539 if (!InOriginalClass)
4540 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004541 Results.MaybeAddResult(R, CurContext);
4542 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004543 }
4544
Douglas Gregorf37c9492010-09-16 15:34:59 +00004545 // Visit the protocols of protocols.
4546 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004547 if (Protocol->hasDefinition()) {
4548 const ObjCList<ObjCProtocolDecl> &Protocols
4549 = Protocol->getReferencedProtocols();
4550 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4551 E = Protocols.end();
4552 I != E; ++I)
4553 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4554 NumSelIdents, CurContext, Selectors, AllowSameLength,
4555 Results, false);
4556 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00004557 }
4558
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004559 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004560 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004561 return;
4562
4563 // Add methods in protocols.
4564 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4565 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4566 E = Protocols.end();
4567 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004568 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004569 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004570
4571 // Add methods in categories.
4572 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4573 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00004574 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004575 NumSelIdents, CurContext, Selectors, AllowSameLength,
4576 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004577
4578 // Add a categories protocol methods.
4579 const ObjCList<ObjCProtocolDecl> &Protocols
4580 = CatDecl->getReferencedProtocols();
4581 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4582 E = Protocols.end();
4583 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004584 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004585 NumSelIdents, CurContext, Selectors, AllowSameLength,
4586 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004587
4588 // Add methods in category implementations.
4589 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004590 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004591 NumSelIdents, CurContext, Selectors, AllowSameLength,
4592 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004593 }
4594
4595 // Add methods in superclass.
4596 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004597 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004598 SelIdents, NumSelIdents, CurContext, Selectors,
4599 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004600
4601 // Add methods in our implementation, if any.
4602 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004603 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004604 NumSelIdents, CurContext, Selectors, AllowSameLength,
4605 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004606}
4607
4608
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004609void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00004610 typedef CodeCompletionResult Result;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004611
4612 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004613 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004614 if (!Class) {
4615 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004616 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004617 Class = Category->getClassInterface();
4618
4619 if (!Class)
4620 return;
4621 }
4622
4623 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004624 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4625 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004626 Results.EnterNewScope();
4627
Douglas Gregor1154e272010-09-16 16:06:31 +00004628 VisitedSelectorSet Selectors;
4629 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004630 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004631 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004632 HandleCodeCompleteResults(this, CodeCompleter,
4633 CodeCompletionContext::CCC_Other,
4634 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00004635}
4636
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004637void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00004638 typedef CodeCompletionResult Result;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004639
4640 // Try to find the interface where setters might live.
4641 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004642 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004643 if (!Class) {
4644 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004645 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004646 Class = Category->getClassInterface();
4647
4648 if (!Class)
4649 return;
4650 }
4651
4652 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004653 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4654 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004655 Results.EnterNewScope();
4656
Douglas Gregor1154e272010-09-16 16:06:31 +00004657 VisitedSelectorSet Selectors;
4658 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004659 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004660
4661 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004662 HandleCodeCompleteResults(this, CodeCompleter,
4663 CodeCompletionContext::CCC_Other,
4664 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004665}
4666
Douglas Gregorf34a6f02011-02-15 22:19:42 +00004667void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4668 bool IsParameter) {
John McCall276321a2010-08-25 06:19:51 +00004669 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004670 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4671 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00004672 Results.EnterNewScope();
4673
4674 // Add context-sensitive, Objective-C parameter-passing keywords.
4675 bool AddedInOut = false;
4676 if ((DS.getObjCDeclQualifier() &
4677 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4678 Results.AddResult("in");
4679 Results.AddResult("inout");
4680 AddedInOut = true;
4681 }
4682 if ((DS.getObjCDeclQualifier() &
4683 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4684 Results.AddResult("out");
4685 if (!AddedInOut)
4686 Results.AddResult("inout");
4687 }
4688 if ((DS.getObjCDeclQualifier() &
4689 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4690 ObjCDeclSpec::DQ_Oneway)) == 0) {
4691 Results.AddResult("bycopy");
4692 Results.AddResult("byref");
4693 Results.AddResult("oneway");
4694 }
4695
Douglas Gregorf34a6f02011-02-15 22:19:42 +00004696 // If we're completing the return type of an Objective-C method and the
4697 // identifier IBAction refers to a macro, provide a completion item for
4698 // an action, e.g.,
4699 // IBAction)<#selector#>:(id)sender
4700 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4701 Context.Idents.get("IBAction").hasMacroDefinition()) {
4702 typedef CodeCompletionString::Chunk Chunk;
4703 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4704 CXAvailability_Available);
4705 Builder.AddTypedTextChunk("IBAction");
4706 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4707 Builder.AddPlaceholderChunk("selector");
4708 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4709 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4710 Builder.AddTextChunk("id");
4711 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4712 Builder.AddTextChunk("sender");
4713 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4714 }
4715
Douglas Gregor99fa2642010-08-24 01:06:58 +00004716 // Add various builtin type names and specifiers.
4717 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4718 Results.ExitScope();
4719
4720 // Add the various type names
4721 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4722 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4723 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4724 CodeCompleter->includeGlobals());
4725
4726 if (CodeCompleter->includeMacros())
4727 AddMacroResults(PP, Results);
4728
4729 HandleCodeCompleteResults(this, CodeCompleter,
4730 CodeCompletionContext::CCC_Type,
4731 Results.data(), Results.size());
4732}
4733
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004734/// \brief When we have an expression with type "id", we may assume
4735/// that it has some more-specific class type based on knowledge of
4736/// common uses of Objective-C. This routine returns that class type,
4737/// or NULL if no better result could be determined.
4738static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00004739 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004740 if (!Msg)
4741 return 0;
4742
4743 Selector Sel = Msg->getSelector();
4744 if (Sel.isNull())
4745 return 0;
4746
4747 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4748 if (!Id)
4749 return 0;
4750
4751 ObjCMethodDecl *Method = Msg->getMethodDecl();
4752 if (!Method)
4753 return 0;
4754
4755 // Determine the class that we're sending the message to.
Douglas Gregor9a129192010-04-21 00:45:42 +00004756 ObjCInterfaceDecl *IFace = 0;
4757 switch (Msg->getReceiverKind()) {
4758 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00004759 if (const ObjCObjectType *ObjType
4760 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4761 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00004762 break;
4763
4764 case ObjCMessageExpr::Instance: {
4765 QualType T = Msg->getInstanceReceiver()->getType();
4766 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4767 IFace = Ptr->getInterfaceDecl();
4768 break;
4769 }
4770
4771 case ObjCMessageExpr::SuperInstance:
4772 case ObjCMessageExpr::SuperClass:
4773 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004774 }
4775
4776 if (!IFace)
4777 return 0;
4778
4779 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4780 if (Method->isInstanceMethod())
4781 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4782 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00004783 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00004784 .Case("autorelease", IFace)
4785 .Case("copy", IFace)
4786 .Case("copyWithZone", IFace)
4787 .Case("mutableCopy", IFace)
4788 .Case("mutableCopyWithZone", IFace)
4789 .Case("awakeFromCoder", IFace)
4790 .Case("replacementObjectFromCoder", IFace)
4791 .Case("class", IFace)
4792 .Case("classForCoder", IFace)
4793 .Case("superclass", Super)
4794 .Default(0);
4795
4796 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4797 .Case("new", IFace)
4798 .Case("alloc", IFace)
4799 .Case("allocWithZone", IFace)
4800 .Case("class", IFace)
4801 .Case("superclass", Super)
4802 .Default(0);
4803}
4804
Douglas Gregor6fc04132010-08-27 15:10:57 +00004805// Add a special completion for a message send to "super", which fills in the
4806// most likely case of forwarding all of our arguments to the superclass
4807// function.
4808///
4809/// \param S The semantic analysis object.
4810///
4811/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4812/// the "super" keyword. Otherwise, we just need to provide the arguments.
4813///
4814/// \param SelIdents The identifiers in the selector that have already been
4815/// provided as arguments for a send to "super".
4816///
4817/// \param NumSelIdents The number of identifiers in \p SelIdents.
4818///
4819/// \param Results The set of results to augment.
4820///
4821/// \returns the Objective-C method declaration that would be invoked by
4822/// this "super" completion. If NULL, no completion was added.
4823static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4824 IdentifierInfo **SelIdents,
4825 unsigned NumSelIdents,
4826 ResultBuilder &Results) {
4827 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4828 if (!CurMethod)
4829 return 0;
4830
4831 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4832 if (!Class)
4833 return 0;
4834
4835 // Try to find a superclass method with the same selector.
4836 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00004837 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4838 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00004839 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4840 CurMethod->isInstanceMethod());
4841
Douglas Gregorb5f1e462011-02-16 00:51:18 +00004842 // Check in categories or class extensions.
4843 if (!SuperMethod) {
4844 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4845 Category = Category->getNextClassCategory())
4846 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4847 CurMethod->isInstanceMethod())))
4848 break;
4849 }
4850 }
4851
Douglas Gregor6fc04132010-08-27 15:10:57 +00004852 if (!SuperMethod)
4853 return 0;
4854
4855 // Check whether the superclass method has the same signature.
4856 if (CurMethod->param_size() != SuperMethod->param_size() ||
4857 CurMethod->isVariadic() != SuperMethod->isVariadic())
4858 return 0;
4859
4860 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4861 CurPEnd = CurMethod->param_end(),
4862 SuperP = SuperMethod->param_begin();
4863 CurP != CurPEnd; ++CurP, ++SuperP) {
4864 // Make sure the parameter types are compatible.
4865 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4866 (*SuperP)->getType()))
4867 return 0;
4868
4869 // Make sure we have a parameter name to forward!
4870 if (!(*CurP)->getIdentifier())
4871 return 0;
4872 }
4873
4874 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004875 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor6fc04132010-08-27 15:10:57 +00004876
4877 // Give this completion a return type.
Douglas Gregor75acd922011-09-27 23:30:47 +00004878 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4879 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004880
4881 // If we need the "super" keyword, add it (plus some spacing).
4882 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004883 Builder.AddTypedTextChunk("super");
4884 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004885 }
4886
4887 Selector Sel = CurMethod->getSelector();
4888 if (Sel.isUnarySelector()) {
4889 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004890 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004891 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004892 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004893 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004894 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004895 } else {
4896 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4897 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4898 if (I > NumSelIdents)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004899 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00004900
4901 if (I < NumSelIdents)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004902 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004903 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004904 Sel.getNameForSlot(I) + ":"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004905 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004906 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004907 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004908 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004909 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004910 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004911 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004912 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004913 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00004914 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004915 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004916 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004917 }
4918 }
4919 }
4920
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004921 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor6fc04132010-08-27 15:10:57 +00004922 SuperMethod->isInstanceMethod()
4923 ? CXCursor_ObjCInstanceMethodDecl
4924 : CXCursor_ObjCClassMethodDecl));
4925 return SuperMethod;
4926}
4927
Douglas Gregora817a192010-05-27 23:06:34 +00004928void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00004929 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4931 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004932 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00004933
Douglas Gregora817a192010-05-27 23:06:34 +00004934 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4935 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00004936 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4937 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00004938
4939 // If we are in an Objective-C method inside a class that has a superclass,
4940 // add "super" as an option.
4941 if (ObjCMethodDecl *Method = getCurMethodDecl())
4942 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00004943 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00004944 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00004945
4946 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4947 }
Douglas Gregora817a192010-05-27 23:06:34 +00004948
4949 Results.ExitScope();
4950
4951 if (CodeCompleter->includeMacros())
4952 AddMacroResults(PP, Results);
Douglas Gregor50832e02010-09-20 22:39:41 +00004953 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004954 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00004955
4956}
4957
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004958void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4959 IdentifierInfo **SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004960 unsigned NumSelIdents,
4961 bool AtArgumentExpression) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004962 ObjCInterfaceDecl *CDecl = 0;
4963 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4964 // Figure out which interface we're in.
4965 CDecl = CurMethod->getClassInterface();
4966 if (!CDecl)
4967 return;
4968
4969 // Find the superclass of this class.
4970 CDecl = CDecl->getSuperClass();
4971 if (!CDecl)
4972 return;
4973
4974 if (CurMethod->isInstanceMethod()) {
4975 // We are inside an instance method, which means that the message
4976 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00004977 // current object.
4978 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor6fc04132010-08-27 15:10:57 +00004979 SelIdents, NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00004980 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00004981 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004982 }
4983
4984 // Fall through to send to the superclass in CDecl.
4985 } else {
4986 // "super" may be the name of a type or variable. Figure out which
4987 // it is.
4988 IdentifierInfo *Super = &Context.Idents.get("super");
4989 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4990 LookupOrdinaryName);
4991 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4992 // "super" names an interface. Use it.
4993 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00004994 if (const ObjCObjectType *Iface
4995 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4996 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00004997 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4998 // "super" names an unresolved type; we can't be more specific.
4999 } else {
5000 // Assume that "super" names some kind of value and parse that way.
5001 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005002 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005003 UnqualifiedId id;
5004 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005005 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5006 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005007 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005008 SelIdents, NumSelIdents,
5009 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005010 }
5011
5012 // Fall through
5013 }
5014
John McCallba7bf592010-08-24 05:47:05 +00005015 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005016 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005017 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005018 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005019 NumSelIdents, AtArgumentExpression,
5020 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005021}
5022
Douglas Gregor74661272010-09-21 00:03:25 +00005023/// \brief Given a set of code-completion results for the argument of a message
5024/// send, determine the preferred type (if any) for that argument expression.
5025static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5026 unsigned NumSelIdents) {
5027 typedef CodeCompletionResult Result;
5028 ASTContext &Context = Results.getSema().Context;
5029
5030 QualType PreferredType;
5031 unsigned BestPriority = CCP_Unlikely * 2;
5032 Result *ResultsData = Results.data();
5033 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5034 Result &R = ResultsData[I];
5035 if (R.Kind == Result::RK_Declaration &&
5036 isa<ObjCMethodDecl>(R.Declaration)) {
5037 if (R.Priority <= BestPriority) {
5038 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5039 if (NumSelIdents <= Method->param_size()) {
5040 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5041 ->getType();
5042 if (R.Priority < BestPriority || PreferredType.isNull()) {
5043 BestPriority = R.Priority;
5044 PreferredType = MyPreferredType;
5045 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5046 MyPreferredType)) {
5047 PreferredType = QualType();
5048 }
5049 }
5050 }
5051 }
5052 }
5053
5054 return PreferredType;
5055}
5056
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005057static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5058 ParsedType Receiver,
5059 IdentifierInfo **SelIdents,
5060 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005061 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005062 bool IsSuper,
5063 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005064 typedef CodeCompletionResult Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00005065 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005066
Douglas Gregor8ce33212009-11-17 17:59:40 +00005067 // If the given name refers to an interface type, retrieve the
5068 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005069 if (Receiver) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005070 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005071 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005072 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5073 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005074 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005075
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005076 // Add all of the factory methods in this Objective-C class, its protocols,
5077 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005078 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005079
Douglas Gregor6fc04132010-08-27 15:10:57 +00005080 // If this is a send-to-super, try to add the special "super" send
5081 // completion.
5082 if (IsSuper) {
5083 if (ObjCMethodDecl *SuperMethod
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005084 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5085 Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005086 Results.Ignore(SuperMethod);
5087 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005088
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005089 // If we're inside an Objective-C method definition, prefer its selector to
5090 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005091 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005092 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005093
Douglas Gregor1154e272010-09-16 16:06:31 +00005094 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005095 if (CDecl)
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005096 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005097 SemaRef.CurContext, Selectors, AtArgumentExpression,
5098 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005099 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005100 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005101
Douglas Gregord720daf2010-04-06 17:30:22 +00005102 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005103 // pool from the AST file.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005104 if (SemaRef.ExternalSource) {
5105 for (uint32_t I = 0,
5106 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005107 I != N; ++I) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005108 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5109 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005110 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005111
5112 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005113 }
5114 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005115
5116 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5117 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005118 M != MEnd; ++M) {
5119 for (ObjCMethodList *MethList = &M->second.second;
5120 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00005121 MethList = MethList->Next) {
5122 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5123 NumSelIdents))
5124 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005125
Douglas Gregor6285f752010-04-06 16:40:00 +00005126 Result R(MethList->Method, 0);
5127 R.StartParameter = NumSelIdents;
5128 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005129 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005130 }
5131 }
5132 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005133
5134 Results.ExitScope();
5135}
Douglas Gregor6285f752010-04-06 16:40:00 +00005136
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005137void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5138 IdentifierInfo **SelIdents,
5139 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005140 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005141 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005142
5143 QualType T = this->GetTypeFromParser(Receiver);
5144
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005145 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005146 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregorea777402011-07-26 15:24:30 +00005147 T, SelIdents, NumSelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005148
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005149 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5150 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005151
5152 // If we're actually at the argument expression (rather than prior to the
5153 // selector), we're actually performing code completion for an expression.
5154 // Determine whether we have a single, best method. If so, we can
5155 // code-complete the expression using the corresponding parameter type as
5156 // our preferred type, improving completion results.
5157 if (AtArgumentExpression) {
5158 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregor63745d52011-07-21 01:05:26 +00005159 NumSelIdents);
Douglas Gregor74661272010-09-21 00:03:25 +00005160 if (PreferredType.isNull())
5161 CodeCompleteOrdinaryName(S, PCC_Expression);
5162 else
5163 CodeCompleteExpression(S, PreferredType);
5164 return;
5165 }
5166
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005167 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005168 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005169 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005170}
5171
Richard Trieu2bd04012011-09-09 02:00:50 +00005172void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregor1b605f72009-11-19 01:08:35 +00005173 IdentifierInfo **SelIdents,
Douglas Gregor6fc04132010-08-27 15:10:57 +00005174 unsigned NumSelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005175 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005176 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005177 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005178
5179 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005180
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005181 // If necessary, apply function/array conversion to the receiver.
5182 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005183 if (RecExpr) {
5184 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5185 if (Conv.isInvalid()) // conversion failed. bail.
5186 return;
5187 RecExpr = Conv.take();
5188 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005189 QualType ReceiverType = RecExpr? RecExpr->getType()
5190 : Super? Context.getObjCObjectPointerType(
5191 Context.getObjCInterfaceType(Super))
5192 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005193
Douglas Gregordc520b02010-11-08 21:12:30 +00005194 // If we're messaging an expression with type "id" or "Class", check
5195 // whether we know something special about the receiver that allows
5196 // us to assume a more-specific receiver type.
5197 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5198 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5199 if (ReceiverType->isObjCClassType())
5200 return CodeCompleteObjCClassMessage(S,
5201 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5202 SelIdents, NumSelIdents,
5203 AtArgumentExpression, Super);
5204
5205 ReceiverType = Context.getObjCObjectPointerType(
5206 Context.getObjCInterfaceType(IFace));
5207 }
5208
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005209 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005210 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005211 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregorea777402011-07-26 15:24:30 +00005212 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005213
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005214 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005215
Douglas Gregor6fc04132010-08-27 15:10:57 +00005216 // If this is a send-to-super, try to add the special "super" send
5217 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005218 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005219 if (ObjCMethodDecl *SuperMethod
5220 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5221 Results))
5222 Results.Ignore(SuperMethod);
5223 }
5224
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005225 // If we're inside an Objective-C method definition, prefer its selector to
5226 // others.
5227 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5228 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005229
Douglas Gregor1154e272010-09-16 16:06:31 +00005230 // Keep track of the selectors we've already added.
5231 VisitedSelectorSet Selectors;
5232
Douglas Gregora3329fa2009-11-18 00:06:18 +00005233 // Handle messages to Class. This really isn't a message to an instance
5234 // method, so we treat it the same way we would treat a message send to a
5235 // class method.
5236 if (ReceiverType->isObjCClassType() ||
5237 ReceiverType->isObjCQualifiedClassType()) {
5238 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5239 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005240 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005241 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005242 }
5243 }
5244 // Handle messages to a qualified ID ("id<foo>").
5245 else if (const ObjCObjectPointerType *QualID
5246 = ReceiverType->getAsObjCQualifiedIdType()) {
5247 // Search protocols for instance methods.
5248 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5249 E = QualID->qual_end();
5250 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005251 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005252 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005253 }
5254 // Handle messages to a pointer to interface type.
5255 else if (const ObjCObjectPointerType *IFacePtr
5256 = ReceiverType->getAsObjCInterfacePointerType()) {
5257 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005258 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005259 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5260 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005261
5262 // Search protocols for instance methods.
5263 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5264 E = IFacePtr->qual_end();
5265 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005266 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005267 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005268 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005269 // Handle messages to "id".
5270 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005271 // We're messaging "id", so provide all instance methods we know
5272 // about as code-completion results.
5273
5274 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005275 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005276 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005277 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5278 I != N; ++I) {
5279 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005280 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005281 continue;
5282
Sebastian Redl75d8a322010-08-02 23:18:59 +00005283 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005284 }
5285 }
5286
Sebastian Redl75d8a322010-08-02 23:18:59 +00005287 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5288 MEnd = MethodPool.end();
5289 M != MEnd; ++M) {
5290 for (ObjCMethodList *MethList = &M->second.first;
5291 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00005292 MethList = MethList->Next) {
5293 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5294 NumSelIdents))
5295 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005296
5297 if (!Selectors.insert(MethList->Method->getSelector()))
5298 continue;
5299
Douglas Gregor6285f752010-04-06 16:40:00 +00005300 Result R(MethList->Method, 0);
5301 R.StartParameter = NumSelIdents;
5302 R.AllParametersAreInformative = false;
5303 Results.MaybeAddResult(R, CurContext);
5304 }
5305 }
5306 }
Steve Naroffeae65032009-11-07 02:08:14 +00005307 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005308
5309
5310 // If we're actually at the argument expression (rather than prior to the
5311 // selector), we're actually performing code completion for an expression.
5312 // Determine whether we have a single, best method. If so, we can
5313 // code-complete the expression using the corresponding parameter type as
5314 // our preferred type, improving completion results.
5315 if (AtArgumentExpression) {
5316 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5317 NumSelIdents);
5318 if (PreferredType.isNull())
5319 CodeCompleteOrdinaryName(S, PCC_Expression);
5320 else
5321 CodeCompleteExpression(S, PreferredType);
5322 return;
5323 }
5324
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005325 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005326 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005327 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005328}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005329
Douglas Gregor68762e72010-08-23 21:17:50 +00005330void Sema::CodeCompleteObjCForCollection(Scope *S,
5331 DeclGroupPtrTy IterationVar) {
5332 CodeCompleteExpressionData Data;
5333 Data.ObjCCollection = true;
5334
5335 if (IterationVar.getAsOpaquePtr()) {
5336 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5337 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5338 if (*I)
5339 Data.IgnoreDecls.push_back(*I);
5340 }
5341 }
5342
5343 CodeCompleteExpression(S, Data);
5344}
5345
Douglas Gregor67c692c2010-08-26 15:07:07 +00005346void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5347 unsigned NumSelIdents) {
5348 // If we have an external source, load the entire class method
5349 // pool from the AST file.
5350 if (ExternalSource) {
5351 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5352 I != N; ++I) {
5353 Selector Sel = ExternalSource->GetExternalSelector(I);
5354 if (Sel.isNull() || MethodPool.count(Sel))
5355 continue;
5356
5357 ReadMethodPool(Sel);
5358 }
5359 }
5360
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005361 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5362 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005363 Results.EnterNewScope();
5364 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5365 MEnd = MethodPool.end();
5366 M != MEnd; ++M) {
5367
5368 Selector Sel = M->first;
5369 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5370 continue;
5371
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005372 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005373 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005374 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005375 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005376 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005377 continue;
5378 }
5379
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005380 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005381 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005382 if (I == NumSelIdents) {
5383 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005384 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005385 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005386 Accumulator.clear();
5387 }
5388 }
5389
Benjamin Kramer632500c2011-07-26 16:59:25 +00005390 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005391 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005392 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005393 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005394 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005395 }
5396 Results.ExitScope();
5397
5398 HandleCodeCompleteResults(this, CodeCompleter,
5399 CodeCompletionContext::CCC_SelectorName,
5400 Results.data(), Results.size());
5401}
5402
Douglas Gregorbaf69612009-11-18 04:19:12 +00005403/// \brief Add all of the protocol declarations that we find in the given
5404/// (translation unit) context.
5405static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005406 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005407 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005408 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005409
5410 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5411 DEnd = Ctx->decls_end();
5412 D != DEnd; ++D) {
5413 // Record any protocols we find.
5414 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005415 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005416 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005417 }
5418}
5419
5420void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5421 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005422 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5423 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005424
Douglas Gregora3b23b02010-12-09 21:44:02 +00005425 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5426 Results.EnterNewScope();
5427
5428 // Tell the result set to ignore all of the protocols we have
5429 // already seen.
5430 // FIXME: This doesn't work when caching code-completion results.
5431 for (unsigned I = 0; I != NumProtocols; ++I)
5432 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5433 Protocols[I].second))
5434 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005435
Douglas Gregora3b23b02010-12-09 21:44:02 +00005436 // Add all protocols.
5437 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5438 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005439
Douglas Gregora3b23b02010-12-09 21:44:02 +00005440 Results.ExitScope();
5441 }
5442
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005443 HandleCodeCompleteResults(this, CodeCompleter,
5444 CodeCompletionContext::CCC_ObjCProtocolName,
5445 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005446}
5447
5448void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005449 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5450 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005451
Douglas Gregora3b23b02010-12-09 21:44:02 +00005452 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5453 Results.EnterNewScope();
5454
5455 // Add all protocols.
5456 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5457 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005458
Douglas Gregora3b23b02010-12-09 21:44:02 +00005459 Results.ExitScope();
5460 }
5461
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005462 HandleCodeCompleteResults(this, CodeCompleter,
5463 CodeCompletionContext::CCC_ObjCProtocolName,
5464 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005465}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005466
5467/// \brief Add all of the Objective-C interface declarations that we find in
5468/// the given (translation unit) context.
5469static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5470 bool OnlyForwardDeclarations,
5471 bool OnlyUnimplemented,
5472 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005473 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005474
5475 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5476 DEnd = Ctx->decls_end();
5477 D != DEnd; ++D) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005478 // Record any interfaces we find.
5479 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005480 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005481 (!OnlyUnimplemented || !Class->getImplementation()))
5482 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005483 }
5484}
5485
5486void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005487 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5488 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005489 Results.EnterNewScope();
5490
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005491 if (CodeCompleter->includeGlobals()) {
5492 // Add all classes.
5493 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5494 false, Results);
5495 }
5496
Douglas Gregor49c22a72009-11-18 16:26:39 +00005497 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005498
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005499 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005500 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005501 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005502}
5503
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005504void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5505 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005506 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005507 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005508 Results.EnterNewScope();
5509
5510 // Make sure that we ignore the class we're currently defining.
5511 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005512 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005513 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00005514 Results.Ignore(CurClass);
5515
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005516 if (CodeCompleter->includeGlobals()) {
5517 // Add all classes.
5518 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5519 false, Results);
5520 }
5521
Douglas Gregor49c22a72009-11-18 16:26:39 +00005522 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005523
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005524 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005525 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005526 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005527}
5528
5529void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005530 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5531 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005532 Results.EnterNewScope();
5533
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005534 if (CodeCompleter->includeGlobals()) {
5535 // Add all unimplemented classes.
5536 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5537 true, Results);
5538 }
5539
Douglas Gregor49c22a72009-11-18 16:26:39 +00005540 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005541
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005542 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005543 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005544 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005545}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005546
5547void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005548 IdentifierInfo *ClassName,
5549 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005550 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005551
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005552 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00005553 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005554
5555 // Ignore any categories we find that have already been implemented by this
5556 // interface.
5557 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5558 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005559 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005560 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5561 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5562 Category = Category->getNextClassCategory())
5563 CategoryNames.insert(Category->getIdentifier());
5564
5565 // Add all of the categories we know about.
5566 Results.EnterNewScope();
5567 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5568 for (DeclContext::decl_iterator D = TU->decls_begin(),
5569 DEnd = TU->decls_end();
5570 D != DEnd; ++D)
5571 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5572 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005573 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005574 Results.ExitScope();
5575
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005576 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005577 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005578 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005579}
5580
5581void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005582 IdentifierInfo *ClassName,
5583 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005584 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005585
5586 // Find the corresponding interface. If we couldn't find the interface, the
5587 // program itself is ill-formed. However, we'll try to be helpful still by
5588 // providing the list of all of the categories we know about.
5589 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005590 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005591 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5592 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005593 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005594
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005595 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor21325842011-07-07 16:03:39 +00005596 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005597
5598 // Add all of the categories that have have corresponding interface
5599 // declarations in this class and any of its superclasses, except for
5600 // already-implemented categories in the class itself.
5601 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5602 Results.EnterNewScope();
5603 bool IgnoreImplemented = true;
5604 while (Class) {
5605 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5606 Category = Category->getNextClassCategory())
5607 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5608 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00005609 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005610
5611 Class = Class->getSuperClass();
5612 IgnoreImplemented = false;
5613 }
5614 Results.ExitScope();
5615
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005616 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005617 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005618 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005619}
Douglas Gregor5d649882009-11-18 22:32:06 +00005620
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005621void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005622 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005623 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5624 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00005625
5626 // Figure out where this @synthesize lives.
5627 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005628 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00005629 if (!Container ||
5630 (!isa<ObjCImplementationDecl>(Container) &&
5631 !isa<ObjCCategoryImplDecl>(Container)))
5632 return;
5633
5634 // Ignore any properties that have already been implemented.
5635 for (DeclContext::decl_iterator D = Container->decls_begin(),
5636 DEnd = Container->decls_end();
5637 D != DEnd; ++D)
5638 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5639 Results.Ignore(PropertyImpl->getPropertyDecl());
5640
5641 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00005642 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00005643 Results.EnterNewScope();
5644 if (ObjCImplementationDecl *ClassImpl
5645 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor95147142011-05-05 15:50:42 +00005646 AddObjCProperties(ClassImpl->getClassInterface(), false,
5647 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00005648 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00005649 else
5650 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00005651 false, /*AllowNullaryMethods=*/false, CurContext,
5652 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00005653 Results.ExitScope();
5654
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005655 HandleCodeCompleteResults(this, CodeCompleter,
5656 CodeCompletionContext::CCC_Other,
5657 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00005658}
5659
5660void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005661 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00005662 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005663 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5664 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00005665
5666 // Figure out where this @synthesize lives.
5667 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005668 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00005669 if (!Container ||
5670 (!isa<ObjCImplementationDecl>(Container) &&
5671 !isa<ObjCCategoryImplDecl>(Container)))
5672 return;
5673
5674 // Figure out which interface we're looking into.
5675 ObjCInterfaceDecl *Class = 0;
5676 if (ObjCImplementationDecl *ClassImpl
5677 = dyn_cast<ObjCImplementationDecl>(Container))
5678 Class = ClassImpl->getClassInterface();
5679 else
5680 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5681 ->getClassInterface();
5682
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005683 // Determine the type of the property we're synthesizing.
5684 QualType PropertyType = Context.getObjCIdType();
5685 if (Class) {
5686 if (ObjCPropertyDecl *Property
5687 = Class->FindPropertyDeclaration(PropertyName)) {
5688 PropertyType
5689 = Property->getType().getNonReferenceType().getUnqualifiedType();
5690
5691 // Give preference to ivars
5692 Results.setPreferredType(PropertyType);
5693 }
5694 }
5695
Douglas Gregor5d649882009-11-18 22:32:06 +00005696 // Add all of the instance variables in this class and its superclasses.
5697 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00005698 bool SawSimilarlyNamedIvar = false;
5699 std::string NameWithPrefix;
5700 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00005701 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00005702 std::string NameWithSuffix = PropertyName->getName().str();
5703 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00005704 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00005705 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5706 Ivar = Ivar->getNextIvar()) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005707 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5708
Douglas Gregor331faa02011-04-18 14:13:53 +00005709 // Determine whether we've seen an ivar with a name similar to the
5710 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005711 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00005712 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005713 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00005714 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005715
5716 // Reduce the priority of this result by one, to give it a slight
5717 // advantage over other results whose names don't match so closely.
5718 if (Results.size() &&
5719 Results.data()[Results.size() - 1].Kind
5720 == CodeCompletionResult::RK_Declaration &&
5721 Results.data()[Results.size() - 1].Declaration == Ivar)
5722 Results.data()[Results.size() - 1].Priority--;
5723 }
Douglas Gregor331faa02011-04-18 14:13:53 +00005724 }
Douglas Gregor5d649882009-11-18 22:32:06 +00005725 }
Douglas Gregor331faa02011-04-18 14:13:53 +00005726
5727 if (!SawSimilarlyNamedIvar) {
5728 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005729 // an ivar of the appropriate type.
5730 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00005731 typedef CodeCompletionResult Result;
5732 CodeCompletionAllocator &Allocator = Results.getAllocator();
5733 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5734
Douglas Gregor75acd922011-09-27 23:30:47 +00005735 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00005736 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00005737 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00005738 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5739 Results.AddResult(Result(Builder.TakeString(), Priority,
5740 CXCursor_ObjCIvarDecl));
5741 }
5742
Douglas Gregor5d649882009-11-18 22:32:06 +00005743 Results.ExitScope();
5744
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005745 HandleCodeCompleteResults(this, CodeCompleter,
5746 CodeCompletionContext::CCC_Other,
5747 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00005748}
Douglas Gregor636a61e2010-04-07 00:21:17 +00005749
Douglas Gregor416b5752010-08-25 01:08:01 +00005750// Mapping from selectors to the methods that implement that selector, along
5751// with the "in original class" flag.
5752typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5753 KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00005754
5755/// \brief Find all of the methods that reside in the given container
5756/// (and its superclasses, protocols, etc.) that meet the given
5757/// criteria. Insert those methods into the map of known methods,
5758/// indexed by selector so they can be easily found.
5759static void FindImplementableMethods(ASTContext &Context,
5760 ObjCContainerDecl *Container,
5761 bool WantInstanceMethods,
5762 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00005763 KnownMethodsMap &KnownMethods,
5764 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00005765 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5766 // Recurse into protocols.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005767 if (!IFace->hasDefinition())
5768 return;
5769
Douglas Gregor636a61e2010-04-07 00:21:17 +00005770 const ObjCList<ObjCProtocolDecl> &Protocols
5771 = IFace->getReferencedProtocols();
5772 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005773 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00005774 I != E; ++I)
5775 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005776 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005777
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005778 // Add methods from any class extensions and categories.
5779 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5780 Cat = Cat->getNextClassCategory())
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00005781 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5782 WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005783 KnownMethods, false);
5784
5785 // Visit the superclass.
5786 if (IFace->getSuperClass())
5787 FindImplementableMethods(Context, IFace->getSuperClass(),
5788 WantInstanceMethods, ReturnType,
5789 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005790 }
5791
5792 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5793 // Recurse into protocols.
5794 const ObjCList<ObjCProtocolDecl> &Protocols
5795 = Category->getReferencedProtocols();
5796 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005797 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00005798 I != E; ++I)
5799 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00005800 KnownMethods, InOriginalClass);
5801
5802 // If this category is the original class, jump to the interface.
5803 if (InOriginalClass && Category->getClassInterface())
5804 FindImplementableMethods(Context, Category->getClassInterface(),
5805 WantInstanceMethods, ReturnType, KnownMethods,
5806 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005807 }
5808
5809 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005810 if (Protocol->hasDefinition()) {
5811 // Recurse into protocols.
5812 const ObjCList<ObjCProtocolDecl> &Protocols
5813 = Protocol->getReferencedProtocols();
5814 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5815 E = Protocols.end();
5816 I != E; ++I)
5817 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5818 KnownMethods, false);
5819 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00005820 }
5821
5822 // Add methods in this container. This operation occurs last because
5823 // we want the methods from this container to override any methods
5824 // we've previously seen with the same selector.
5825 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5826 MEnd = Container->meth_end();
5827 M != MEnd; ++M) {
5828 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5829 if (!ReturnType.isNull() &&
5830 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5831 continue;
5832
Douglas Gregor416b5752010-08-25 01:08:01 +00005833 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00005834 }
5835 }
5836}
5837
Douglas Gregor669a25a2011-02-17 00:22:45 +00005838/// \brief Add the parenthesized return or parameter type chunk to a code
5839/// completion string.
5840static void AddObjCPassingTypeChunk(QualType Type,
5841 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00005842 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00005843 CodeCompletionBuilder &Builder) {
5844 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor75acd922011-09-27 23:30:47 +00005845 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00005846 Builder.getAllocator()));
5847 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5848}
5849
5850/// \brief Determine whether the given class is or inherits from a class by
5851/// the given name.
5852static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005853 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005854 if (!Class)
5855 return false;
5856
5857 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5858 return true;
5859
5860 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5861}
5862
5863/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5864/// Key-Value Observing (KVO).
5865static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5866 bool IsInstanceMethod,
5867 QualType ReturnType,
5868 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005869 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00005870 ResultBuilder &Results) {
5871 IdentifierInfo *PropName = Property->getIdentifier();
5872 if (!PropName || PropName->getLength() == 0)
5873 return;
5874
Douglas Gregor75acd922011-09-27 23:30:47 +00005875 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5876
Douglas Gregor669a25a2011-02-17 00:22:45 +00005877 // Builder that will create each code completion.
5878 typedef CodeCompletionResult Result;
5879 CodeCompletionAllocator &Allocator = Results.getAllocator();
5880 CodeCompletionBuilder Builder(Allocator);
5881
5882 // The selector table.
5883 SelectorTable &Selectors = Context.Selectors;
5884
5885 // The property name, copied into the code completion allocation region
5886 // on demand.
5887 struct KeyHolder {
5888 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005889 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00005890 const char *CopiedKey;
5891
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005892 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor669a25a2011-02-17 00:22:45 +00005893 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5894
5895 operator const char *() {
5896 if (CopiedKey)
5897 return CopiedKey;
5898
5899 return CopiedKey = Allocator.CopyString(Key);
5900 }
5901 } Key(Allocator, PropName->getName());
5902
5903 // The uppercased name of the property name.
5904 std::string UpperKey = PropName->getName();
5905 if (!UpperKey.empty())
5906 UpperKey[0] = toupper(UpperKey[0]);
5907
5908 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5909 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5910 Property->getType());
5911 bool ReturnTypeMatchesVoid
5912 = ReturnType.isNull() || ReturnType->isVoidType();
5913
5914 // Add the normal accessor -(type)key.
5915 if (IsInstanceMethod &&
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005916 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00005917 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5918 if (ReturnType.isNull())
Douglas Gregor75acd922011-09-27 23:30:47 +00005919 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00005920
5921 Builder.AddTypedTextChunk(Key);
5922 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5923 CXCursor_ObjCInstanceMethodDecl));
5924 }
5925
5926 // If we have an integral or boolean property (or the user has provided
5927 // an integral or boolean return type), add the accessor -(type)isKey.
5928 if (IsInstanceMethod &&
5929 ((!ReturnType.isNull() &&
5930 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5931 (ReturnType.isNull() &&
5932 (Property->getType()->isIntegerType() ||
5933 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005934 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005935 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005936 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005937 if (ReturnType.isNull()) {
5938 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5939 Builder.AddTextChunk("BOOL");
5940 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5941 }
5942
5943 Builder.AddTypedTextChunk(
5944 Allocator.CopyString(SelectorId->getName()));
5945 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5946 CXCursor_ObjCInstanceMethodDecl));
5947 }
5948 }
5949
5950 // Add the normal mutator.
5951 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5952 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005953 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00005954 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00005955 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00005956 if (ReturnType.isNull()) {
5957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5958 Builder.AddTextChunk("void");
5959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5960 }
5961
5962 Builder.AddTypedTextChunk(
5963 Allocator.CopyString(SelectorId->getName()));
5964 Builder.AddTypedTextChunk(":");
Douglas Gregor75acd922011-09-27 23:30:47 +00005965 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00005966 Builder.AddTextChunk(Key);
5967 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5968 CXCursor_ObjCInstanceMethodDecl));
5969 }
5970 }
5971
5972 // Indexed and unordered accessors
5973 unsigned IndexedGetterPriority = CCP_CodePattern;
5974 unsigned IndexedSetterPriority = CCP_CodePattern;
5975 unsigned UnorderedGetterPriority = CCP_CodePattern;
5976 unsigned UnorderedSetterPriority = CCP_CodePattern;
5977 if (const ObjCObjectPointerType *ObjCPointer
5978 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5979 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5980 // If this interface type is not provably derived from a known
5981 // collection, penalize the corresponding completions.
5982 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5983 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5984 if (!InheritsFromClassNamed(IFace, "NSArray"))
5985 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5986 }
5987
5988 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5989 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5990 if (!InheritsFromClassNamed(IFace, "NSSet"))
5991 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5992 }
5993 }
5994 } else {
5995 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5996 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5997 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5998 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5999 }
6000
6001 // Add -(NSUInteger)countOf<key>
6002 if (IsInstanceMethod &&
6003 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006004 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006005 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006006 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006007 if (ReturnType.isNull()) {
6008 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6009 Builder.AddTextChunk("NSUInteger");
6010 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6011 }
6012
6013 Builder.AddTypedTextChunk(
6014 Allocator.CopyString(SelectorId->getName()));
6015 Results.AddResult(Result(Builder.TakeString(),
6016 std::min(IndexedGetterPriority,
6017 UnorderedGetterPriority),
6018 CXCursor_ObjCInstanceMethodDecl));
6019 }
6020 }
6021
6022 // Indexed getters
6023 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6024 if (IsInstanceMethod &&
6025 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006026 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006027 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006028 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006029 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006030 if (ReturnType.isNull()) {
6031 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6032 Builder.AddTextChunk("id");
6033 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6034 }
6035
6036 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6037 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6038 Builder.AddTextChunk("NSUInteger");
6039 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6040 Builder.AddTextChunk("index");
6041 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6042 CXCursor_ObjCInstanceMethodDecl));
6043 }
6044 }
6045
6046 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6047 if (IsInstanceMethod &&
6048 (ReturnType.isNull() ||
6049 (ReturnType->isObjCObjectPointerType() &&
6050 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6051 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6052 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006053 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006054 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006055 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006056 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006057 if (ReturnType.isNull()) {
6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6059 Builder.AddTextChunk("NSArray *");
6060 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6061 }
6062
6063 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6064 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6065 Builder.AddTextChunk("NSIndexSet *");
6066 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6067 Builder.AddTextChunk("indexes");
6068 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6069 CXCursor_ObjCInstanceMethodDecl));
6070 }
6071 }
6072
6073 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6074 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006075 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006076 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006077 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006078 &Context.Idents.get("range")
6079 };
6080
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006081 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006082 if (ReturnType.isNull()) {
6083 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6084 Builder.AddTextChunk("void");
6085 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6086 }
6087
6088 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6089 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6090 Builder.AddPlaceholderChunk("object-type");
6091 Builder.AddTextChunk(" **");
6092 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6093 Builder.AddTextChunk("buffer");
6094 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6095 Builder.AddTypedTextChunk("range:");
6096 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6097 Builder.AddTextChunk("NSRange");
6098 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6099 Builder.AddTextChunk("inRange");
6100 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6101 CXCursor_ObjCInstanceMethodDecl));
6102 }
6103 }
6104
6105 // Mutable indexed accessors
6106
6107 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6108 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006109 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006110 IdentifierInfo *SelectorIds[2] = {
6111 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006112 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006113 };
6114
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006115 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006116 if (ReturnType.isNull()) {
6117 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6118 Builder.AddTextChunk("void");
6119 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6120 }
6121
6122 Builder.AddTypedTextChunk("insertObject:");
6123 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6124 Builder.AddPlaceholderChunk("object-type");
6125 Builder.AddTextChunk(" *");
6126 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6127 Builder.AddTextChunk("object");
6128 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6129 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6130 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6131 Builder.AddPlaceholderChunk("NSUInteger");
6132 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6133 Builder.AddTextChunk("index");
6134 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6135 CXCursor_ObjCInstanceMethodDecl));
6136 }
6137 }
6138
6139 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6140 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006141 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006142 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006143 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006144 &Context.Idents.get("atIndexes")
6145 };
6146
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006147 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006148 if (ReturnType.isNull()) {
6149 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6150 Builder.AddTextChunk("void");
6151 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6152 }
6153
6154 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6155 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6156 Builder.AddTextChunk("NSArray *");
6157 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6158 Builder.AddTextChunk("array");
6159 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6160 Builder.AddTypedTextChunk("atIndexes:");
6161 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6162 Builder.AddPlaceholderChunk("NSIndexSet *");
6163 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6164 Builder.AddTextChunk("indexes");
6165 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6166 CXCursor_ObjCInstanceMethodDecl));
6167 }
6168 }
6169
6170 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6171 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006172 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006173 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006174 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006175 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006176 if (ReturnType.isNull()) {
6177 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6178 Builder.AddTextChunk("void");
6179 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6180 }
6181
6182 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6183 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6184 Builder.AddTextChunk("NSUInteger");
6185 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6186 Builder.AddTextChunk("index");
6187 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6188 CXCursor_ObjCInstanceMethodDecl));
6189 }
6190 }
6191
6192 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6193 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006194 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006195 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006196 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006197 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006198 if (ReturnType.isNull()) {
6199 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6200 Builder.AddTextChunk("void");
6201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6202 }
6203
6204 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6205 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6206 Builder.AddTextChunk("NSIndexSet *");
6207 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6208 Builder.AddTextChunk("indexes");
6209 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6210 CXCursor_ObjCInstanceMethodDecl));
6211 }
6212 }
6213
6214 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6215 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006216 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006217 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006218 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006219 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006220 &Context.Idents.get("withObject")
6221 };
6222
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006223 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006224 if (ReturnType.isNull()) {
6225 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6226 Builder.AddTextChunk("void");
6227 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6228 }
6229
6230 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6231 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6232 Builder.AddPlaceholderChunk("NSUInteger");
6233 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6234 Builder.AddTextChunk("index");
6235 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6236 Builder.AddTypedTextChunk("withObject:");
6237 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6238 Builder.AddTextChunk("id");
6239 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6240 Builder.AddTextChunk("object");
6241 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6242 CXCursor_ObjCInstanceMethodDecl));
6243 }
6244 }
6245
6246 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6247 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006248 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006249 = (Twine("replace") + UpperKey + "AtIndexes").str();
6250 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006251 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006252 &Context.Idents.get(SelectorName1),
6253 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006254 };
6255
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006256 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006257 if (ReturnType.isNull()) {
6258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6259 Builder.AddTextChunk("void");
6260 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6261 }
6262
6263 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6265 Builder.AddPlaceholderChunk("NSIndexSet *");
6266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6267 Builder.AddTextChunk("indexes");
6268 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6269 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6271 Builder.AddTextChunk("NSArray *");
6272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6273 Builder.AddTextChunk("array");
6274 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6275 CXCursor_ObjCInstanceMethodDecl));
6276 }
6277 }
6278
6279 // Unordered getters
6280 // - (NSEnumerator *)enumeratorOfKey
6281 if (IsInstanceMethod &&
6282 (ReturnType.isNull() ||
6283 (ReturnType->isObjCObjectPointerType() &&
6284 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6285 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6286 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006287 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006288 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006289 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006290 if (ReturnType.isNull()) {
6291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6292 Builder.AddTextChunk("NSEnumerator *");
6293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6294 }
6295
6296 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6297 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6298 CXCursor_ObjCInstanceMethodDecl));
6299 }
6300 }
6301
6302 // - (type *)memberOfKey:(type *)object
6303 if (IsInstanceMethod &&
6304 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006305 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006306 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006307 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006308 if (ReturnType.isNull()) {
6309 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6310 Builder.AddPlaceholderChunk("object-type");
6311 Builder.AddTextChunk(" *");
6312 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6313 }
6314
6315 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6316 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6317 if (ReturnType.isNull()) {
6318 Builder.AddPlaceholderChunk("object-type");
6319 Builder.AddTextChunk(" *");
6320 } else {
6321 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006322 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006323 Builder.getAllocator()));
6324 }
6325 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6326 Builder.AddTextChunk("object");
6327 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6328 CXCursor_ObjCInstanceMethodDecl));
6329 }
6330 }
6331
6332 // Mutable unordered accessors
6333 // - (void)addKeyObject:(type *)object
6334 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006335 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006336 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006337 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006338 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006339 if (ReturnType.isNull()) {
6340 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6341 Builder.AddTextChunk("void");
6342 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6343 }
6344
6345 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6346 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6347 Builder.AddPlaceholderChunk("object-type");
6348 Builder.AddTextChunk(" *");
6349 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6350 Builder.AddTextChunk("object");
6351 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6352 CXCursor_ObjCInstanceMethodDecl));
6353 }
6354 }
6355
6356 // - (void)addKey:(NSSet *)objects
6357 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006358 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006359 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006360 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006361 if (ReturnType.isNull()) {
6362 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6363 Builder.AddTextChunk("void");
6364 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6365 }
6366
6367 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6368 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6369 Builder.AddTextChunk("NSSet *");
6370 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6371 Builder.AddTextChunk("objects");
6372 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6373 CXCursor_ObjCInstanceMethodDecl));
6374 }
6375 }
6376
6377 // - (void)removeKeyObject:(type *)object
6378 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006379 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006380 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006381 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006382 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006383 if (ReturnType.isNull()) {
6384 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6385 Builder.AddTextChunk("void");
6386 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6387 }
6388
6389 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6390 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6391 Builder.AddPlaceholderChunk("object-type");
6392 Builder.AddTextChunk(" *");
6393 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6394 Builder.AddTextChunk("object");
6395 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6396 CXCursor_ObjCInstanceMethodDecl));
6397 }
6398 }
6399
6400 // - (void)removeKey:(NSSet *)objects
6401 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006402 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006403 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006404 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006405 if (ReturnType.isNull()) {
6406 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6407 Builder.AddTextChunk("void");
6408 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6409 }
6410
6411 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6412 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6413 Builder.AddTextChunk("NSSet *");
6414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6415 Builder.AddTextChunk("objects");
6416 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6417 CXCursor_ObjCInstanceMethodDecl));
6418 }
6419 }
6420
6421 // - (void)intersectKey:(NSSet *)objects
6422 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006423 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006424 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006425 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006426 if (ReturnType.isNull()) {
6427 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6428 Builder.AddTextChunk("void");
6429 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6430 }
6431
6432 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6433 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6434 Builder.AddTextChunk("NSSet *");
6435 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6436 Builder.AddTextChunk("objects");
6437 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6438 CXCursor_ObjCInstanceMethodDecl));
6439 }
6440 }
6441
6442 // Key-Value Observing
6443 // + (NSSet *)keyPathsForValuesAffectingKey
6444 if (!IsInstanceMethod &&
6445 (ReturnType.isNull() ||
6446 (ReturnType->isObjCObjectPointerType() &&
6447 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6448 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6449 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006450 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006451 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006452 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006453 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006454 if (ReturnType.isNull()) {
6455 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6456 Builder.AddTextChunk("NSSet *");
6457 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6458 }
6459
6460 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6461 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006462 CXCursor_ObjCClassMethodDecl));
6463 }
6464 }
6465
6466 // + (BOOL)automaticallyNotifiesObserversForKey
6467 if (!IsInstanceMethod &&
6468 (ReturnType.isNull() ||
6469 ReturnType->isIntegerType() ||
6470 ReturnType->isBooleanType())) {
6471 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006472 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00006473 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6474 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6475 if (ReturnType.isNull()) {
6476 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6477 Builder.AddTextChunk("BOOL");
6478 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6479 }
6480
6481 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6482 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6483 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00006484 }
6485 }
6486}
6487
Douglas Gregor636a61e2010-04-07 00:21:17 +00006488void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6489 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006490 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006491 // Determine the return type of the method we're declaring, if
6492 // provided.
6493 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006494 Decl *IDecl = 0;
6495 if (CurContext->isObjCContainer()) {
6496 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6497 IDecl = cast<Decl>(OCD);
6498 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006499 // Determine where we should start searching for methods.
6500 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006501 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00006502 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006503 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6504 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006505 IsInImplementation = true;
6506 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006507 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006508 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006509 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006510 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00006511 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006512 }
6513
6514 if (!SearchDecl && S) {
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006515 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006516 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006517 }
6518
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006519 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006520 HandleCodeCompleteResults(this, CodeCompleter,
6521 CodeCompletionContext::CCC_Other,
6522 0, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006523 return;
6524 }
6525
6526 // Find all of the methods that we could declare/implement here.
6527 KnownMethodsMap KnownMethods;
6528 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006529 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006530
Douglas Gregor636a61e2010-04-07 00:21:17 +00006531 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00006532 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006533 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6534 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006535 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00006536 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006537 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6538 MEnd = KnownMethods.end();
6539 M != MEnd; ++M) {
Douglas Gregor416b5752010-08-25 01:08:01 +00006540 ObjCMethodDecl *Method = M->second.first;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006541 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006542
6543 // If the result type was not already provided, add it to the
6544 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00006545 if (ReturnType.isNull())
Douglas Gregor75acd922011-09-27 23:30:47 +00006546 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6547 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006548
6549 Selector Sel = Method->getSelector();
6550
6551 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006552 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006553 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006554
6555 // Add parameters to the pattern.
6556 unsigned I = 0;
6557 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6558 PEnd = Method->param_end();
6559 P != PEnd; (void)++P, ++I) {
6560 // Add the part of the selector name.
6561 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006562 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006563 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6565 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006566 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006567 } else
6568 break;
6569
6570 // Add the parameter type.
Douglas Gregor75acd922011-09-27 23:30:47 +00006571 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6572 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006573
6574 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006575 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006576 }
6577
6578 if (Method->isVariadic()) {
6579 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006580 Builder.AddChunk(CodeCompletionString::CK_Comma);
6581 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00006582 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00006583
Douglas Gregord37c59d2010-05-28 00:57:46 +00006584 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006585 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006586 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6587 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6588 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006589 if (!Method->getResultType()->isVoidType()) {
6590 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006591 Builder.AddTextChunk("return");
6592 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6593 Builder.AddPlaceholderChunk("expression");
6594 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006595 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006596 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006597
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006598 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6599 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006600 }
6601
Douglas Gregor416b5752010-08-25 01:08:01 +00006602 unsigned Priority = CCP_CodePattern;
6603 if (!M->second.second)
6604 Priority += CCD_InBaseClass;
6605
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006606 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor7116a8c2010-08-17 16:06:07 +00006607 Method->isInstanceMethod()
6608 ? CXCursor_ObjCInstanceMethodDecl
6609 : CXCursor_ObjCClassMethodDecl));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006610 }
6611
Douglas Gregor669a25a2011-02-17 00:22:45 +00006612 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6613 // the properties in this class and its categories.
6614 if (Context.getLangOptions().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006615 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006616 Containers.push_back(SearchDecl);
6617
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006618 VisitedSelectorSet KnownSelectors;
6619 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6620 MEnd = KnownMethods.end();
6621 M != MEnd; ++M)
6622 KnownSelectors.insert(M->first);
6623
6624
Douglas Gregor669a25a2011-02-17 00:22:45 +00006625 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6626 if (!IFace)
6627 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6628 IFace = Category->getClassInterface();
6629
6630 if (IFace) {
6631 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6632 Category = Category->getNextClassCategory())
6633 Containers.push_back(Category);
6634 }
6635
6636 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6637 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6638 PEnd = Containers[I]->prop_end();
6639 P != PEnd; ++P) {
6640 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006641 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006642 }
6643 }
6644 }
6645
Douglas Gregor636a61e2010-04-07 00:21:17 +00006646 Results.ExitScope();
6647
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006648 HandleCodeCompleteResults(this, CodeCompleter,
6649 CodeCompletionContext::CCC_Other,
6650 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006651}
Douglas Gregor95887f92010-07-08 23:20:03 +00006652
6653void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6654 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00006655 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00006656 ParsedType ReturnTy,
Douglas Gregor95887f92010-07-08 23:20:03 +00006657 IdentifierInfo **SelIdents,
6658 unsigned NumSelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00006659 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006660 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00006661 if (ExternalSource) {
6662 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6663 I != N; ++I) {
6664 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006665 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00006666 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00006667
6668 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00006669 }
6670 }
6671
6672 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00006673 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006674 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6675 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00006676
6677 if (ReturnTy)
6678 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00006679
Douglas Gregor95887f92010-07-08 23:20:03 +00006680 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00006681 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6682 MEnd = MethodPool.end();
6683 M != MEnd; ++M) {
6684 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6685 &M->second.second;
6686 MethList && MethList->Method;
Douglas Gregor95887f92010-07-08 23:20:03 +00006687 MethList = MethList->Next) {
6688 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6689 NumSelIdents))
6690 continue;
6691
Douglas Gregor45879692010-07-08 23:37:41 +00006692 if (AtParameterName) {
6693 // Suggest parameter names we've seen before.
6694 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6695 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6696 if (Param->getIdentifier()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006697 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006698 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006699 Param->getIdentifier()->getName()));
6700 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00006701 }
6702 }
6703
6704 continue;
6705 }
6706
Douglas Gregor95887f92010-07-08 23:20:03 +00006707 Result R(MethList->Method, 0);
6708 R.StartParameter = NumSelIdents;
6709 R.AllParametersAreInformative = false;
6710 R.DeclaringEntity = true;
6711 Results.MaybeAddResult(R, CurContext);
6712 }
6713 }
6714
6715 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006716 HandleCodeCompleteResults(this, CodeCompleter,
6717 CodeCompletionContext::CCC_Other,
6718 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00006719}
Douglas Gregorb14904c2010-08-13 22:48:40 +00006720
Douglas Gregorec00a262010-08-24 22:20:20 +00006721void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006722 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006723 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006724 Results.EnterNewScope();
6725
6726 // #if <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006727 CodeCompletionBuilder Builder(Results.getAllocator());
6728 Builder.AddTypedTextChunk("if");
6729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6730 Builder.AddPlaceholderChunk("condition");
6731 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006732
6733 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006734 Builder.AddTypedTextChunk("ifdef");
6735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6736 Builder.AddPlaceholderChunk("macro");
6737 Results.AddResult(Builder.TakeString());
6738
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006739 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006740 Builder.AddTypedTextChunk("ifndef");
6741 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6742 Builder.AddPlaceholderChunk("macro");
6743 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006744
6745 if (InConditional) {
6746 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006747 Builder.AddTypedTextChunk("elif");
6748 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6749 Builder.AddPlaceholderChunk("condition");
6750 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006751
6752 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006753 Builder.AddTypedTextChunk("else");
6754 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006755
6756 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006757 Builder.AddTypedTextChunk("endif");
6758 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006759 }
6760
6761 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006762 Builder.AddTypedTextChunk("include");
6763 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6764 Builder.AddTextChunk("\"");
6765 Builder.AddPlaceholderChunk("header");
6766 Builder.AddTextChunk("\"");
6767 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006768
6769 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006770 Builder.AddTypedTextChunk("include");
6771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6772 Builder.AddTextChunk("<");
6773 Builder.AddPlaceholderChunk("header");
6774 Builder.AddTextChunk(">");
6775 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006776
6777 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006778 Builder.AddTypedTextChunk("define");
6779 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6780 Builder.AddPlaceholderChunk("macro");
6781 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006782
6783 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006784 Builder.AddTypedTextChunk("define");
6785 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6786 Builder.AddPlaceholderChunk("macro");
6787 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6788 Builder.AddPlaceholderChunk("args");
6789 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6790 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006791
6792 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006793 Builder.AddTypedTextChunk("undef");
6794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6795 Builder.AddPlaceholderChunk("macro");
6796 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006797
6798 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006799 Builder.AddTypedTextChunk("line");
6800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6801 Builder.AddPlaceholderChunk("number");
6802 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006803
6804 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006805 Builder.AddTypedTextChunk("line");
6806 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6807 Builder.AddPlaceholderChunk("number");
6808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6809 Builder.AddTextChunk("\"");
6810 Builder.AddPlaceholderChunk("filename");
6811 Builder.AddTextChunk("\"");
6812 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006813
6814 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006815 Builder.AddTypedTextChunk("error");
6816 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6817 Builder.AddPlaceholderChunk("message");
6818 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006819
6820 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006821 Builder.AddTypedTextChunk("pragma");
6822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6823 Builder.AddPlaceholderChunk("arguments");
6824 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006825
6826 if (getLangOptions().ObjC1) {
6827 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006828 Builder.AddTypedTextChunk("import");
6829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6830 Builder.AddTextChunk("\"");
6831 Builder.AddPlaceholderChunk("header");
6832 Builder.AddTextChunk("\"");
6833 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006834
6835 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006836 Builder.AddTypedTextChunk("import");
6837 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6838 Builder.AddTextChunk("<");
6839 Builder.AddPlaceholderChunk("header");
6840 Builder.AddTextChunk(">");
6841 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006842 }
6843
6844 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006845 Builder.AddTypedTextChunk("include_next");
6846 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6847 Builder.AddTextChunk("\"");
6848 Builder.AddPlaceholderChunk("header");
6849 Builder.AddTextChunk("\"");
6850 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006851
6852 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006853 Builder.AddTypedTextChunk("include_next");
6854 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6855 Builder.AddTextChunk("<");
6856 Builder.AddPlaceholderChunk("header");
6857 Builder.AddTextChunk(">");
6858 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006859
6860 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006861 Builder.AddTypedTextChunk("warning");
6862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6863 Builder.AddPlaceholderChunk("message");
6864 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006865
6866 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6867 // completions for them. And __include_macros is a Clang-internal extension
6868 // that we don't want to encourage anyone to use.
6869
6870 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6871 Results.ExitScope();
6872
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006873 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00006874 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006875 Results.data(), Results.size());
6876}
6877
6878void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00006879 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00006880 S->getFnParent()? Sema::PCC_RecoveryInFunction
6881 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00006882}
6883
Douglas Gregorec00a262010-08-24 22:20:20 +00006884void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006885 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006886 IsDefinition? CodeCompletionContext::CCC_MacroName
6887 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00006888 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6889 // Add just the names of macros, not their arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006890 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor12785102010-08-24 20:21:13 +00006891 Results.EnterNewScope();
6892 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6893 MEnd = PP.macro_end();
6894 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006895 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006896 M->first->getName()));
6897 Results.AddResult(Builder.TakeString());
Douglas Gregor12785102010-08-24 20:21:13 +00006898 }
6899 Results.ExitScope();
6900 } else if (IsDefinition) {
6901 // FIXME: Can we detect when the user just wrote an include guard above?
6902 }
6903
Douglas Gregor0ac41382010-09-23 23:01:17 +00006904 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00006905 Results.data(), Results.size());
6906}
6907
Douglas Gregorec00a262010-08-24 22:20:20 +00006908void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006909 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00006910 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00006911
6912 if (!CodeCompleter || CodeCompleter->includeMacros())
6913 AddMacroResults(PP, Results);
6914
6915 // defined (<macro>)
6916 Results.EnterNewScope();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006917 CodeCompletionBuilder Builder(Results.getAllocator());
6918 Builder.AddTypedTextChunk("defined");
6919 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6921 Builder.AddPlaceholderChunk("macro");
6922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6923 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00006924 Results.ExitScope();
6925
6926 HandleCodeCompleteResults(this, CodeCompleter,
6927 CodeCompletionContext::CCC_PreprocessorExpression,
6928 Results.data(), Results.size());
6929}
6930
6931void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6932 IdentifierInfo *Macro,
6933 MacroInfo *MacroInfo,
6934 unsigned Argument) {
6935 // FIXME: In the future, we could provide "overload" results, much like we
6936 // do for function calls.
6937
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00006938 // Now just ignore this. There will be another code-completion callback
6939 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00006940}
6941
Douglas Gregor11583702010-08-25 17:04:25 +00006942void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00006943 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00006944 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor11583702010-08-25 17:04:25 +00006945 0, 0);
6946}
6947
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006948void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006949 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006950 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00006951 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6952 CodeCompletionDeclConsumer Consumer(Builder,
6953 Context.getTranslationUnitDecl());
6954 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6955 Consumer);
6956 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00006957
6958 if (!CodeCompleter || CodeCompleter->includeMacros())
6959 AddMacroResults(PP, Builder);
6960
6961 Results.clear();
6962 Results.insert(Results.end(),
6963 Builder.data(), Builder.data() + Builder.size());
6964}