blob: e7a9a8d83865d04018bcb041019fcdffd3b7a5ef [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
65
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
437 llvm::SmallVector<DeclContext *, 4> TargetParents;
438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
589 case BuiltinType::UndeducedAuto:
590 return STC_Other;
591
592 case BuiltinType::ObjCId:
593 case BuiltinType::ObjCClass:
594 case BuiltinType::ObjCSel:
595 return STC_ObjectiveC;
596
597 default:
598 return STC_Arithmetic;
599 }
600 return STC_Other;
601
602 case Type::Complex:
603 return STC_Arithmetic;
604
605 case Type::Pointer:
606 return STC_Pointer;
607
608 case Type::BlockPointer:
609 return STC_Block;
610
611 case Type::LValueReference:
612 case Type::RValueReference:
613 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
614
615 case Type::ConstantArray:
616 case Type::IncompleteArray:
617 case Type::VariableArray:
618 case Type::DependentSizedArray:
619 return STC_Array;
620
621 case Type::DependentSizedExtVector:
622 case Type::Vector:
623 case Type::ExtVector:
624 return STC_Arithmetic;
625
626 case Type::FunctionProto:
627 case Type::FunctionNoProto:
628 return STC_Function;
629
630 case Type::Record:
631 return STC_Record;
632
633 case Type::Enum:
634 return STC_Arithmetic;
635
636 case Type::ObjCObject:
637 case Type::ObjCInterface:
638 case Type::ObjCObjectPointer:
639 return STC_ObjectiveC;
640
641 default:
642 return STC_Other;
643 }
644}
645
646/// \brief Get the type that a given expression will have if this declaration
647/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000648QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000649 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
650
651 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
652 return C.getTypeDeclType(Type);
653 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
654 return C.getObjCInterfaceType(Iface);
655
656 QualType T;
657 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000658 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000659 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000660 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000661 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000662 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000663 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
664 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
665 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
666 T = Property->getType();
667 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
668 T = Value->getType();
669 else
670 return QualType();
671
672 return T.getNonReferenceType();
673}
674
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000675void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
676 // If this is an Objective-C method declaration whose selector matches our
677 // preferred selector, give it a priority boost.
678 if (!PreferredSelector.isNull())
679 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
680 if (PreferredSelector == Method->getSelector())
681 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000682
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000683 // If we have a preferred type, adjust the priority for results with exactly-
684 // matching or nearly-matching types.
685 if (!PreferredType.isNull()) {
686 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
687 if (!T.isNull()) {
688 CanQualType TC = SemaRef.Context.getCanonicalType(T);
689 // Check for exactly-matching types (modulo qualifiers).
690 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
691 R.Priority /= CCF_ExactTypeMatch;
692 // Check for nearly-matching types, based on classification of each.
693 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000694 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000695 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
696 R.Priority /= CCF_SimilarTypeMatch;
697 }
698 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000699}
700
Douglas Gregor6f942b22010-09-21 16:06:22 +0000701void ResultBuilder::MaybeAddConstructorResults(Result R) {
702 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
703 !CompletionContext.wantConstructorResults())
704 return;
705
706 ASTContext &Context = SemaRef.Context;
707 NamedDecl *D = R.Declaration;
708 CXXRecordDecl *Record = 0;
709 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
710 Record = ClassTemplate->getTemplatedDecl();
711 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
712 // Skip specializations and partial specializations.
713 if (isa<ClassTemplateSpecializationDecl>(Record))
714 return;
715 } else {
716 // There are no constructors here.
717 return;
718 }
719
720 Record = Record->getDefinition();
721 if (!Record)
722 return;
723
724
725 QualType RecordTy = Context.getTypeDeclType(Record);
726 DeclarationName ConstructorName
727 = Context.DeclarationNames.getCXXConstructorName(
728 Context.getCanonicalType(RecordTy));
729 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
730 Ctors.first != Ctors.second; ++Ctors.first) {
731 R.Declaration = *Ctors.first;
732 R.CursorKind = getCursorKindForDecl(R.Declaration);
733 Results.push_back(R);
734 }
735}
736
Douglas Gregore495b7f2010-01-14 00:20:49 +0000737void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
738 assert(!ShadowMaps.empty() && "Must enter into a results scope");
739
740 if (R.Kind != Result::RK_Declaration) {
741 // For non-declaration results, just add the result.
742 Results.push_back(R);
743 return;
744 }
745
746 // Look through using declarations.
747 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
748 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
749 return;
750 }
751
752 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
753 unsigned IDNS = CanonDecl->getIdentifierNamespace();
754
Douglas Gregor45bcd432010-01-14 03:21:49 +0000755 bool AsNestedNameSpecifier = false;
756 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000757 return;
758
Douglas Gregor6f942b22010-09-21 16:06:22 +0000759 // C++ constructors are never found by name lookup.
760 if (isa<CXXConstructorDecl>(R.Declaration))
761 return;
762
Douglas Gregor86d9a522009-09-21 16:56:56 +0000763 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000764 ShadowMapEntry::iterator I, IEnd;
765 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
766 if (NamePos != SMap.end()) {
767 I = NamePos->second.begin();
768 IEnd = NamePos->second.end();
769 }
770
771 for (; I != IEnd; ++I) {
772 NamedDecl *ND = I->first;
773 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000774 if (ND->getCanonicalDecl() == CanonDecl) {
775 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000776 Results[Index].Declaration = R.Declaration;
777
Douglas Gregor86d9a522009-09-21 16:56:56 +0000778 // We're done.
779 return;
780 }
781 }
782
783 // This is a new declaration in this scope. However, check whether this
784 // declaration name is hidden by a similarly-named declaration in an outer
785 // scope.
786 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
787 --SMEnd;
788 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000789 ShadowMapEntry::iterator I, IEnd;
790 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
791 if (NamePos != SM->end()) {
792 I = NamePos->second.begin();
793 IEnd = NamePos->second.end();
794 }
795 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000796 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000797 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000798 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
799 Decl::IDNS_ObjCProtocol)))
800 continue;
801
802 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000803 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000805 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 continue;
807
808 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000809 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000810 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000811
812 break;
813 }
814 }
815
816 // Make sure that any given declaration only shows up in the result set once.
817 if (!AllDeclsFound.insert(CanonDecl))
818 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000819
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000820 // If the filter is for nested-name-specifiers, then this result starts a
821 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000822 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000823 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000824 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000825 } else
826 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000827
Douglas Gregor0563c262009-09-22 23:15:58 +0000828 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000829 if (R.QualifierIsInformative && !R.Qualifier &&
830 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000831 DeclContext *Ctx = R.Declaration->getDeclContext();
832 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
833 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
834 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
835 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
836 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
837 else
838 R.QualifierIsInformative = false;
839 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000840
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841 // Insert this result into the set of results and into the current shadow
842 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000843 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000844 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000845
846 if (!AsNestedNameSpecifier)
847 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000848}
849
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000850void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000851 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000852 if (R.Kind != Result::RK_Declaration) {
853 // For non-declaration results, just add the result.
854 Results.push_back(R);
855 return;
856 }
857
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000858 // Look through using declarations.
859 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
860 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
861 return;
862 }
863
Douglas Gregor45bcd432010-01-14 03:21:49 +0000864 bool AsNestedNameSpecifier = false;
865 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000866 return;
867
Douglas Gregor6f942b22010-09-21 16:06:22 +0000868 // C++ constructors are never found by name lookup.
869 if (isa<CXXConstructorDecl>(R.Declaration))
870 return;
871
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000872 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
873 return;
874
875 // Make sure that any given declaration only shows up in the result set once.
876 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
877 return;
878
879 // If the filter is for nested-name-specifiers, then this result starts a
880 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000881 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000882 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000883 R.Priority = CCP_NestedNameSpecifier;
884 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000885 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
886 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000887 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000888 R.QualifierIsInformative = true;
889
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000890 // If this result is supposed to have an informative qualifier, add one.
891 if (R.QualifierIsInformative && !R.Qualifier &&
892 !R.StartsNestedNameSpecifier) {
893 DeclContext *Ctx = R.Declaration->getDeclContext();
894 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
895 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
896 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
897 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000898 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000899 else
900 R.QualifierIsInformative = false;
901 }
902
Douglas Gregor12e13132010-05-26 22:00:08 +0000903 // Adjust the priority if this result comes from a base class.
904 if (InBaseClass)
905 R.Priority += CCD_InBaseClass;
906
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000907 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000908
Douglas Gregor3cdee122010-08-26 16:36:48 +0000909 if (HasObjectTypeQualifiers)
910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
911 if (Method->isInstance()) {
912 Qualifiers MethodQuals
913 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
914 if (ObjectTypeQualifiers == MethodQuals)
915 R.Priority += CCD_ObjectQualifierMatch;
916 else if (ObjectTypeQualifiers - MethodQuals) {
917 // The method cannot be invoked, because doing so would drop
918 // qualifiers.
919 return;
920 }
921 }
922
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000923 // Insert this result into the set of results.
924 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000925
926 if (!AsNestedNameSpecifier)
927 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000928}
929
Douglas Gregora4477812010-01-14 16:01:26 +0000930void ResultBuilder::AddResult(Result R) {
931 assert(R.Kind != Result::RK_Declaration &&
932 "Declaration results need more context");
933 Results.push_back(R);
934}
935
Douglas Gregor86d9a522009-09-21 16:56:56 +0000936/// \brief Enter into a new scope.
937void ResultBuilder::EnterNewScope() {
938 ShadowMaps.push_back(ShadowMap());
939}
940
941/// \brief Exit from the current scope.
942void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000943 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
944 EEnd = ShadowMaps.back().end();
945 E != EEnd;
946 ++E)
947 E->second.Destroy();
948
Douglas Gregor86d9a522009-09-21 16:56:56 +0000949 ShadowMaps.pop_back();
950}
951
Douglas Gregor791215b2009-09-21 20:51:25 +0000952/// \brief Determines whether this given declaration will be found by
953/// ordinary name lookup.
954bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000955 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
956
Douglas Gregor791215b2009-09-21 20:51:25 +0000957 unsigned IDNS = Decl::IDNS_Ordinary;
958 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000959 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000960 else if (SemaRef.getLangOptions().ObjC1) {
961 if (isa<ObjCIvarDecl>(ND))
962 return true;
963 if (isa<ObjCPropertyDecl>(ND) &&
964 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
965 return true;
966 }
967
Douglas Gregor791215b2009-09-21 20:51:25 +0000968 return ND->getIdentifierNamespace() & IDNS;
969}
970
Douglas Gregor01dfea02010-01-10 23:08:15 +0000971/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000972/// ordinary name lookup but is not a type name.
973bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
974 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
975 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
976 return false;
977
978 unsigned IDNS = Decl::IDNS_Ordinary;
979 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000980 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000981 else if (SemaRef.getLangOptions().ObjC1) {
982 if (isa<ObjCIvarDecl>(ND))
983 return true;
984 if (isa<ObjCPropertyDecl>(ND) &&
985 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
986 return true;
987 }
988
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000989 return ND->getIdentifierNamespace() & IDNS;
990}
991
Douglas Gregorf9578432010-07-28 21:50:18 +0000992bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
993 if (!IsOrdinaryNonTypeName(ND))
994 return 0;
995
996 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
997 if (VD->getType()->isIntegralOrEnumerationType())
998 return true;
999
1000 return false;
1001}
1002
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001003/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001004/// ordinary name lookup.
1005bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001006 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1007
Douglas Gregor01dfea02010-01-10 23:08:15 +00001008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001011
1012 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001013 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1014 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001015}
1016
Douglas Gregor86d9a522009-09-21 16:56:56 +00001017/// \brief Determines whether the given declaration is suitable as the
1018/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1019bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1020 // Allow us to find class templates, too.
1021 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1022 ND = ClassTemplate->getTemplatedDecl();
1023
1024 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1025}
1026
1027/// \brief Determines whether the given declaration is an enumeration.
1028bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1029 return isa<EnumDecl>(ND);
1030}
1031
1032/// \brief Determines whether the given declaration is a class or struct.
1033bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1034 // Allow us to find class templates, too.
1035 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1036 ND = ClassTemplate->getTemplatedDecl();
1037
1038 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001039 return RD->getTagKind() == TTK_Class ||
1040 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041
1042 return false;
1043}
1044
1045/// \brief Determines whether the given declaration is a union.
1046bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1047 // Allow us to find class templates, too.
1048 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1049 ND = ClassTemplate->getTemplatedDecl();
1050
1051 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001052 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001053
1054 return false;
1055}
1056
1057/// \brief Determines whether the given declaration is a namespace.
1058bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1059 return isa<NamespaceDecl>(ND);
1060}
1061
1062/// \brief Determines whether the given declaration is a namespace or
1063/// namespace alias.
1064bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1065 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1066}
1067
Douglas Gregor76282942009-12-11 17:31:05 +00001068/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001069bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001070 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1071 ND = Using->getTargetDecl();
1072
1073 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001074}
1075
Douglas Gregor76282942009-12-11 17:31:05 +00001076/// \brief Determines which members of a class should be visible via
1077/// "." or "->". Only value declarations, nested name specifiers, and
1078/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001079bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001080 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1081 ND = Using->getTargetDecl();
1082
Douglas Gregorce821962009-12-11 18:14:22 +00001083 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1084 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001085}
1086
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001087static bool isObjCReceiverType(ASTContext &C, QualType T) {
1088 T = C.getCanonicalType(T);
1089 switch (T->getTypeClass()) {
1090 case Type::ObjCObject:
1091 case Type::ObjCInterface:
1092 case Type::ObjCObjectPointer:
1093 return true;
1094
1095 case Type::Builtin:
1096 switch (cast<BuiltinType>(T)->getKind()) {
1097 case BuiltinType::ObjCId:
1098 case BuiltinType::ObjCClass:
1099 case BuiltinType::ObjCSel:
1100 return true;
1101
1102 default:
1103 break;
1104 }
1105 return false;
1106
1107 default:
1108 break;
1109 }
1110
1111 if (!C.getLangOptions().CPlusPlus)
1112 return false;
1113
1114 // FIXME: We could perform more analysis here to determine whether a
1115 // particular class type has any conversions to Objective-C types. For now,
1116 // just accept all class types.
1117 return T->isDependentType() || T->isRecordType();
1118}
1119
1120bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1121 QualType T = getDeclUsageType(SemaRef.Context, ND);
1122 if (T.isNull())
1123 return false;
1124
1125 T = SemaRef.Context.getBaseElementType(T);
1126 return isObjCReceiverType(SemaRef.Context, T);
1127}
1128
Douglas Gregorfb629412010-08-23 21:17:50 +00001129bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1130 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1131 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1132 return false;
1133
1134 QualType T = getDeclUsageType(SemaRef.Context, ND);
1135 if (T.isNull())
1136 return false;
1137
1138 T = SemaRef.Context.getBaseElementType(T);
1139 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1140 T->isObjCIdType() ||
1141 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1142}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001143
Douglas Gregor52779fb2010-09-23 23:01:17 +00001144bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1145 return false;
1146}
1147
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001148/// \rief Determines whether the given declaration is an Objective-C
1149/// instance variable.
1150bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1151 return isa<ObjCIvarDecl>(ND);
1152}
1153
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001154namespace {
1155 /// \brief Visible declaration consumer that adds a code-completion result
1156 /// for each visible declaration.
1157 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1158 ResultBuilder &Results;
1159 DeclContext *CurContext;
1160
1161 public:
1162 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1163 : Results(Results), CurContext(CurContext) { }
1164
Douglas Gregor0cc84042010-01-14 15:47:35 +00001165 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1166 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001167 }
1168 };
1169}
1170
Douglas Gregor86d9a522009-09-21 16:56:56 +00001171/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001172static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001173 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001174 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001175 Results.AddResult(Result("short", CCP_Type));
1176 Results.AddResult(Result("long", CCP_Type));
1177 Results.AddResult(Result("signed", CCP_Type));
1178 Results.AddResult(Result("unsigned", CCP_Type));
1179 Results.AddResult(Result("void", CCP_Type));
1180 Results.AddResult(Result("char", CCP_Type));
1181 Results.AddResult(Result("int", CCP_Type));
1182 Results.AddResult(Result("float", CCP_Type));
1183 Results.AddResult(Result("double", CCP_Type));
1184 Results.AddResult(Result("enum", CCP_Type));
1185 Results.AddResult(Result("struct", CCP_Type));
1186 Results.AddResult(Result("union", CCP_Type));
1187 Results.AddResult(Result("const", CCP_Type));
1188 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001189
Douglas Gregor86d9a522009-09-21 16:56:56 +00001190 if (LangOpts.C99) {
1191 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001192 Results.AddResult(Result("_Complex", CCP_Type));
1193 Results.AddResult(Result("_Imaginary", CCP_Type));
1194 Results.AddResult(Result("_Bool", CCP_Type));
1195 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001196 }
1197
Douglas Gregor218937c2011-02-01 19:23:04 +00001198 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001199 if (LangOpts.CPlusPlus) {
1200 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001201 Results.AddResult(Result("bool", CCP_Type +
1202 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001203 Results.AddResult(Result("class", CCP_Type));
1204 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001205
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001206 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001207 Builder.AddTypedTextChunk("typename");
1208 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1209 Builder.AddPlaceholderChunk("qualifier");
1210 Builder.AddTextChunk("::");
1211 Builder.AddPlaceholderChunk("name");
1212 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001213
Douglas Gregor86d9a522009-09-21 16:56:56 +00001214 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001215 Results.AddResult(Result("auto", CCP_Type));
1216 Results.AddResult(Result("char16_t", CCP_Type));
1217 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001218
Douglas Gregor218937c2011-02-01 19:23:04 +00001219 Builder.AddTypedTextChunk("decltype");
1220 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1221 Builder.AddPlaceholderChunk("expression");
1222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1223 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001224 }
1225 }
1226
1227 // GNU extensions
1228 if (LangOpts.GNUMode) {
1229 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001230 // Results.AddResult(Result("_Decimal32"));
1231 // Results.AddResult(Result("_Decimal64"));
1232 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001233
Douglas Gregor218937c2011-02-01 19:23:04 +00001234 Builder.AddTypedTextChunk("typeof");
1235 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1236 Builder.AddPlaceholderChunk("expression");
1237 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001238
Douglas Gregor218937c2011-02-01 19:23:04 +00001239 Builder.AddTypedTextChunk("typeof");
1240 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1241 Builder.AddPlaceholderChunk("type");
1242 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1243 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 }
1245}
1246
John McCallf312b1e2010-08-26 23:41:50 +00001247static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001248 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001249 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001250 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001251 // Note: we don't suggest either "auto" or "register", because both
1252 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1253 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001254 Results.AddResult(Result("extern"));
1255 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001256}
1257
John McCallf312b1e2010-08-26 23:41:50 +00001258static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001259 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001260 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001261 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001262 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001263 case Sema::PCC_Class:
1264 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001265 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001266 Results.AddResult(Result("explicit"));
1267 Results.AddResult(Result("friend"));
1268 Results.AddResult(Result("mutable"));
1269 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001270 }
1271 // Fall through
1272
John McCallf312b1e2010-08-26 23:41:50 +00001273 case Sema::PCC_ObjCInterface:
1274 case Sema::PCC_ObjCImplementation:
1275 case Sema::PCC_Namespace:
1276 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001277 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001278 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 break;
1280
John McCallf312b1e2010-08-26 23:41:50 +00001281 case Sema::PCC_ObjCInstanceVariableList:
1282 case Sema::PCC_Expression:
1283 case Sema::PCC_Statement:
1284 case Sema::PCC_ForInit:
1285 case Sema::PCC_Condition:
1286 case Sema::PCC_RecoveryInFunction:
1287 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001288 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001289 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 break;
1291 }
1292}
1293
Douglas Gregorbca403c2010-01-13 23:51:12 +00001294static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1295static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1296static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001297 ResultBuilder &Results,
1298 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001299static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001300 ResultBuilder &Results,
1301 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001302static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001303 ResultBuilder &Results,
1304 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001305static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001306
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001307static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001308 CodeCompletionBuilder Builder(Results.getAllocator());
1309 Builder.AddTypedTextChunk("typedef");
1310 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1311 Builder.AddPlaceholderChunk("type");
1312 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1313 Builder.AddPlaceholderChunk("name");
1314 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001315}
1316
John McCallf312b1e2010-08-26 23:41:50 +00001317static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001318 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001319 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001320 case Sema::PCC_Namespace:
1321 case Sema::PCC_Class:
1322 case Sema::PCC_ObjCInstanceVariableList:
1323 case Sema::PCC_Template:
1324 case Sema::PCC_MemberTemplate:
1325 case Sema::PCC_Statement:
1326 case Sema::PCC_RecoveryInFunction:
1327 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001328 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001329 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001330 return true;
1331
John McCallf312b1e2010-08-26 23:41:50 +00001332 case Sema::PCC_Expression:
1333 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001334 return LangOpts.CPlusPlus;
1335
1336 case Sema::PCC_ObjCInterface:
1337 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001338 return false;
1339
John McCallf312b1e2010-08-26 23:41:50 +00001340 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001341 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001342 }
1343
1344 return false;
1345}
1346
Douglas Gregor01dfea02010-01-10 23:08:15 +00001347/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001348static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001349 Scope *S,
1350 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001351 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001352 CodeCompletionBuilder Builder(Results.getAllocator());
1353
John McCall0a2c5e22010-08-25 06:19:51 +00001354 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001355 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001356 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001357 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001358 if (Results.includeCodePatterns()) {
1359 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001360 Builder.AddTypedTextChunk("namespace");
1361 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1362 Builder.AddPlaceholderChunk("identifier");
1363 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1364 Builder.AddPlaceholderChunk("declarations");
1365 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1366 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1367 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001368 }
1369
Douglas Gregor01dfea02010-01-10 23:08:15 +00001370 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001371 Builder.AddTypedTextChunk("namespace");
1372 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1373 Builder.AddPlaceholderChunk("name");
1374 Builder.AddChunk(CodeCompletionString::CK_Equal);
1375 Builder.AddPlaceholderChunk("namespace");
1376 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377
1378 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001379 Builder.AddTypedTextChunk("using");
1380 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1381 Builder.AddTextChunk("namespace");
1382 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1383 Builder.AddPlaceholderChunk("identifier");
1384 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001385
1386 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001387 Builder.AddTypedTextChunk("asm");
1388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1389 Builder.AddPlaceholderChunk("string-literal");
1390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1391 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001392
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001393 if (Results.includeCodePatterns()) {
1394 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001395 Builder.AddTypedTextChunk("template");
1396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1397 Builder.AddPlaceholderChunk("declaration");
1398 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001399 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001400 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001401
1402 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001403 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001404
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001405 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001406 // Fall through
1407
John McCallf312b1e2010-08-26 23:41:50 +00001408 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001409 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001410 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("using");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("qualifier");
1414 Builder.AddTextChunk("::");
1415 Builder.AddPlaceholderChunk("name");
1416 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001417
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001418 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001419 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001420 Builder.AddTypedTextChunk("using");
1421 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1422 Builder.AddTextChunk("typename");
1423 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1424 Builder.AddPlaceholderChunk("qualifier");
1425 Builder.AddTextChunk("::");
1426 Builder.AddPlaceholderChunk("name");
1427 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001428 }
1429
John McCallf312b1e2010-08-26 23:41:50 +00001430 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001431 AddTypedefResult(Results);
1432
Douglas Gregor01dfea02010-01-10 23:08:15 +00001433 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001434 Builder.AddTypedTextChunk("public");
1435 Builder.AddChunk(CodeCompletionString::CK_Colon);
1436 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001437
1438 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001439 Builder.AddTypedTextChunk("protected");
1440 Builder.AddChunk(CodeCompletionString::CK_Colon);
1441 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001442
1443 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001444 Builder.AddTypedTextChunk("private");
1445 Builder.AddChunk(CodeCompletionString::CK_Colon);
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447 }
1448 }
1449 // Fall through
1450
John McCallf312b1e2010-08-26 23:41:50 +00001451 case Sema::PCC_Template:
1452 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001453 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001454 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001455 Builder.AddTypedTextChunk("template");
1456 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1457 Builder.AddPlaceholderChunk("parameters");
1458 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1459 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460 }
1461
Douglas Gregorbca403c2010-01-13 23:51:12 +00001462 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1463 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001464 break;
1465
John McCallf312b1e2010-08-26 23:41:50 +00001466 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001467 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1468 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1469 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001470 break;
1471
John McCallf312b1e2010-08-26 23:41:50 +00001472 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001473 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1474 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1475 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001476 break;
1477
John McCallf312b1e2010-08-26 23:41:50 +00001478 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001479 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001480 break;
1481
John McCallf312b1e2010-08-26 23:41:50 +00001482 case Sema::PCC_RecoveryInFunction:
1483 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001484 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001485
Douglas Gregord8e8a582010-05-25 21:41:55 +00001486 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001487 Builder.AddTypedTextChunk("try");
1488 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1489 Builder.AddPlaceholderChunk("statements");
1490 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1491 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1492 Builder.AddTextChunk("catch");
1493 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1494 Builder.AddPlaceholderChunk("declaration");
1495 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1496 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1497 Builder.AddPlaceholderChunk("statements");
1498 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1499 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1500 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001501 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001502 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001504
Douglas Gregord8e8a582010-05-25 21:41:55 +00001505 if (Results.includeCodePatterns()) {
1506 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001507 Builder.AddTypedTextChunk("if");
1508 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001509 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001510 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001511 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001512 Builder.AddPlaceholderChunk("expression");
1513 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1514 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1515 Builder.AddPlaceholderChunk("statements");
1516 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1517 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1518 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001519
Douglas Gregord8e8a582010-05-25 21:41:55 +00001520 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001521 Builder.AddTypedTextChunk("switch");
1522 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001523 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001524 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001525 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001526 Builder.AddPlaceholderChunk("expression");
1527 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1528 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1531 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001532 }
1533
Douglas Gregor01dfea02010-01-10 23:08:15 +00001534 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001535 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001537 Builder.AddTypedTextChunk("case");
1538 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1539 Builder.AddPlaceholderChunk("expression");
1540 Builder.AddChunk(CodeCompletionString::CK_Colon);
1541 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001542
1543 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001544 Builder.AddTypedTextChunk("default");
1545 Builder.AddChunk(CodeCompletionString::CK_Colon);
1546 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001547 }
1548
Douglas Gregord8e8a582010-05-25 21:41:55 +00001549 if (Results.includeCodePatterns()) {
1550 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001551 Builder.AddTypedTextChunk("while");
1552 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001553 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001554 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001555 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001556 Builder.AddPlaceholderChunk("expression");
1557 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1558 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1559 Builder.AddPlaceholderChunk("statements");
1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563
1564 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001565 Builder.AddTypedTextChunk("do");
1566 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1567 Builder.AddPlaceholderChunk("statements");
1568 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1569 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1570 Builder.AddTextChunk("while");
1571 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1572 Builder.AddPlaceholderChunk("expression");
1573 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1574 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001575
Douglas Gregord8e8a582010-05-25 21:41:55 +00001576 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001577 Builder.AddTypedTextChunk("for");
1578 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001579 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001580 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001581 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddPlaceholderChunk("init-expression");
1583 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1584 Builder.AddPlaceholderChunk("condition");
1585 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1586 Builder.AddPlaceholderChunk("inc-expression");
1587 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1588 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1589 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001594 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001595
1596 if (S->getContinueParent()) {
1597 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001598 Builder.AddTypedTextChunk("continue");
1599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001600 }
1601
1602 if (S->getBreakParent()) {
1603 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001604 Builder.AddTypedTextChunk("break");
1605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606 }
1607
1608 // "return expression ;" or "return ;", depending on whether we
1609 // know the function is void or not.
1610 bool isVoid = false;
1611 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1612 isVoid = Function->getResultType()->isVoidType();
1613 else if (ObjCMethodDecl *Method
1614 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1615 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001616 else if (SemaRef.getCurBlock() &&
1617 !SemaRef.getCurBlock()->ReturnType.isNull())
1618 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001619 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001620 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001621 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1622 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001623 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001625
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001626 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001627 Builder.AddTypedTextChunk("goto");
1628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1629 Builder.AddPlaceholderChunk("label");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001632 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001633 Builder.AddTypedTextChunk("using");
1634 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1635 Builder.AddTextChunk("namespace");
1636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1637 Builder.AddPlaceholderChunk("identifier");
1638 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001639 }
1640
1641 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001642 case Sema::PCC_ForInit:
1643 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001644 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001645 // Fall through: conditions and statements can have expressions.
1646
Douglas Gregor02688102010-09-14 23:59:36 +00001647 case Sema::PCC_ParenthesizedExpression:
John McCallf312b1e2010-08-26 23:41:50 +00001648 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001649 if (SemaRef.getLangOptions().CPlusPlus) {
1650 // 'this', if we're in a non-static member function.
1651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1652 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001653 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001654
1655 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001656 Results.AddResult(Result("true"));
1657 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001658
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001659 // dynamic_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001660 Builder.AddTypedTextChunk("dynamic_cast");
1661 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1662 Builder.AddPlaceholderChunk("type");
1663 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1664 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1665 Builder.AddPlaceholderChunk("expression");
1666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1667 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001668
1669 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001670 Builder.AddTypedTextChunk("static_cast");
1671 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1672 Builder.AddPlaceholderChunk("type");
1673 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1674 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1675 Builder.AddPlaceholderChunk("expression");
1676 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1677 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001678
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001679 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001680 Builder.AddTypedTextChunk("reinterpret_cast");
1681 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1682 Builder.AddPlaceholderChunk("type");
1683 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1684 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1685 Builder.AddPlaceholderChunk("expression");
1686 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1687 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001688
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001689 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001690 Builder.AddTypedTextChunk("const_cast");
1691 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1692 Builder.AddPlaceholderChunk("type");
1693 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1694 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1695 Builder.AddPlaceholderChunk("expression");
1696 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1697 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001698
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001699 // typeid ( expression-or-type )
Douglas Gregor218937c2011-02-01 19:23:04 +00001700 Builder.AddTypedTextChunk("typeid");
1701 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1702 Builder.AddPlaceholderChunk("expression-or-type");
1703 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001705
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001706 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001707 Builder.AddTypedTextChunk("new");
1708 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1709 Builder.AddPlaceholderChunk("type");
1710 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1711 Builder.AddPlaceholderChunk("expressions");
1712 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1713 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001714
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001715 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001716 Builder.AddTypedTextChunk("new");
1717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1718 Builder.AddPlaceholderChunk("type");
1719 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1720 Builder.AddPlaceholderChunk("size");
1721 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1722 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1723 Builder.AddPlaceholderChunk("expressions");
1724 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1725 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001726
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001727 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001728 Builder.AddTypedTextChunk("delete");
1729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1730 Builder.AddPlaceholderChunk("expression");
1731 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001732
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001733 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001734 Builder.AddTypedTextChunk("delete");
1735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1736 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1737 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1738 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1739 Builder.AddPlaceholderChunk("expression");
1740 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001741
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001742 // throw expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001743 Builder.AddTypedTextChunk("throw");
1744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1745 Builder.AddPlaceholderChunk("expression");
1746 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor12e13132010-05-26 22:00:08 +00001747
1748 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749 }
1750
1751 if (SemaRef.getLangOptions().ObjC1) {
1752 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001753 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1754 // The interface can be NULL.
1755 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1756 if (ID->getSuperClass())
1757 Results.AddResult(Result("super"));
1758 }
1759
Douglas Gregorbca403c2010-01-13 23:51:12 +00001760 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001761 }
1762
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001763 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001764 Builder.AddTypedTextChunk("sizeof");
1765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1766 Builder.AddPlaceholderChunk("expression-or-type");
1767 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1768 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001769 break;
1770 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001771
John McCallf312b1e2010-08-26 23:41:50 +00001772 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001773 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001774 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001775 }
1776
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001777 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1778 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001779
John McCallf312b1e2010-08-26 23:41:50 +00001780 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001781 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001782}
1783
Douglas Gregora63f6de2011-02-01 21:15:40 +00001784/// \brief Retrieve the string representation of the given type as a string
1785/// that has the appropriate lifetime for code completion.
1786///
1787/// This routine provides a fast path where we provide constant strings for
1788/// common type names.
1789const char *GetCompletionTypeString(QualType T,
1790 ASTContext &Context,
Douglas Gregordae68752011-02-01 22:57:45 +00001791 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001792 PrintingPolicy Policy(Context.PrintingPolicy);
1793 Policy.AnonymousTagLocations = false;
1794
1795 if (!T.getLocalQualifiers()) {
1796 // Built-in type names are constant strings.
1797 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1798 return BT->getName(Context.getLangOptions());
1799
1800 // Anonymous tag types are constant strings.
1801 if (const TagType *TagT = dyn_cast<TagType>(T))
1802 if (TagDecl *Tag = TagT->getDecl())
1803 if (!Tag->getIdentifier() && !Tag->getTypedefForAnonDecl()) {
1804 switch (Tag->getTagKind()) {
1805 case TTK_Struct: return "struct <anonymous>";
1806 case TTK_Class: return "class <anonymous>";
1807 case TTK_Union: return "union <anonymous>";
1808 case TTK_Enum: return "enum <anonymous>";
1809 }
1810 }
1811 }
1812
1813 // Slow path: format the type as a string.
1814 std::string Result;
1815 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001816 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001817}
1818
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001819/// \brief If the given declaration has an associated type, add it as a result
1820/// type chunk.
1821static void AddResultTypeChunk(ASTContext &Context,
1822 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001823 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001824 if (!ND)
1825 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001826
1827 // Skip constructors and conversion functions, which have their return types
1828 // built into their names.
1829 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1830 return;
1831
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001832 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001833 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001834 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1835 T = Function->getResultType();
1836 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1837 T = Method->getResultType();
1838 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1839 T = FunTmpl->getTemplatedDecl()->getResultType();
1840 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1841 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1842 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1843 /* Do nothing: ignore unresolved using declarations*/
1844 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1845 T = Value->getType();
1846 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1847 T = Property->getType();
1848
1849 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1850 return;
1851
Douglas Gregora63f6de2011-02-01 21:15:40 +00001852 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1853 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001854}
1855
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001856static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001857 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001858 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1859 if (Sentinel->getSentinel() == 0) {
1860 if (Context.getLangOptions().ObjC1 &&
1861 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001862 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001863 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001864 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001865 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001866 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001867 }
1868}
1869
Douglas Gregor83482d12010-08-24 16:15:59 +00001870static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001871 ParmVarDecl *Param,
1872 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001873 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1874 if (Param->getType()->isDependentType() ||
1875 !Param->getType()->isBlockPointerType()) {
1876 // The argument for a dependent or non-block parameter is a placeholder
1877 // containing that parameter's type.
1878 std::string Result;
1879
Douglas Gregoraba48082010-08-29 19:47:46 +00001880 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001881 Result = Param->getIdentifier()->getName();
1882
1883 Param->getType().getAsStringInternal(Result,
1884 Context.PrintingPolicy);
1885
1886 if (ObjCMethodParam) {
1887 Result = "(" + Result;
1888 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001889 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001890 Result += Param->getIdentifier()->getName();
1891 }
1892 return Result;
1893 }
1894
1895 // The argument for a block pointer parameter is a block literal with
1896 // the appropriate type.
1897 FunctionProtoTypeLoc *Block = 0;
1898 TypeLoc TL;
1899 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1900 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1901 while (true) {
1902 // Look through typedefs.
1903 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1904 if (TypeSourceInfo *InnerTSInfo
1905 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1906 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1907 continue;
1908 }
1909 }
1910
1911 // Look through qualified types
1912 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1913 TL = QualifiedTL->getUnqualifiedLoc();
1914 continue;
1915 }
1916
1917 // Try to get the function prototype behind the block pointer type,
1918 // then we're done.
1919 if (BlockPointerTypeLoc *BlockPtr
1920 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00001921 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor83482d12010-08-24 16:15:59 +00001922 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1923 }
1924 break;
1925 }
1926 }
1927
1928 if (!Block) {
1929 // We were unable to find a FunctionProtoTypeLoc with parameter names
1930 // for the block; just use the parameter type as a placeholder.
1931 std::string Result;
1932 Param->getType().getUnqualifiedType().
1933 getAsStringInternal(Result, Context.PrintingPolicy);
1934
1935 if (ObjCMethodParam) {
1936 Result = "(" + Result;
1937 Result += ")";
1938 if (Param->getIdentifier())
1939 Result += Param->getIdentifier()->getName();
1940 }
1941
1942 return Result;
1943 }
1944
1945 // We have the function prototype behind the block pointer type, as it was
1946 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001947 std::string Result;
1948 QualType ResultType = Block->getTypePtr()->getResultType();
1949 if (!ResultType->isVoidType())
1950 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1951
1952 Result = '^' + Result;
1953 if (Block->getNumArgs() == 0) {
1954 if (Block->getTypePtr()->isVariadic())
1955 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001956 else
1957 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00001958 } else {
1959 Result += "(";
1960 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1961 if (I)
1962 Result += ", ";
1963 Result += FormatFunctionParameter(Context, Block->getArg(I));
1964
1965 if (I == N - 1 && Block->getTypePtr()->isVariadic())
1966 Result += ", ...";
1967 }
1968 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00001969 }
Douglas Gregor38276252010-09-08 22:47:51 +00001970
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001971 if (Param->getIdentifier())
1972 Result += Param->getIdentifier()->getName();
1973
Douglas Gregor83482d12010-08-24 16:15:59 +00001974 return Result;
1975}
1976
Douglas Gregor86d9a522009-09-21 16:56:56 +00001977/// \brief Add function parameter chunks to the given code completion string.
1978static void AddFunctionParameterChunks(ASTContext &Context,
1979 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00001980 CodeCompletionBuilder &Result,
1981 unsigned Start = 0,
1982 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001983 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00001984 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001985
Douglas Gregor218937c2011-02-01 19:23:04 +00001986 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001987 ParmVarDecl *Param = Function->getParamDecl(P);
1988
Douglas Gregor218937c2011-02-01 19:23:04 +00001989 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001990 // When we see an optional default argument, put that argument and
1991 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00001992 CodeCompletionBuilder Opt(Result.getAllocator());
1993 if (!FirstParameter)
1994 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
1995 AddFunctionParameterChunks(Context, Function, Opt, P, true);
1996 Result.AddOptionalChunk(Opt.TakeString());
1997 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001998 }
1999
Douglas Gregor218937c2011-02-01 19:23:04 +00002000 if (FirstParameter)
2001 FirstParameter = false;
2002 else
2003 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2004
2005 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002006
2007 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002008 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2009
Douglas Gregore17794f2010-08-31 05:13:43 +00002010 if (Function->isVariadic() && P == N - 1)
2011 PlaceholderStr += ", ...";
2012
Douglas Gregor86d9a522009-09-21 16:56:56 +00002013 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002014 Result.AddPlaceholderChunk(
2015 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002016 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002017
2018 if (const FunctionProtoType *Proto
2019 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002020 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002021 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002022 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002023
Douglas Gregor218937c2011-02-01 19:23:04 +00002024 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002025 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002026}
2027
2028/// \brief Add template parameter chunks to the given code completion string.
2029static void AddTemplateParameterChunks(ASTContext &Context,
2030 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002031 CodeCompletionBuilder &Result,
2032 unsigned MaxParameters = 0,
2033 unsigned Start = 0,
2034 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002035 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002036 bool FirstParameter = true;
2037
2038 TemplateParameterList *Params = Template->getTemplateParameters();
2039 TemplateParameterList::iterator PEnd = Params->end();
2040 if (MaxParameters)
2041 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002042 for (TemplateParameterList::iterator P = Params->begin() + Start;
2043 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002044 bool HasDefaultArg = false;
2045 std::string PlaceholderStr;
2046 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2047 if (TTP->wasDeclaredWithTypename())
2048 PlaceholderStr = "typename";
2049 else
2050 PlaceholderStr = "class";
2051
2052 if (TTP->getIdentifier()) {
2053 PlaceholderStr += ' ';
2054 PlaceholderStr += TTP->getIdentifier()->getName();
2055 }
2056
2057 HasDefaultArg = TTP->hasDefaultArgument();
2058 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002059 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002060 if (NTTP->getIdentifier())
2061 PlaceholderStr = NTTP->getIdentifier()->getName();
2062 NTTP->getType().getAsStringInternal(PlaceholderStr,
2063 Context.PrintingPolicy);
2064 HasDefaultArg = NTTP->hasDefaultArgument();
2065 } else {
2066 assert(isa<TemplateTemplateParmDecl>(*P));
2067 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2068
2069 // Since putting the template argument list into the placeholder would
2070 // be very, very long, we just use an abbreviation.
2071 PlaceholderStr = "template<...> class";
2072 if (TTP->getIdentifier()) {
2073 PlaceholderStr += ' ';
2074 PlaceholderStr += TTP->getIdentifier()->getName();
2075 }
2076
2077 HasDefaultArg = TTP->hasDefaultArgument();
2078 }
2079
Douglas Gregor218937c2011-02-01 19:23:04 +00002080 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002081 // When we see an optional default argument, put that argument and
2082 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002083 CodeCompletionBuilder Opt(Result.getAllocator());
2084 if (!FirstParameter)
2085 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2086 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2087 P - Params->begin(), true);
2088 Result.AddOptionalChunk(Opt.TakeString());
2089 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002090 }
2091
Douglas Gregor218937c2011-02-01 19:23:04 +00002092 InDefaultArg = false;
2093
Douglas Gregor86d9a522009-09-21 16:56:56 +00002094 if (FirstParameter)
2095 FirstParameter = false;
2096 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002097 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002098
2099 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002100 Result.AddPlaceholderChunk(
2101 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002102 }
2103}
2104
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002105/// \brief Add a qualifier to the given code-completion string, if the
2106/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002107static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002108AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002109 NestedNameSpecifier *Qualifier,
2110 bool QualifierIsInformative,
2111 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002112 if (!Qualifier)
2113 return;
2114
2115 std::string PrintedNNS;
2116 {
2117 llvm::raw_string_ostream OS(PrintedNNS);
2118 Qualifier->print(OS, Context.PrintingPolicy);
2119 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002120 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002121 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002122 else
Douglas Gregordae68752011-02-01 22:57:45 +00002123 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002124}
2125
Douglas Gregor218937c2011-02-01 19:23:04 +00002126static void
2127AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2128 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002129 const FunctionProtoType *Proto
2130 = Function->getType()->getAs<FunctionProtoType>();
2131 if (!Proto || !Proto->getTypeQuals())
2132 return;
2133
Douglas Gregora63f6de2011-02-01 21:15:40 +00002134 // FIXME: Add ref-qualifier!
2135
2136 // Handle single qualifiers without copying
2137 if (Proto->getTypeQuals() == Qualifiers::Const) {
2138 Result.AddInformativeChunk(" const");
2139 return;
2140 }
2141
2142 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2143 Result.AddInformativeChunk(" volatile");
2144 return;
2145 }
2146
2147 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2148 Result.AddInformativeChunk(" restrict");
2149 return;
2150 }
2151
2152 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002153 std::string QualsStr;
2154 if (Proto->getTypeQuals() & Qualifiers::Const)
2155 QualsStr += " const";
2156 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2157 QualsStr += " volatile";
2158 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2159 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002160 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002161}
2162
Douglas Gregor6f942b22010-09-21 16:06:22 +00002163/// \brief Add the name of the given declaration
2164static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002165 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002166 typedef CodeCompletionString::Chunk Chunk;
2167
2168 DeclarationName Name = ND->getDeclName();
2169 if (!Name)
2170 return;
2171
2172 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002173 case DeclarationName::CXXOperatorName: {
2174 const char *OperatorName = 0;
2175 switch (Name.getCXXOverloadedOperator()) {
2176 case OO_None:
2177 case OO_Conditional:
2178 case NUM_OVERLOADED_OPERATORS:
2179 OperatorName = "operator";
2180 break;
2181
2182#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2183 case OO_##Name: OperatorName = "operator" Spelling; break;
2184#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2185#include "clang/Basic/OperatorKinds.def"
2186
2187 case OO_New: OperatorName = "operator new"; break;
2188 case OO_Delete: OperatorName = "operator delete"; break;
2189 case OO_Array_New: OperatorName = "operator new[]"; break;
2190 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2191 case OO_Call: OperatorName = "operator()"; break;
2192 case OO_Subscript: OperatorName = "operator[]"; break;
2193 }
2194 Result.AddTypedTextChunk(OperatorName);
2195 break;
2196 }
2197
Douglas Gregor6f942b22010-09-21 16:06:22 +00002198 case DeclarationName::Identifier:
2199 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002200 case DeclarationName::CXXDestructorName:
2201 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002202 Result.AddTypedTextChunk(
2203 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002204 break;
2205
2206 case DeclarationName::CXXUsingDirective:
2207 case DeclarationName::ObjCZeroArgSelector:
2208 case DeclarationName::ObjCOneArgSelector:
2209 case DeclarationName::ObjCMultiArgSelector:
2210 break;
2211
2212 case DeclarationName::CXXConstructorName: {
2213 CXXRecordDecl *Record = 0;
2214 QualType Ty = Name.getCXXNameType();
2215 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2216 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2217 else if (const InjectedClassNameType *InjectedTy
2218 = Ty->getAs<InjectedClassNameType>())
2219 Record = InjectedTy->getDecl();
2220 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002221 Result.AddTypedTextChunk(
2222 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002223 break;
2224 }
2225
Douglas Gregordae68752011-02-01 22:57:45 +00002226 Result.AddTypedTextChunk(
2227 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002228 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002229 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002230 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002231 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002232 }
2233 break;
2234 }
2235 }
2236}
2237
Douglas Gregor86d9a522009-09-21 16:56:56 +00002238/// \brief If possible, create a new code completion string for the given
2239/// result.
2240///
2241/// \returns Either a new, heap-allocated code completion string describing
2242/// how to use this result, or NULL to indicate that the string or name of the
2243/// result is all that is needed.
2244CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002245CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002246 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002247 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002248 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002249
Douglas Gregor218937c2011-02-01 19:23:04 +00002250 if (Kind == RK_Pattern) {
2251 Pattern->Priority = Priority;
2252 Pattern->Availability = Availability;
2253 return Pattern;
2254 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002255
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002256 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002257 Result.AddTypedTextChunk(Keyword);
2258 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002259 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002260
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002261 if (Kind == RK_Macro) {
2262 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002263 assert(MI && "Not a macro?");
2264
Douglas Gregordae68752011-02-01 22:57:45 +00002265 Result.AddTypedTextChunk(
2266 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002267
2268 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002269 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002270
2271 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002272 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002273 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2274 A != AEnd; ++A) {
2275 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002276 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002277
2278 if (!MI->isVariadic() || A != AEnd - 1) {
2279 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002280 Result.AddPlaceholderChunk(
2281 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002282 continue;
2283 }
2284
2285 // Variadic argument; cope with the different between GNU and C99
2286 // variadic macros, providing a single placeholder for the rest of the
2287 // arguments.
2288 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002289 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002290 else {
2291 std::string Arg = (*A)->getName();
2292 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002293 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002294 }
2295 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002296 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2297 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002298 }
2299
Douglas Gregord8e8a582010-05-25 21:41:55 +00002300 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002301 NamedDecl *ND = Declaration;
2302
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002303 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002304 Result.AddTypedTextChunk(
2305 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002306 Result.AddTextChunk("::");
2307 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002308 }
2309
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002310 AddResultTypeChunk(S.Context, ND, Result);
2311
Douglas Gregor86d9a522009-09-21 16:56:56 +00002312 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002313 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2314 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002315 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002316 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002317 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002318 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002319 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002320 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002321 }
2322
2323 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002324 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2325 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002326 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002327 AddTypedNameChunk(S.Context, Function, Result);
2328
Douglas Gregor86d9a522009-09-21 16:56:56 +00002329 // Figure out which template parameters are deduced (or have default
2330 // arguments).
2331 llvm::SmallVector<bool, 16> Deduced;
2332 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2333 unsigned LastDeducibleArgument;
2334 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2335 --LastDeducibleArgument) {
2336 if (!Deduced[LastDeducibleArgument - 1]) {
2337 // C++0x: Figure out if the template argument has a default. If so,
2338 // the user doesn't need to type this argument.
2339 // FIXME: We need to abstract template parameters better!
2340 bool HasDefaultArg = false;
2341 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002342 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002343 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2344 HasDefaultArg = TTP->hasDefaultArgument();
2345 else if (NonTypeTemplateParmDecl *NTTP
2346 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2347 HasDefaultArg = NTTP->hasDefaultArgument();
2348 else {
2349 assert(isa<TemplateTemplateParmDecl>(Param));
2350 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002351 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002352 }
2353
2354 if (!HasDefaultArg)
2355 break;
2356 }
2357 }
2358
2359 if (LastDeducibleArgument) {
2360 // Some of the function template arguments cannot be deduced from a
2361 // function call, so we introduce an explicit template argument list
2362 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002363 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002364 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2365 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002366 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002367 }
2368
2369 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002370 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002371 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002372 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002373 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002374 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002375 }
2376
2377 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002378 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2379 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002382 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002383 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002384 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2385 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002386 }
2387
Douglas Gregor9630eb62009-11-17 16:44:22 +00002388 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002389 Selector Sel = Method->getSelector();
2390 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002391 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002392 Sel.getIdentifierInfoForSlot(0)->getName()));
2393 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002394 }
2395
Douglas Gregord3c68542009-11-19 01:08:35 +00002396 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2397 SelName += ':';
2398 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002399 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002400 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002401 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002402
2403 // If there is only one parameter, and we're past it, add an empty
2404 // typed-text chunk since there is nothing to type.
2405 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002406 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002407 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002408 unsigned Idx = 0;
2409 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2410 PEnd = Method->param_end();
2411 P != PEnd; (void)++P, ++Idx) {
2412 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002413 std::string Keyword;
2414 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002415 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002416 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2417 Keyword += II->getName().str();
2418 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002419 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002420 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002421 else
Douglas Gregordae68752011-02-01 22:57:45 +00002422 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002423 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002424
2425 // If we're before the starting parameter, skip the placeholder.
2426 if (Idx < StartParameter)
2427 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002428
2429 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002430
2431 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002432 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002433 else {
2434 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2435 Arg = "(" + Arg + ")";
2436 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002437 if (DeclaringEntity || AllParametersAreInformative)
2438 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002439 }
2440
Douglas Gregore17794f2010-08-31 05:13:43 +00002441 if (Method->isVariadic() && (P + 1) == PEnd)
2442 Arg += ", ...";
2443
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002444 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002445 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002446 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002447 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002448 else
Douglas Gregordae68752011-02-01 22:57:45 +00002449 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002450 }
2451
Douglas Gregor2a17af02009-12-23 00:21:46 +00002452 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002453 if (Method->param_size() == 0) {
2454 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002455 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002456 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002457 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002458 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002459 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002460 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002461
2462 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002463 }
2464
Douglas Gregor218937c2011-02-01 19:23:04 +00002465 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002466 }
2467
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002468 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002469 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2470 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002471
Douglas Gregordae68752011-02-01 22:57:45 +00002472 Result.AddTypedTextChunk(
2473 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002474 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002475}
2476
Douglas Gregor86d802e2009-09-23 00:34:09 +00002477CodeCompletionString *
2478CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2479 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002480 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002481 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002482 typedef CodeCompletionString::Chunk Chunk;
2483
Douglas Gregor218937c2011-02-01 19:23:04 +00002484 // FIXME: Set priority, availability appropriately.
2485 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002486 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002487 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002488 const FunctionProtoType *Proto
2489 = dyn_cast<FunctionProtoType>(getFunctionType());
2490 if (!FDecl && !Proto) {
2491 // Function without a prototype. Just give the return type and a
2492 // highlighted ellipsis.
2493 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002494 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2495 S.Context,
2496 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002497 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2498 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2499 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2500 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002501 }
2502
2503 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002504 Result.AddTextChunk(
2505 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002506 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002507 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002508 Result.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002509 Proto->getResultType().getAsString(S.Context.PrintingPolicy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002510
Douglas Gregor218937c2011-02-01 19:23:04 +00002511 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002512 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2513 for (unsigned I = 0; I != NumParams; ++I) {
2514 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002515 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002516
2517 std::string ArgString;
2518 QualType ArgType;
2519
2520 if (FDecl) {
2521 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2522 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2523 } else {
2524 ArgType = Proto->getArgType(I);
2525 }
2526
2527 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2528
2529 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002530 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002531 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002532 else
Douglas Gregordae68752011-02-01 22:57:45 +00002533 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002534 }
2535
2536 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002537 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002538 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002540 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002541 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002542 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002543 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002544
Douglas Gregor218937c2011-02-01 19:23:04 +00002545 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002546}
2547
Douglas Gregor1827e102010-08-16 16:18:59 +00002548unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002549 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002550 bool PreferredTypeIsPointer) {
2551 unsigned Priority = CCP_Macro;
2552
Douglas Gregorb05496d2010-09-20 21:11:48 +00002553 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2554 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2555 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002556 Priority = CCP_Constant;
2557 if (PreferredTypeIsPointer)
2558 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002559 }
2560 // Treat "YES", "NO", "true", and "false" as constants.
2561 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2562 MacroName.equals("true") || MacroName.equals("false"))
2563 Priority = CCP_Constant;
2564 // Treat "bool" as a type.
2565 else if (MacroName.equals("bool"))
2566 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2567
Douglas Gregor1827e102010-08-16 16:18:59 +00002568
2569 return Priority;
2570}
2571
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002572CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2573 if (!D)
2574 return CXCursor_UnexposedDecl;
2575
2576 switch (D->getKind()) {
2577 case Decl::Enum: return CXCursor_EnumDecl;
2578 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2579 case Decl::Field: return CXCursor_FieldDecl;
2580 case Decl::Function:
2581 return CXCursor_FunctionDecl;
2582 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2583 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2584 case Decl::ObjCClass:
2585 // FIXME
2586 return CXCursor_UnexposedDecl;
2587 case Decl::ObjCForwardProtocol:
2588 // FIXME
2589 return CXCursor_UnexposedDecl;
2590 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2591 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2592 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2593 case Decl::ObjCMethod:
2594 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2595 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2596 case Decl::CXXMethod: return CXCursor_CXXMethod;
2597 case Decl::CXXConstructor: return CXCursor_Constructor;
2598 case Decl::CXXDestructor: return CXCursor_Destructor;
2599 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2600 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2601 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2602 case Decl::ParmVar: return CXCursor_ParmDecl;
2603 case Decl::Typedef: return CXCursor_TypedefDecl;
2604 case Decl::Var: return CXCursor_VarDecl;
2605 case Decl::Namespace: return CXCursor_Namespace;
2606 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2607 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2608 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2609 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2610 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2611 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2612 case Decl::ClassTemplatePartialSpecialization:
2613 return CXCursor_ClassTemplatePartialSpecialization;
2614 case Decl::UsingDirective: return CXCursor_UsingDirective;
2615
2616 case Decl::Using:
2617 case Decl::UnresolvedUsingValue:
2618 case Decl::UnresolvedUsingTypename:
2619 return CXCursor_UsingDeclaration;
2620
2621 default:
2622 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2623 switch (TD->getTagKind()) {
2624 case TTK_Struct: return CXCursor_StructDecl;
2625 case TTK_Class: return CXCursor_ClassDecl;
2626 case TTK_Union: return CXCursor_UnionDecl;
2627 case TTK_Enum: return CXCursor_EnumDecl;
2628 }
2629 }
2630 }
2631
2632 return CXCursor_UnexposedDecl;
2633}
2634
Douglas Gregor590c7d52010-07-08 20:55:51 +00002635static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2636 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002637 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002638
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002639 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002640
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002641 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2642 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002643 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002644 Results.AddResult(Result(M->first,
2645 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002646 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002647 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002648 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002649
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002650 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002651
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002652}
2653
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002654static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2655 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002656 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002657
2658 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002659
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002660 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2661 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2662 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2663 Results.AddResult(Result("__func__", CCP_Constant));
2664 Results.ExitScope();
2665}
2666
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002667static void HandleCodeCompleteResults(Sema *S,
2668 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002669 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002670 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002671 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002672 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002673 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002674}
2675
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002676static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2677 Sema::ParserCompletionContext PCC) {
2678 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002679 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002680 return CodeCompletionContext::CCC_TopLevel;
2681
John McCallf312b1e2010-08-26 23:41:50 +00002682 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002683 return CodeCompletionContext::CCC_ClassStructUnion;
2684
John McCallf312b1e2010-08-26 23:41:50 +00002685 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002686 return CodeCompletionContext::CCC_ObjCInterface;
2687
John McCallf312b1e2010-08-26 23:41:50 +00002688 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002689 return CodeCompletionContext::CCC_ObjCImplementation;
2690
John McCallf312b1e2010-08-26 23:41:50 +00002691 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002692 return CodeCompletionContext::CCC_ObjCIvarList;
2693
John McCallf312b1e2010-08-26 23:41:50 +00002694 case Sema::PCC_Template:
2695 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002696 if (S.CurContext->isFileContext())
2697 return CodeCompletionContext::CCC_TopLevel;
2698 else if (S.CurContext->isRecord())
2699 return CodeCompletionContext::CCC_ClassStructUnion;
2700 else
2701 return CodeCompletionContext::CCC_Other;
2702
John McCallf312b1e2010-08-26 23:41:50 +00002703 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002704 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002705
John McCallf312b1e2010-08-26 23:41:50 +00002706 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002707 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2708 S.getLangOptions().ObjC1)
2709 return CodeCompletionContext::CCC_ParenthesizedExpression;
2710 else
2711 return CodeCompletionContext::CCC_Expression;
2712
2713 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002714 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002715 return CodeCompletionContext::CCC_Expression;
2716
John McCallf312b1e2010-08-26 23:41:50 +00002717 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002718 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002719
John McCallf312b1e2010-08-26 23:41:50 +00002720 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002721 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002722
2723 case Sema::PCC_ParenthesizedExpression:
2724 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002725
2726 case Sema::PCC_LocalDeclarationSpecifiers:
2727 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002728 }
2729
2730 return CodeCompletionContext::CCC_Other;
2731}
2732
Douglas Gregorf6961522010-08-27 21:18:54 +00002733/// \brief If we're in a C++ virtual member function, add completion results
2734/// that invoke the functions we override, since it's common to invoke the
2735/// overridden function as well as adding new functionality.
2736///
2737/// \param S The semantic analysis object for which we are generating results.
2738///
2739/// \param InContext This context in which the nested-name-specifier preceding
2740/// the code-completion point
2741static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2742 ResultBuilder &Results) {
2743 // Look through blocks.
2744 DeclContext *CurContext = S.CurContext;
2745 while (isa<BlockDecl>(CurContext))
2746 CurContext = CurContext->getParent();
2747
2748
2749 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2750 if (!Method || !Method->isVirtual())
2751 return;
2752
2753 // We need to have names for all of the parameters, if we're going to
2754 // generate a forwarding call.
2755 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2756 PEnd = Method->param_end();
2757 P != PEnd;
2758 ++P) {
2759 if (!(*P)->getDeclName())
2760 return;
2761 }
2762
2763 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2764 MEnd = Method->end_overridden_methods();
2765 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002766 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002767 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2768 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2769 continue;
2770
2771 // If we need a nested-name-specifier, add one now.
2772 if (!InContext) {
2773 NestedNameSpecifier *NNS
2774 = getRequiredQualification(S.Context, CurContext,
2775 Overridden->getDeclContext());
2776 if (NNS) {
2777 std::string Str;
2778 llvm::raw_string_ostream OS(Str);
2779 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002780 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002781 }
2782 } else if (!InContext->Equals(Overridden->getDeclContext()))
2783 continue;
2784
Douglas Gregordae68752011-02-01 22:57:45 +00002785 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002786 Overridden->getNameAsString()));
2787 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002788 bool FirstParam = true;
2789 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2790 PEnd = Method->param_end();
2791 P != PEnd; ++P) {
2792 if (FirstParam)
2793 FirstParam = false;
2794 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002795 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002796
Douglas Gregordae68752011-02-01 22:57:45 +00002797 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002798 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002799 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002800 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2801 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002802 CCP_SuperCompletion,
2803 CXCursor_CXXMethod));
2804 Results.Ignore(Overridden);
2805 }
2806}
2807
Douglas Gregor01dfea02010-01-10 23:08:15 +00002808void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002809 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002810 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002811 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002812 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002813 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002814
Douglas Gregor01dfea02010-01-10 23:08:15 +00002815 // Determine how to filter results, e.g., so that the names of
2816 // values (functions, enumerators, function templates, etc.) are
2817 // only allowed where we can have an expression.
2818 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002819 case PCC_Namespace:
2820 case PCC_Class:
2821 case PCC_ObjCInterface:
2822 case PCC_ObjCImplementation:
2823 case PCC_ObjCInstanceVariableList:
2824 case PCC_Template:
2825 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002826 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002827 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002828 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2829 break;
2830
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002831 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002832 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002833 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002834 case PCC_ForInit:
2835 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002836 if (WantTypesInContext(CompletionContext, getLangOptions()))
2837 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2838 else
2839 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002840
2841 if (getLangOptions().CPlusPlus)
2842 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002843 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002844
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002845 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002846 // Unfiltered
2847 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002848 }
2849
Douglas Gregor3cdee122010-08-26 16:36:48 +00002850 // If we are in a C++ non-static member function, check the qualifiers on
2851 // the member function to filter/prioritize the results list.
2852 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2853 if (CurMethod->isInstance())
2854 Results.setObjectTypeQualifiers(
2855 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2856
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002857 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002858 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2859 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002860
Douglas Gregorbca403c2010-01-13 23:51:12 +00002861 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002862 Results.ExitScope();
2863
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002864 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002865 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002866 case PCC_Expression:
2867 case PCC_Statement:
2868 case PCC_RecoveryInFunction:
2869 if (S->getFnParent())
2870 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2871 break;
2872
2873 case PCC_Namespace:
2874 case PCC_Class:
2875 case PCC_ObjCInterface:
2876 case PCC_ObjCImplementation:
2877 case PCC_ObjCInstanceVariableList:
2878 case PCC_Template:
2879 case PCC_MemberTemplate:
2880 case PCC_ForInit:
2881 case PCC_Condition:
2882 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002883 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002884 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002885 }
2886
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002887 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002888 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002889
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002890 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002891 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002892}
2893
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002894static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2895 ParsedType Receiver,
2896 IdentifierInfo **SelIdents,
2897 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002898 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002899 bool IsSuper,
2900 ResultBuilder &Results);
2901
2902void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2903 bool AllowNonIdentifiers,
2904 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002905 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002906 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002907 AllowNestedNameSpecifiers
2908 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2909 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002910 Results.EnterNewScope();
2911
2912 // Type qualifiers can come after names.
2913 Results.AddResult(Result("const"));
2914 Results.AddResult(Result("volatile"));
2915 if (getLangOptions().C99)
2916 Results.AddResult(Result("restrict"));
2917
2918 if (getLangOptions().CPlusPlus) {
2919 if (AllowNonIdentifiers) {
2920 Results.AddResult(Result("operator"));
2921 }
2922
2923 // Add nested-name-specifiers.
2924 if (AllowNestedNameSpecifiers) {
2925 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00002926 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002927 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2928 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2929 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00002930 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002931 }
2932 }
2933 Results.ExitScope();
2934
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002935 // If we're in a context where we might have an expression (rather than a
2936 // declaration), and what we've seen so far is an Objective-C type that could
2937 // be a receiver of a class message, this may be a class message send with
2938 // the initial opening bracket '[' missing. Add appropriate completions.
2939 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2940 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2941 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2942 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2943 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2944 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2945 DS.getTypeQualifiers() == 0 &&
2946 S &&
2947 (S->getFlags() & Scope::DeclScope) != 0 &&
2948 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2949 Scope::FunctionPrototypeScope |
2950 Scope::AtCatchScope)) == 0) {
2951 ParsedType T = DS.getRepAsType();
2952 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002953 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002954 }
2955
Douglas Gregor4497dd42010-08-24 04:59:56 +00002956 // Note that we intentionally suppress macro results here, since we do not
2957 // encourage using macros to produce the names of entities.
2958
Douglas Gregor52779fb2010-09-23 23:01:17 +00002959 HandleCodeCompleteResults(this, CodeCompleter,
2960 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002961 Results.data(), Results.size());
2962}
2963
Douglas Gregorfb629412010-08-23 21:17:50 +00002964struct Sema::CodeCompleteExpressionData {
2965 CodeCompleteExpressionData(QualType PreferredType = QualType())
2966 : PreferredType(PreferredType), IntegralConstantExpression(false),
2967 ObjCCollection(false) { }
2968
2969 QualType PreferredType;
2970 bool IntegralConstantExpression;
2971 bool ObjCCollection;
2972 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2973};
2974
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002975/// \brief Perform code-completion in an expression context when we know what
2976/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002977///
2978/// \param IntegralConstantExpression Only permit integral constant
2979/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002980void Sema::CodeCompleteExpression(Scope *S,
2981 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002982 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002983 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
2984 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00002985 if (Data.ObjCCollection)
2986 Results.setFilter(&ResultBuilder::IsObjCCollection);
2987 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002988 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002989 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002990 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2991 else
2992 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002993
2994 if (!Data.PreferredType.isNull())
2995 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2996
2997 // Ignore any declarations that we were told that we don't care about.
2998 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2999 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003000
3001 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003002 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3003 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003004
3005 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003006 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003007 Results.ExitScope();
3008
Douglas Gregor590c7d52010-07-08 20:55:51 +00003009 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003010 if (!Data.PreferredType.isNull())
3011 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3012 || Data.PreferredType->isMemberPointerType()
3013 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003014
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003015 if (S->getFnParent() &&
3016 !Data.ObjCCollection &&
3017 !Data.IntegralConstantExpression)
3018 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3019
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003020 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003021 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003022 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003023 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3024 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003025 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003026}
3027
Douglas Gregorac5fd842010-09-18 01:28:11 +00003028void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3029 if (E.isInvalid())
3030 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3031 else if (getLangOptions().ObjC1)
3032 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003033}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003034
Douglas Gregor73449212010-12-09 23:01:55 +00003035/// \brief The set of properties that have already been added, referenced by
3036/// property name.
3037typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3038
Douglas Gregor95ac6552009-11-18 01:29:26 +00003039static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003040 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003041 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003042 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003043 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003044 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003045
3046 // Add properties in this container.
3047 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3048 PEnd = Container->prop_end();
3049 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003050 ++P) {
3051 if (AddedProperties.insert(P->getIdentifier()))
3052 Results.MaybeAddResult(Result(*P, 0), CurContext);
3053 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003054
3055 // Add properties in referenced protocols.
3056 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3057 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3058 PEnd = Protocol->protocol_end();
3059 P != PEnd; ++P)
Douglas Gregor73449212010-12-09 23:01:55 +00003060 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
3061 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003062 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003063 if (AllowCategories) {
3064 // Look through categories.
3065 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3066 Category; Category = Category->getNextClassCategory())
Douglas Gregor73449212010-12-09 23:01:55 +00003067 AddObjCProperties(Category, AllowCategories, CurContext,
3068 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003069 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003070
3071 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003072 for (ObjCInterfaceDecl::all_protocol_iterator
3073 I = IFace->all_referenced_protocol_begin(),
3074 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor73449212010-12-09 23:01:55 +00003075 AddObjCProperties(*I, AllowCategories, CurContext, AddedProperties,
3076 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003077
3078 // Look in the superclass.
3079 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00003080 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003081 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003082 } else if (const ObjCCategoryDecl *Category
3083 = dyn_cast<ObjCCategoryDecl>(Container)) {
3084 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003085 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3086 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003087 P != PEnd; ++P)
Douglas Gregor73449212010-12-09 23:01:55 +00003088 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
3089 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003090 }
3091}
3092
Douglas Gregor81b747b2009-09-17 21:32:03 +00003093void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3094 SourceLocation OpLoc,
3095 bool IsArrow) {
3096 if (!BaseE || !CodeCompleter)
3097 return;
3098
John McCall0a2c5e22010-08-25 06:19:51 +00003099 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003100
Douglas Gregor81b747b2009-09-17 21:32:03 +00003101 Expr *Base = static_cast<Expr *>(BaseE);
3102 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003103
3104 if (IsArrow) {
3105 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3106 BaseType = Ptr->getPointeeType();
3107 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003108 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003109 else
3110 return;
3111 }
3112
Douglas Gregor218937c2011-02-01 19:23:04 +00003113 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003114 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3115 BaseType),
3116 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003117 Results.EnterNewScope();
3118 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003119 // Indicate that we are performing a member access, and the cv-qualifiers
3120 // for the base object type.
3121 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3122
Douglas Gregor95ac6552009-11-18 01:29:26 +00003123 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003124 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003125 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003126 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3127 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003128
Douglas Gregor95ac6552009-11-18 01:29:26 +00003129 if (getLangOptions().CPlusPlus) {
3130 if (!Results.empty()) {
3131 // The "template" keyword can follow "->" or "." in the grammar.
3132 // However, we only want to suggest the template keyword if something
3133 // is dependent.
3134 bool IsDependent = BaseType->isDependentType();
3135 if (!IsDependent) {
3136 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3137 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3138 IsDependent = Ctx->isDependentContext();
3139 break;
3140 }
3141 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003142
Douglas Gregor95ac6552009-11-18 01:29:26 +00003143 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003144 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003145 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003146 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003147 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3148 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003149 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003150
3151 // Add property results based on our interface.
3152 const ObjCObjectPointerType *ObjCPtr
3153 = BaseType->getAsObjCInterfacePointerType();
3154 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor73449212010-12-09 23:01:55 +00003155 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext,
3156 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003157
3158 // Add properties from the protocols in a qualified interface.
3159 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3160 E = ObjCPtr->qual_end();
3161 I != E; ++I)
Douglas Gregor73449212010-12-09 23:01:55 +00003162 AddObjCProperties(*I, true, CurContext, AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003163 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003164 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003165 // Objective-C instance variable access.
3166 ObjCInterfaceDecl *Class = 0;
3167 if (const ObjCObjectPointerType *ObjCPtr
3168 = BaseType->getAs<ObjCObjectPointerType>())
3169 Class = ObjCPtr->getInterfaceDecl();
3170 else
John McCallc12c5bb2010-05-15 11:32:37 +00003171 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003172
3173 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003174 if (Class) {
3175 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3176 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003177 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3178 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003179 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003180 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003181
3182 // FIXME: How do we cope with isa?
3183
3184 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003185
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003186 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003187 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003188 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003189 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003190}
3191
Douglas Gregor374929f2009-09-18 15:37:17 +00003192void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3193 if (!CodeCompleter)
3194 return;
3195
John McCall0a2c5e22010-08-25 06:19:51 +00003196 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003197 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003198 enum CodeCompletionContext::Kind ContextKind
3199 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003200 switch ((DeclSpec::TST)TagSpec) {
3201 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003202 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003203 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003204 break;
3205
3206 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003207 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003208 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003209 break;
3210
3211 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003212 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003213 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003214 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003215 break;
3216
3217 default:
3218 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3219 return;
3220 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003221
Douglas Gregor218937c2011-02-01 19:23:04 +00003222 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003223 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003224
3225 // First pass: look for tags.
3226 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003227 LookupVisibleDecls(S, LookupTagName, Consumer,
3228 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003229
Douglas Gregor8071e422010-08-15 06:18:01 +00003230 if (CodeCompleter->includeGlobals()) {
3231 // Second pass: look for nested name specifiers.
3232 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3233 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3234 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003235
Douglas Gregor52779fb2010-09-23 23:01:17 +00003236 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003237 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003238}
3239
Douglas Gregor1a480c42010-08-27 17:35:51 +00003240void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003241 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3242 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003243 Results.EnterNewScope();
3244 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3245 Results.AddResult("const");
3246 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3247 Results.AddResult("volatile");
3248 if (getLangOptions().C99 &&
3249 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3250 Results.AddResult("restrict");
3251 Results.ExitScope();
3252 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003253 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003254 Results.data(), Results.size());
3255}
3256
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003257void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003258 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003259 return;
3260
John McCall781472f2010-08-25 08:40:02 +00003261 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003262 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003263 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3264 Data.IntegralConstantExpression = true;
3265 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003266 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003267 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003268
3269 // Code-complete the cases of a switch statement over an enumeration type
3270 // by providing the list of
3271 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3272
3273 // Determine which enumerators we have already seen in the switch statement.
3274 // FIXME: Ideally, we would also be able to look *past* the code-completion
3275 // token, in case we are code-completing in the middle of the switch and not
3276 // at the end. However, we aren't able to do so at the moment.
3277 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003278 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003279 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3280 SC = SC->getNextSwitchCase()) {
3281 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3282 if (!Case)
3283 continue;
3284
3285 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3286 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3287 if (EnumConstantDecl *Enumerator
3288 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3289 // We look into the AST of the case statement to determine which
3290 // enumerator was named. Alternatively, we could compute the value of
3291 // the integral constant expression, then compare it against the
3292 // values of each enumerator. However, value-based approach would not
3293 // work as well with C++ templates where enumerators declared within a
3294 // template are type- and value-dependent.
3295 EnumeratorsSeen.insert(Enumerator);
3296
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003297 // If this is a qualified-id, keep track of the nested-name-specifier
3298 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003299 //
3300 // switch (TagD.getKind()) {
3301 // case TagDecl::TK_enum:
3302 // break;
3303 // case XXX
3304 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003305 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003306 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3307 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003308 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003309 }
3310 }
3311
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003312 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3313 // If there are no prior enumerators in C++, check whether we have to
3314 // qualify the names of the enumerators that we suggest, because they
3315 // may not be visible in this scope.
3316 Qualifier = getRequiredQualification(Context, CurContext,
3317 Enum->getDeclContext());
3318
3319 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3320 }
3321
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003322 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003323 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3324 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003325 Results.EnterNewScope();
3326 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3327 EEnd = Enum->enumerator_end();
3328 E != EEnd; ++E) {
3329 if (EnumeratorsSeen.count(*E))
3330 continue;
3331
John McCall0a2c5e22010-08-25 06:19:51 +00003332 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00003333 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003334 }
3335 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003336
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003337 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003338 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003339 HandleCodeCompleteResults(this, CodeCompleter,
3340 CodeCompletionContext::CCC_Expression,
3341 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003342}
3343
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003344namespace {
3345 struct IsBetterOverloadCandidate {
3346 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003347 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003348
3349 public:
John McCall5769d612010-02-08 23:07:23 +00003350 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3351 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003352
3353 bool
3354 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003355 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003356 }
3357 };
3358}
3359
Douglas Gregord28dcd72010-05-30 06:10:08 +00003360static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3361 if (NumArgs && !Args)
3362 return true;
3363
3364 for (unsigned I = 0; I != NumArgs; ++I)
3365 if (!Args[I])
3366 return true;
3367
3368 return false;
3369}
3370
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003371void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3372 ExprTy **ArgsIn, unsigned NumArgs) {
3373 if (!CodeCompleter)
3374 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003375
3376 // When we're code-completing for a call, we fall back to ordinary
3377 // name code-completion whenever we can't produce specific
3378 // results. We may want to revisit this strategy in the future,
3379 // e.g., by merging the two kinds of results.
3380
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003381 Expr *Fn = (Expr *)FnIn;
3382 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003383
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003384 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003385 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003386 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003387 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003388 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003389 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003390
John McCall3b4294e2009-12-16 12:17:52 +00003391 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003392 SourceLocation Loc = Fn->getExprLoc();
3393 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003394
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003395 // FIXME: What if we're calling something that isn't a function declaration?
3396 // FIXME: What if we're calling a pseudo-destructor?
3397 // FIXME: What if we're calling a member function?
3398
Douglas Gregorc0265402010-01-21 15:46:19 +00003399 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3400 llvm::SmallVector<ResultCandidate, 8> Results;
3401
John McCall3b4294e2009-12-16 12:17:52 +00003402 Expr *NakedFn = Fn->IgnoreParenCasts();
3403 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3404 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3405 /*PartialOverloading=*/ true);
3406 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3407 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003408 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003409 if (!getLangOptions().CPlusPlus ||
3410 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003411 Results.push_back(ResultCandidate(FDecl));
3412 else
John McCall86820f52010-01-26 01:37:31 +00003413 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003414 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3415 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003416 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003417 }
John McCall3b4294e2009-12-16 12:17:52 +00003418 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003419
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003420 QualType ParamType;
3421
Douglas Gregorc0265402010-01-21 15:46:19 +00003422 if (!CandidateSet.empty()) {
3423 // Sort the overload candidate set by placing the best overloads first.
3424 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003425 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003426
Douglas Gregorc0265402010-01-21 15:46:19 +00003427 // Add the remaining viable overload candidates as code-completion reslults.
3428 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3429 CandEnd = CandidateSet.end();
3430 Cand != CandEnd; ++Cand) {
3431 if (Cand->Viable)
3432 Results.push_back(ResultCandidate(Cand->Function));
3433 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003434
3435 // From the viable candidates, try to determine the type of this parameter.
3436 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3437 if (const FunctionType *FType = Results[I].getFunctionType())
3438 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3439 if (NumArgs < Proto->getNumArgs()) {
3440 if (ParamType.isNull())
3441 ParamType = Proto->getArgType(NumArgs);
3442 else if (!Context.hasSameUnqualifiedType(
3443 ParamType.getNonReferenceType(),
3444 Proto->getArgType(NumArgs).getNonReferenceType())) {
3445 ParamType = QualType();
3446 break;
3447 }
3448 }
3449 }
3450 } else {
3451 // Try to determine the parameter type from the type of the expression
3452 // being called.
3453 QualType FunctionType = Fn->getType();
3454 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3455 FunctionType = Ptr->getPointeeType();
3456 else if (const BlockPointerType *BlockPtr
3457 = FunctionType->getAs<BlockPointerType>())
3458 FunctionType = BlockPtr->getPointeeType();
3459 else if (const MemberPointerType *MemPtr
3460 = FunctionType->getAs<MemberPointerType>())
3461 FunctionType = MemPtr->getPointeeType();
3462
3463 if (const FunctionProtoType *Proto
3464 = FunctionType->getAs<FunctionProtoType>()) {
3465 if (NumArgs < Proto->getNumArgs())
3466 ParamType = Proto->getArgType(NumArgs);
3467 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003468 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003469
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003470 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003471 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003472 else
3473 CodeCompleteExpression(S, ParamType);
3474
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003475 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003476 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3477 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003478}
3479
John McCalld226f652010-08-21 09:40:31 +00003480void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3481 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003482 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003483 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003484 return;
3485 }
3486
3487 CodeCompleteExpression(S, VD->getType());
3488}
3489
3490void Sema::CodeCompleteReturn(Scope *S) {
3491 QualType ResultType;
3492 if (isa<BlockDecl>(CurContext)) {
3493 if (BlockScopeInfo *BSI = getCurBlock())
3494 ResultType = BSI->ReturnType;
3495 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3496 ResultType = Function->getResultType();
3497 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3498 ResultType = Method->getResultType();
3499
3500 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003501 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003502 else
3503 CodeCompleteExpression(S, ResultType);
3504}
3505
3506void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3507 if (LHS)
3508 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3509 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003510 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003511}
3512
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003513void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003514 bool EnteringContext) {
3515 if (!SS.getScopeRep() || !CodeCompleter)
3516 return;
3517
Douglas Gregor86d9a522009-09-21 16:56:56 +00003518 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3519 if (!Ctx)
3520 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003521
3522 // Try to instantiate any non-dependent declaration contexts before
3523 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003524 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003525 return;
3526
Douglas Gregor218937c2011-02-01 19:23:04 +00003527 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3528 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003529 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003530
Douglas Gregor86d9a522009-09-21 16:56:56 +00003531 // The "template" keyword can follow "::" in the grammar, but only
3532 // put it into the grammar if the nested-name-specifier is dependent.
3533 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3534 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003535 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003536
3537 // Add calls to overridden virtual functions, if there are any.
3538 //
3539 // FIXME: This isn't wonderful, because we don't know whether we're actually
3540 // in a context that permits expressions. This is a general issue with
3541 // qualified-id completions.
3542 if (!EnteringContext)
3543 MaybeAddOverrideCalls(*this, Ctx, Results);
3544 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003545
Douglas Gregorf6961522010-08-27 21:18:54 +00003546 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3547 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3548
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003549 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003550 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003551 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003552}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003553
3554void Sema::CodeCompleteUsing(Scope *S) {
3555 if (!CodeCompleter)
3556 return;
3557
Douglas Gregor218937c2011-02-01 19:23:04 +00003558 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003559 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3560 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003561 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003562
3563 // If we aren't in class scope, we could see the "namespace" keyword.
3564 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003565 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003566
3567 // After "using", we can see anything that would start a
3568 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003569 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003570 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3571 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003572 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003573
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003574 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003575 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003576 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003577}
3578
3579void Sema::CodeCompleteUsingDirective(Scope *S) {
3580 if (!CodeCompleter)
3581 return;
3582
Douglas Gregor86d9a522009-09-21 16:56:56 +00003583 // After "using namespace", we expect to see a namespace name or namespace
3584 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003585 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3586 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003587 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003588 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003589 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003590 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3591 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003592 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003593 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003594 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003595 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003596}
3597
3598void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3599 if (!CodeCompleter)
3600 return;
3601
Douglas Gregor86d9a522009-09-21 16:56:56 +00003602 DeclContext *Ctx = (DeclContext *)S->getEntity();
3603 if (!S->getParent())
3604 Ctx = Context.getTranslationUnitDecl();
3605
Douglas Gregor52779fb2010-09-23 23:01:17 +00003606 bool SuppressedGlobalResults
3607 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3608
Douglas Gregor218937c2011-02-01 19:23:04 +00003609 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003610 SuppressedGlobalResults
3611 ? CodeCompletionContext::CCC_Namespace
3612 : CodeCompletionContext::CCC_Other,
3613 &ResultBuilder::IsNamespace);
3614
3615 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003616 // We only want to see those namespaces that have already been defined
3617 // within this scope, because its likely that the user is creating an
3618 // extended namespace declaration. Keep track of the most recent
3619 // definition of each namespace.
3620 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3621 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3622 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3623 NS != NSEnd; ++NS)
3624 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3625
3626 // Add the most recent definition (or extended definition) of each
3627 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003628 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003629 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3630 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3631 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003632 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003633 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003634 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003635 }
3636
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003637 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003638 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003639 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003640}
3641
3642void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3643 if (!CodeCompleter)
3644 return;
3645
Douglas Gregor86d9a522009-09-21 16:56:56 +00003646 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003647 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3648 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003649 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003650 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003651 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3652 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003653 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003654 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003655 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003656}
3657
Douglas Gregored8d3222009-09-18 20:05:18 +00003658void Sema::CodeCompleteOperatorName(Scope *S) {
3659 if (!CodeCompleter)
3660 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003661
John McCall0a2c5e22010-08-25 06:19:51 +00003662 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003663 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3664 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003665 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003666 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003667
Douglas Gregor86d9a522009-09-21 16:56:56 +00003668 // Add the names of overloadable operators.
3669#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3670 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003671 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003672#include "clang/Basic/OperatorKinds.def"
3673
3674 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003675 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003676 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003677 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3678 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003679
3680 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003681 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003682 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003683
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003684 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003685 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003686 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003687}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003688
Douglas Gregor0133f522010-08-28 00:00:50 +00003689void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003690 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003691 unsigned NumInitializers) {
3692 CXXConstructorDecl *Constructor
3693 = static_cast<CXXConstructorDecl *>(ConstructorD);
3694 if (!Constructor)
3695 return;
3696
Douglas Gregor218937c2011-02-01 19:23:04 +00003697 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003698 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003699 Results.EnterNewScope();
3700
3701 // Fill in any already-initialized fields or base classes.
3702 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3703 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3704 for (unsigned I = 0; I != NumInitializers; ++I) {
3705 if (Initializers[I]->isBaseInitializer())
3706 InitializedBases.insert(
3707 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3708 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003709 InitializedFields.insert(cast<FieldDecl>(
3710 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003711 }
3712
3713 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003714 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003715 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003716 CXXRecordDecl *ClassDecl = Constructor->getParent();
3717 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3718 BaseEnd = ClassDecl->bases_end();
3719 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003720 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3721 SawLastInitializer
3722 = NumInitializers > 0 &&
3723 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3724 Context.hasSameUnqualifiedType(Base->getType(),
3725 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003726 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003727 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003728
Douglas Gregor218937c2011-02-01 19:23:04 +00003729 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003730 Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003731 Base->getType().getAsString(Context.PrintingPolicy)));
3732 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3733 Builder.AddPlaceholderChunk("args");
3734 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3735 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003736 SawLastInitializer? CCP_NextInitializer
3737 : CCP_MemberDeclaration));
3738 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003739 }
3740
3741 // Add completions for virtual base classes.
3742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3743 BaseEnd = ClassDecl->vbases_end();
3744 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003745 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3746 SawLastInitializer
3747 = NumInitializers > 0 &&
3748 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3749 Context.hasSameUnqualifiedType(Base->getType(),
3750 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003751 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003752 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003753
Douglas Gregor218937c2011-02-01 19:23:04 +00003754 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003755 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003756 Base->getType().getAsString(Context.PrintingPolicy)));
3757 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3758 Builder.AddPlaceholderChunk("args");
3759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3760 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003761 SawLastInitializer? CCP_NextInitializer
3762 : CCP_MemberDeclaration));
3763 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003764 }
3765
3766 // Add completions for members.
3767 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3768 FieldEnd = ClassDecl->field_end();
3769 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003770 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3771 SawLastInitializer
3772 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003773 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3774 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003775 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003776 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003777
3778 if (!Field->getDeclName())
3779 continue;
3780
Douglas Gregordae68752011-02-01 22:57:45 +00003781 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003782 Field->getIdentifier()->getName()));
3783 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3784 Builder.AddPlaceholderChunk("args");
3785 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3786 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003787 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003788 : CCP_MemberDeclaration,
3789 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003790 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003791 }
3792 Results.ExitScope();
3793
Douglas Gregor52779fb2010-09-23 23:01:17 +00003794 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003795 Results.data(), Results.size());
3796}
3797
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003798// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3799// true or false.
3800#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003801static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003802 ResultBuilder &Results,
3803 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003804 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003805 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003806 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003807
Douglas Gregor218937c2011-02-01 19:23:04 +00003808 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003809 if (LangOpts.ObjC2) {
3810 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003811 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3813 Builder.AddPlaceholderChunk("property");
3814 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003815
3816 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00003817 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3818 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3819 Builder.AddPlaceholderChunk("property");
3820 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003821 }
3822}
3823
Douglas Gregorbca403c2010-01-13 23:51:12 +00003824static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003825 ResultBuilder &Results,
3826 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003827 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003828
3829 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003830 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003831
3832 if (LangOpts.ObjC2) {
3833 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003834 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003835
3836 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003837 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003838
3839 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003840 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003841 }
3842}
3843
Douglas Gregorbca403c2010-01-13 23:51:12 +00003844static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003845 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003846 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003847
3848 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00003849 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3851 Builder.AddPlaceholderChunk("name");
3852 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003853
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003854 if (Results.includeCodePatterns()) {
3855 // @interface name
3856 // FIXME: Could introduce the whole pattern, including superclasses and
3857 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00003858 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3859 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3860 Builder.AddPlaceholderChunk("class");
3861 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003862
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003863 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00003864 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3866 Builder.AddPlaceholderChunk("protocol");
3867 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003868
3869 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00003870 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3871 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3872 Builder.AddPlaceholderChunk("class");
3873 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003874 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003875
3876 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00003877 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3878 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3879 Builder.AddPlaceholderChunk("alias");
3880 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3881 Builder.AddPlaceholderChunk("class");
3882 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003883}
3884
John McCalld226f652010-08-21 09:40:31 +00003885void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003886 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003887 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003888 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3889 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003890 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003891 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003892 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003893 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003894 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003895 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003896 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003897 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003898 HandleCodeCompleteResults(this, CodeCompleter,
3899 CodeCompletionContext::CCC_Other,
3900 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003901}
3902
Douglas Gregorbca403c2010-01-13 23:51:12 +00003903static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003904 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003905 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003906
3907 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00003908 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
3909 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3910 Builder.AddPlaceholderChunk("type-name");
3911 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3912 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003913
3914 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00003915 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3916 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3917 Builder.AddPlaceholderChunk("protocol-name");
3918 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3919 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003920
3921 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00003922 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
3923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3924 Builder.AddPlaceholderChunk("selector");
3925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3926 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003927}
3928
Douglas Gregorbca403c2010-01-13 23:51:12 +00003929static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003930 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003931 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003932
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003933 if (Results.includeCodePatterns()) {
3934 // @try { statements } @catch ( declaration ) { statements } @finally
3935 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00003936 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3937 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3938 Builder.AddPlaceholderChunk("statements");
3939 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3940 Builder.AddTextChunk("@catch");
3941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3942 Builder.AddPlaceholderChunk("parameter");
3943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3944 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3945 Builder.AddPlaceholderChunk("statements");
3946 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3947 Builder.AddTextChunk("@finally");
3948 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3949 Builder.AddPlaceholderChunk("statements");
3950 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3951 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003952 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003953
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003954 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00003955 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
3956 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3957 Builder.AddPlaceholderChunk("expression");
3958 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003959
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003960 if (Results.includeCodePatterns()) {
3961 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00003962 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3963 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3964 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3965 Builder.AddPlaceholderChunk("expression");
3966 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3967 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3968 Builder.AddPlaceholderChunk("statements");
3969 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3970 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003971 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003972}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003973
Douglas Gregorbca403c2010-01-13 23:51:12 +00003974static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003975 ResultBuilder &Results,
3976 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003977 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003978 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3979 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3980 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003981 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003982 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003983}
3984
3985void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003986 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3987 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003988 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003989 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003990 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003991 HandleCodeCompleteResults(this, CodeCompleter,
3992 CodeCompletionContext::CCC_Other,
3993 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003994}
3995
3996void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003997 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3998 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003999 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004000 AddObjCStatementResults(Results, false);
4001 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004002 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004003 HandleCodeCompleteResults(this, CodeCompleter,
4004 CodeCompletionContext::CCC_Other,
4005 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004006}
4007
4008void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004009 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4010 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004011 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004012 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004013 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004014 HandleCodeCompleteResults(this, CodeCompleter,
4015 CodeCompletionContext::CCC_Other,
4016 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004017}
4018
Douglas Gregor988358f2009-11-19 00:14:45 +00004019/// \brief Determine whether the addition of the given flag to an Objective-C
4020/// property's attributes will cause a conflict.
4021static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4022 // Check if we've already added this flag.
4023 if (Attributes & NewFlag)
4024 return true;
4025
4026 Attributes |= NewFlag;
4027
4028 // Check for collisions with "readonly".
4029 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4030 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4031 ObjCDeclSpec::DQ_PR_assign |
4032 ObjCDeclSpec::DQ_PR_copy |
4033 ObjCDeclSpec::DQ_PR_retain)))
4034 return true;
4035
4036 // Check for more than one of { assign, copy, retain }.
4037 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4038 ObjCDeclSpec::DQ_PR_copy |
4039 ObjCDeclSpec::DQ_PR_retain);
4040 if (AssignCopyRetMask &&
4041 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4042 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4043 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
4044 return true;
4045
4046 return false;
4047}
4048
Douglas Gregora93b1082009-11-18 23:08:07 +00004049void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004050 if (!CodeCompleter)
4051 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004052
Steve Naroffece8e712009-10-08 21:55:05 +00004053 unsigned Attributes = ODS.getPropertyAttributes();
4054
John McCall0a2c5e22010-08-25 06:19:51 +00004055 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004056 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4057 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004058 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004059 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004060 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004061 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004062 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004063 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004064 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004065 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004066 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004067 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004068 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004069 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004070 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004071 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004072 CodeCompletionBuilder Setter(Results.getAllocator());
4073 Setter.AddTypedTextChunk("setter");
4074 Setter.AddTextChunk(" = ");
4075 Setter.AddPlaceholderChunk("method");
4076 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004077 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004078 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004079 CodeCompletionBuilder Getter(Results.getAllocator());
4080 Getter.AddTypedTextChunk("getter");
4081 Getter.AddTextChunk(" = ");
4082 Getter.AddPlaceholderChunk("method");
4083 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004084 }
Steve Naroffece8e712009-10-08 21:55:05 +00004085 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004086 HandleCodeCompleteResults(this, CodeCompleter,
4087 CodeCompletionContext::CCC_Other,
4088 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004089}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004090
Douglas Gregor4ad96852009-11-19 07:41:15 +00004091/// \brief Descripts the kind of Objective-C method that we want to find
4092/// via code completion.
4093enum ObjCMethodKind {
4094 MK_Any, //< Any kind of method, provided it means other specified criteria.
4095 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4096 MK_OneArgSelector //< One-argument selector.
4097};
4098
Douglas Gregor458433d2010-08-26 15:07:07 +00004099static bool isAcceptableObjCSelector(Selector Sel,
4100 ObjCMethodKind WantKind,
4101 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004102 unsigned NumSelIdents,
4103 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004104 if (NumSelIdents > Sel.getNumArgs())
4105 return false;
4106
4107 switch (WantKind) {
4108 case MK_Any: break;
4109 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4110 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4111 }
4112
Douglas Gregorcf544262010-11-17 21:36:08 +00004113 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4114 return false;
4115
Douglas Gregor458433d2010-08-26 15:07:07 +00004116 for (unsigned I = 0; I != NumSelIdents; ++I)
4117 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4118 return false;
4119
4120 return true;
4121}
4122
Douglas Gregor4ad96852009-11-19 07:41:15 +00004123static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4124 ObjCMethodKind WantKind,
4125 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004126 unsigned NumSelIdents,
4127 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004128 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004129 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004130}
Douglas Gregord36adf52010-09-16 16:06:31 +00004131
4132namespace {
4133 /// \brief A set of selectors, which is used to avoid introducing multiple
4134 /// completions with the same selector into the result set.
4135 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4136}
4137
Douglas Gregor36ecb042009-11-17 23:22:23 +00004138/// \brief Add all of the Objective-C methods in the given Objective-C
4139/// container to the set of results.
4140///
4141/// The container will be a class, protocol, category, or implementation of
4142/// any of the above. This mether will recurse to include methods from
4143/// the superclasses of classes along with their categories, protocols, and
4144/// implementations.
4145///
4146/// \param Container the container in which we'll look to find methods.
4147///
4148/// \param WantInstance whether to add instance methods (only); if false, this
4149/// routine will add factory methods (only).
4150///
4151/// \param CurContext the context in which we're performing the lookup that
4152/// finds methods.
4153///
Douglas Gregorcf544262010-11-17 21:36:08 +00004154/// \param AllowSameLength Whether we allow a method to be added to the list
4155/// when it has the same number of parameters as we have selector identifiers.
4156///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004157/// \param Results the structure into which we'll add results.
4158static void AddObjCMethods(ObjCContainerDecl *Container,
4159 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004160 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004161 IdentifierInfo **SelIdents,
4162 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004163 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004164 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004165 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004166 ResultBuilder &Results,
4167 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004168 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004169 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4170 MEnd = Container->meth_end();
4171 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004172 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4173 // Check whether the selector identifiers we've been given are a
4174 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004175 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4176 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004177 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004178
Douglas Gregord36adf52010-09-16 16:06:31 +00004179 if (!Selectors.insert((*M)->getSelector()))
4180 continue;
4181
Douglas Gregord3c68542009-11-19 01:08:35 +00004182 Result R = Result(*M, 0);
4183 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004184 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004185 if (!InOriginalClass)
4186 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004187 Results.MaybeAddResult(R, CurContext);
4188 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004189 }
4190
Douglas Gregore396c7b2010-09-16 15:34:59 +00004191 // Visit the protocols of protocols.
4192 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4193 const ObjCList<ObjCProtocolDecl> &Protocols
4194 = Protocol->getReferencedProtocols();
4195 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4196 E = Protocols.end();
4197 I != E; ++I)
4198 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004199 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004200 }
4201
Douglas Gregor36ecb042009-11-17 23:22:23 +00004202 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4203 if (!IFace)
4204 return;
4205
4206 // Add methods in protocols.
4207 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4208 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4209 E = Protocols.end();
4210 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004211 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004212 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004213
4214 // Add methods in categories.
4215 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4216 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004217 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004218 NumSelIdents, CurContext, Selectors, AllowSameLength,
4219 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004220
4221 // Add a categories protocol methods.
4222 const ObjCList<ObjCProtocolDecl> &Protocols
4223 = CatDecl->getReferencedProtocols();
4224 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4225 E = Protocols.end();
4226 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004227 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004228 NumSelIdents, CurContext, Selectors, AllowSameLength,
4229 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004230
4231 // Add methods in category implementations.
4232 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004233 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004234 NumSelIdents, CurContext, Selectors, AllowSameLength,
4235 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004236 }
4237
4238 // Add methods in superclass.
4239 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004240 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004241 SelIdents, NumSelIdents, CurContext, Selectors,
4242 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004243
4244 // Add methods in our implementation, if any.
4245 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004246 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004247 NumSelIdents, CurContext, Selectors, AllowSameLength,
4248 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004249}
4250
4251
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004252void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004253 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004254
4255 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004256 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004257 if (!Class) {
4258 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004259 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004260 Class = Category->getClassInterface();
4261
4262 if (!Class)
4263 return;
4264 }
4265
4266 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004267 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4268 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004269 Results.EnterNewScope();
4270
Douglas Gregord36adf52010-09-16 16:06:31 +00004271 VisitedSelectorSet Selectors;
4272 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004273 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004274 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004275 HandleCodeCompleteResults(this, CodeCompleter,
4276 CodeCompletionContext::CCC_Other,
4277 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004278}
4279
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004280void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004281 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004282
4283 // Try to find the interface where setters might live.
4284 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004285 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004286 if (!Class) {
4287 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004288 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004289 Class = Category->getClassInterface();
4290
4291 if (!Class)
4292 return;
4293 }
4294
4295 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004296 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4297 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004298 Results.EnterNewScope();
4299
Douglas Gregord36adf52010-09-16 16:06:31 +00004300 VisitedSelectorSet Selectors;
4301 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004302 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004303
4304 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004305 HandleCodeCompleteResults(this, CodeCompleter,
4306 CodeCompletionContext::CCC_Other,
4307 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004308}
4309
Douglas Gregord32b0222010-08-24 01:06:58 +00004310void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00004311 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004312 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4313 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004314 Results.EnterNewScope();
4315
4316 // Add context-sensitive, Objective-C parameter-passing keywords.
4317 bool AddedInOut = false;
4318 if ((DS.getObjCDeclQualifier() &
4319 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4320 Results.AddResult("in");
4321 Results.AddResult("inout");
4322 AddedInOut = true;
4323 }
4324 if ((DS.getObjCDeclQualifier() &
4325 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4326 Results.AddResult("out");
4327 if (!AddedInOut)
4328 Results.AddResult("inout");
4329 }
4330 if ((DS.getObjCDeclQualifier() &
4331 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4332 ObjCDeclSpec::DQ_Oneway)) == 0) {
4333 Results.AddResult("bycopy");
4334 Results.AddResult("byref");
4335 Results.AddResult("oneway");
4336 }
4337
4338 // Add various builtin type names and specifiers.
4339 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4340 Results.ExitScope();
4341
4342 // Add the various type names
4343 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4344 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4345 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4346 CodeCompleter->includeGlobals());
4347
4348 if (CodeCompleter->includeMacros())
4349 AddMacroResults(PP, Results);
4350
4351 HandleCodeCompleteResults(this, CodeCompleter,
4352 CodeCompletionContext::CCC_Type,
4353 Results.data(), Results.size());
4354}
4355
Douglas Gregor22f56992010-04-06 19:22:33 +00004356/// \brief When we have an expression with type "id", we may assume
4357/// that it has some more-specific class type based on knowledge of
4358/// common uses of Objective-C. This routine returns that class type,
4359/// or NULL if no better result could be determined.
4360static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004361 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004362 if (!Msg)
4363 return 0;
4364
4365 Selector Sel = Msg->getSelector();
4366 if (Sel.isNull())
4367 return 0;
4368
4369 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4370 if (!Id)
4371 return 0;
4372
4373 ObjCMethodDecl *Method = Msg->getMethodDecl();
4374 if (!Method)
4375 return 0;
4376
4377 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004378 ObjCInterfaceDecl *IFace = 0;
4379 switch (Msg->getReceiverKind()) {
4380 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004381 if (const ObjCObjectType *ObjType
4382 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4383 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004384 break;
4385
4386 case ObjCMessageExpr::Instance: {
4387 QualType T = Msg->getInstanceReceiver()->getType();
4388 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4389 IFace = Ptr->getInterfaceDecl();
4390 break;
4391 }
4392
4393 case ObjCMessageExpr::SuperInstance:
4394 case ObjCMessageExpr::SuperClass:
4395 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004396 }
4397
4398 if (!IFace)
4399 return 0;
4400
4401 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4402 if (Method->isInstanceMethod())
4403 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4404 .Case("retain", IFace)
4405 .Case("autorelease", IFace)
4406 .Case("copy", IFace)
4407 .Case("copyWithZone", IFace)
4408 .Case("mutableCopy", IFace)
4409 .Case("mutableCopyWithZone", IFace)
4410 .Case("awakeFromCoder", IFace)
4411 .Case("replacementObjectFromCoder", IFace)
4412 .Case("class", IFace)
4413 .Case("classForCoder", IFace)
4414 .Case("superclass", Super)
4415 .Default(0);
4416
4417 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4418 .Case("new", IFace)
4419 .Case("alloc", IFace)
4420 .Case("allocWithZone", IFace)
4421 .Case("class", IFace)
4422 .Case("superclass", Super)
4423 .Default(0);
4424}
4425
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004426// Add a special completion for a message send to "super", which fills in the
4427// most likely case of forwarding all of our arguments to the superclass
4428// function.
4429///
4430/// \param S The semantic analysis object.
4431///
4432/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4433/// the "super" keyword. Otherwise, we just need to provide the arguments.
4434///
4435/// \param SelIdents The identifiers in the selector that have already been
4436/// provided as arguments for a send to "super".
4437///
4438/// \param NumSelIdents The number of identifiers in \p SelIdents.
4439///
4440/// \param Results The set of results to augment.
4441///
4442/// \returns the Objective-C method declaration that would be invoked by
4443/// this "super" completion. If NULL, no completion was added.
4444static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4445 IdentifierInfo **SelIdents,
4446 unsigned NumSelIdents,
4447 ResultBuilder &Results) {
4448 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4449 if (!CurMethod)
4450 return 0;
4451
4452 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4453 if (!Class)
4454 return 0;
4455
4456 // Try to find a superclass method with the same selector.
4457 ObjCMethodDecl *SuperMethod = 0;
4458 while ((Class = Class->getSuperClass()) && !SuperMethod)
4459 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4460 CurMethod->isInstanceMethod());
4461
4462 if (!SuperMethod)
4463 return 0;
4464
4465 // Check whether the superclass method has the same signature.
4466 if (CurMethod->param_size() != SuperMethod->param_size() ||
4467 CurMethod->isVariadic() != SuperMethod->isVariadic())
4468 return 0;
4469
4470 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4471 CurPEnd = CurMethod->param_end(),
4472 SuperP = SuperMethod->param_begin();
4473 CurP != CurPEnd; ++CurP, ++SuperP) {
4474 // Make sure the parameter types are compatible.
4475 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4476 (*SuperP)->getType()))
4477 return 0;
4478
4479 // Make sure we have a parameter name to forward!
4480 if (!(*CurP)->getIdentifier())
4481 return 0;
4482 }
4483
4484 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004485 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004486
4487 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004488 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004489
4490 // If we need the "super" keyword, add it (plus some spacing).
4491 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004492 Builder.AddTypedTextChunk("super");
4493 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004494 }
4495
4496 Selector Sel = CurMethod->getSelector();
4497 if (Sel.isUnarySelector()) {
4498 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004499 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004500 Sel.getIdentifierInfoForSlot(0)->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004501 else
Douglas Gregordae68752011-02-01 22:57:45 +00004502 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004503 Sel.getIdentifierInfoForSlot(0)->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004504 } else {
4505 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4506 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4507 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004508 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004509
4510 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004511 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004512 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004513 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004514 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004515 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004516 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004517 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004518 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004519 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004520 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004521 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004522 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004523 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004524 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004525 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004526 }
4527 }
4528 }
4529
Douglas Gregor218937c2011-02-01 19:23:04 +00004530 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004531 SuperMethod->isInstanceMethod()
4532 ? CXCursor_ObjCInstanceMethodDecl
4533 : CXCursor_ObjCClassMethodDecl));
4534 return SuperMethod;
4535}
4536
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004537void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004538 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004539 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4540 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004541 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004542
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004543 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4544 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004545 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4546 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004547
4548 // If we are in an Objective-C method inside a class that has a superclass,
4549 // add "super" as an option.
4550 if (ObjCMethodDecl *Method = getCurMethodDecl())
4551 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004552 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004553 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004554
4555 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4556 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004557
4558 Results.ExitScope();
4559
4560 if (CodeCompleter->includeMacros())
4561 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004562 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004563 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004564
4565}
4566
Douglas Gregor2725ca82010-04-21 19:57:20 +00004567void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4568 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004569 unsigned NumSelIdents,
4570 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004571 ObjCInterfaceDecl *CDecl = 0;
4572 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4573 // Figure out which interface we're in.
4574 CDecl = CurMethod->getClassInterface();
4575 if (!CDecl)
4576 return;
4577
4578 // Find the superclass of this class.
4579 CDecl = CDecl->getSuperClass();
4580 if (!CDecl)
4581 return;
4582
4583 if (CurMethod->isInstanceMethod()) {
4584 // We are inside an instance method, which means that the message
4585 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004586 // current object.
4587 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004588 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004589 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004590 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004591 }
4592
4593 // Fall through to send to the superclass in CDecl.
4594 } else {
4595 // "super" may be the name of a type or variable. Figure out which
4596 // it is.
4597 IdentifierInfo *Super = &Context.Idents.get("super");
4598 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4599 LookupOrdinaryName);
4600 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4601 // "super" names an interface. Use it.
4602 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004603 if (const ObjCObjectType *Iface
4604 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4605 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004606 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4607 // "super" names an unresolved type; we can't be more specific.
4608 } else {
4609 // Assume that "super" names some kind of value and parse that way.
4610 CXXScopeSpec SS;
4611 UnqualifiedId id;
4612 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004613 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004614 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004615 SelIdents, NumSelIdents,
4616 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004617 }
4618
4619 // Fall through
4620 }
4621
John McCallb3d87482010-08-24 05:47:05 +00004622 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004623 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004624 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004625 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004626 NumSelIdents, AtArgumentExpression,
4627 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004628}
4629
Douglas Gregorb9d77572010-09-21 00:03:25 +00004630/// \brief Given a set of code-completion results for the argument of a message
4631/// send, determine the preferred type (if any) for that argument expression.
4632static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4633 unsigned NumSelIdents) {
4634 typedef CodeCompletionResult Result;
4635 ASTContext &Context = Results.getSema().Context;
4636
4637 QualType PreferredType;
4638 unsigned BestPriority = CCP_Unlikely * 2;
4639 Result *ResultsData = Results.data();
4640 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4641 Result &R = ResultsData[I];
4642 if (R.Kind == Result::RK_Declaration &&
4643 isa<ObjCMethodDecl>(R.Declaration)) {
4644 if (R.Priority <= BestPriority) {
4645 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4646 if (NumSelIdents <= Method->param_size()) {
4647 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4648 ->getType();
4649 if (R.Priority < BestPriority || PreferredType.isNull()) {
4650 BestPriority = R.Priority;
4651 PreferredType = MyPreferredType;
4652 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4653 MyPreferredType)) {
4654 PreferredType = QualType();
4655 }
4656 }
4657 }
4658 }
4659 }
4660
4661 return PreferredType;
4662}
4663
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004664static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4665 ParsedType Receiver,
4666 IdentifierInfo **SelIdents,
4667 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004668 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004669 bool IsSuper,
4670 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004671 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004672 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004673
Douglas Gregor24a069f2009-11-17 17:59:40 +00004674 // If the given name refers to an interface type, retrieve the
4675 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004676 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004677 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004678 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004679 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4680 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004681 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004682
Douglas Gregor36ecb042009-11-17 23:22:23 +00004683 // Add all of the factory methods in this Objective-C class, its protocols,
4684 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004685 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004686
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004687 // If this is a send-to-super, try to add the special "super" send
4688 // completion.
4689 if (IsSuper) {
4690 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004691 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4692 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004693 Results.Ignore(SuperMethod);
4694 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004695
Douglas Gregor265f7492010-08-27 15:29:55 +00004696 // If we're inside an Objective-C method definition, prefer its selector to
4697 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004698 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004699 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004700
Douglas Gregord36adf52010-09-16 16:06:31 +00004701 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004702 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004703 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004704 SemaRef.CurContext, Selectors, AtArgumentExpression,
4705 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004706 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004707 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004708
Douglas Gregor719770d2010-04-06 17:30:22 +00004709 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004710 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004711 if (SemaRef.ExternalSource) {
4712 for (uint32_t I = 0,
4713 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004714 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004715 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4716 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004717 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004718
4719 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004720 }
4721 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004722
4723 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4724 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004725 M != MEnd; ++M) {
4726 for (ObjCMethodList *MethList = &M->second.second;
4727 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004728 MethList = MethList->Next) {
4729 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4730 NumSelIdents))
4731 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004732
Douglas Gregor13438f92010-04-06 16:40:00 +00004733 Result R(MethList->Method, 0);
4734 R.StartParameter = NumSelIdents;
4735 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004736 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004737 }
4738 }
4739 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004740
4741 Results.ExitScope();
4742}
Douglas Gregor13438f92010-04-06 16:40:00 +00004743
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004744void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4745 IdentifierInfo **SelIdents,
4746 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004747 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004748 bool IsSuper) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004749 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4750 CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004751 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4752 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004753
4754 // If we're actually at the argument expression (rather than prior to the
4755 // selector), we're actually performing code completion for an expression.
4756 // Determine whether we have a single, best method. If so, we can
4757 // code-complete the expression using the corresponding parameter type as
4758 // our preferred type, improving completion results.
4759 if (AtArgumentExpression) {
4760 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4761 NumSelIdents);
4762 if (PreferredType.isNull())
4763 CodeCompleteOrdinaryName(S, PCC_Expression);
4764 else
4765 CodeCompleteExpression(S, PreferredType);
4766 return;
4767 }
4768
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004769 HandleCodeCompleteResults(this, CodeCompleter,
4770 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004771 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004772}
4773
Douglas Gregord3c68542009-11-19 01:08:35 +00004774void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4775 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004776 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004777 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004778 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004779 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004780
4781 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004782
Douglas Gregor36ecb042009-11-17 23:22:23 +00004783 // If necessary, apply function/array conversion to the receiver.
4784 // C99 6.7.5.3p[7,8].
Douglas Gregor78edf512010-09-15 16:23:04 +00004785 if (RecExpr)
4786 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004787 QualType ReceiverType = RecExpr? RecExpr->getType()
4788 : Super? Context.getObjCObjectPointerType(
4789 Context.getObjCInterfaceType(Super))
4790 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004791
Douglas Gregorda892642010-11-08 21:12:30 +00004792 // If we're messaging an expression with type "id" or "Class", check
4793 // whether we know something special about the receiver that allows
4794 // us to assume a more-specific receiver type.
4795 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4796 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
4797 if (ReceiverType->isObjCClassType())
4798 return CodeCompleteObjCClassMessage(S,
4799 ParsedType::make(Context.getObjCInterfaceType(IFace)),
4800 SelIdents, NumSelIdents,
4801 AtArgumentExpression, Super);
4802
4803 ReceiverType = Context.getObjCObjectPointerType(
4804 Context.getObjCInterfaceType(IFace));
4805 }
4806
Douglas Gregor36ecb042009-11-17 23:22:23 +00004807 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00004808 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4809 CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004810 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004811
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004812 // If this is a send-to-super, try to add the special "super" send
4813 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004814 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004815 if (ObjCMethodDecl *SuperMethod
4816 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4817 Results))
4818 Results.Ignore(SuperMethod);
4819 }
4820
Douglas Gregor265f7492010-08-27 15:29:55 +00004821 // If we're inside an Objective-C method definition, prefer its selector to
4822 // others.
4823 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4824 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004825
Douglas Gregord36adf52010-09-16 16:06:31 +00004826 // Keep track of the selectors we've already added.
4827 VisitedSelectorSet Selectors;
4828
Douglas Gregorf74a4192009-11-18 00:06:18 +00004829 // Handle messages to Class. This really isn't a message to an instance
4830 // method, so we treat it the same way we would treat a message send to a
4831 // class method.
4832 if (ReceiverType->isObjCClassType() ||
4833 ReceiverType->isObjCQualifiedClassType()) {
4834 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4835 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004836 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004837 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004838 }
4839 }
4840 // Handle messages to a qualified ID ("id<foo>").
4841 else if (const ObjCObjectPointerType *QualID
4842 = ReceiverType->getAsObjCQualifiedIdType()) {
4843 // Search protocols for instance methods.
4844 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4845 E = QualID->qual_end();
4846 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004847 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004848 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004849 }
4850 // Handle messages to a pointer to interface type.
4851 else if (const ObjCObjectPointerType *IFacePtr
4852 = ReceiverType->getAsObjCInterfacePointerType()) {
4853 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004854 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004855 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
4856 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004857
4858 // Search protocols for instance methods.
4859 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4860 E = IFacePtr->qual_end();
4861 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004862 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004863 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004864 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004865 // Handle messages to "id".
4866 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004867 // We're messaging "id", so provide all instance methods we know
4868 // about as code-completion results.
4869
4870 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004871 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004872 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004873 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4874 I != N; ++I) {
4875 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004876 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004877 continue;
4878
Sebastian Redldb9d2142010-08-02 23:18:59 +00004879 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004880 }
4881 }
4882
Sebastian Redldb9d2142010-08-02 23:18:59 +00004883 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4884 MEnd = MethodPool.end();
4885 M != MEnd; ++M) {
4886 for (ObjCMethodList *MethList = &M->second.first;
4887 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004888 MethList = MethList->Next) {
4889 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4890 NumSelIdents))
4891 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00004892
4893 if (!Selectors.insert(MethList->Method->getSelector()))
4894 continue;
4895
Douglas Gregor13438f92010-04-06 16:40:00 +00004896 Result R(MethList->Method, 0);
4897 R.StartParameter = NumSelIdents;
4898 R.AllParametersAreInformative = false;
4899 Results.MaybeAddResult(R, CurContext);
4900 }
4901 }
4902 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00004903 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00004904
4905
4906 // If we're actually at the argument expression (rather than prior to the
4907 // selector), we're actually performing code completion for an expression.
4908 // Determine whether we have a single, best method. If so, we can
4909 // code-complete the expression using the corresponding parameter type as
4910 // our preferred type, improving completion results.
4911 if (AtArgumentExpression) {
4912 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4913 NumSelIdents);
4914 if (PreferredType.isNull())
4915 CodeCompleteOrdinaryName(S, PCC_Expression);
4916 else
4917 CodeCompleteExpression(S, PreferredType);
4918 return;
4919 }
4920
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004921 HandleCodeCompleteResults(this, CodeCompleter,
4922 CodeCompletionContext::CCC_Other,
4923 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004924}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004925
Douglas Gregorfb629412010-08-23 21:17:50 +00004926void Sema::CodeCompleteObjCForCollection(Scope *S,
4927 DeclGroupPtrTy IterationVar) {
4928 CodeCompleteExpressionData Data;
4929 Data.ObjCCollection = true;
4930
4931 if (IterationVar.getAsOpaquePtr()) {
4932 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4933 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4934 if (*I)
4935 Data.IgnoreDecls.push_back(*I);
4936 }
4937 }
4938
4939 CodeCompleteExpression(S, Data);
4940}
4941
Douglas Gregor458433d2010-08-26 15:07:07 +00004942void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4943 unsigned NumSelIdents) {
4944 // If we have an external source, load the entire class method
4945 // pool from the AST file.
4946 if (ExternalSource) {
4947 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4948 I != N; ++I) {
4949 Selector Sel = ExternalSource->GetExternalSelector(I);
4950 if (Sel.isNull() || MethodPool.count(Sel))
4951 continue;
4952
4953 ReadMethodPool(Sel);
4954 }
4955 }
4956
Douglas Gregor218937c2011-02-01 19:23:04 +00004957 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4958 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00004959 Results.EnterNewScope();
4960 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4961 MEnd = MethodPool.end();
4962 M != MEnd; ++M) {
4963
4964 Selector Sel = M->first;
4965 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4966 continue;
4967
Douglas Gregor218937c2011-02-01 19:23:04 +00004968 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00004969 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00004970 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004971 Sel.getIdentifierInfoForSlot(0)->getName()));
4972 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00004973 continue;
4974 }
4975
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004976 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004977 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004978 if (I == NumSelIdents) {
4979 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00004980 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004981 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004982 Accumulator.clear();
4983 }
4984 }
4985
4986 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4987 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004988 }
Douglas Gregordae68752011-02-01 22:57:45 +00004989 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00004990 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00004991 }
4992 Results.ExitScope();
4993
4994 HandleCodeCompleteResults(this, CodeCompleter,
4995 CodeCompletionContext::CCC_SelectorName,
4996 Results.data(), Results.size());
4997}
4998
Douglas Gregor55385fe2009-11-18 04:19:12 +00004999/// \brief Add all of the protocol declarations that we find in the given
5000/// (translation unit) context.
5001static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005002 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005003 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005004 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005005
5006 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5007 DEnd = Ctx->decls_end();
5008 D != DEnd; ++D) {
5009 // Record any protocols we find.
5010 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005011 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005012 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005013
5014 // Record any forward-declared protocols we find.
5015 if (ObjCForwardProtocolDecl *Forward
5016 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5017 for (ObjCForwardProtocolDecl::protocol_iterator
5018 P = Forward->protocol_begin(),
5019 PEnd = Forward->protocol_end();
5020 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005021 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005022 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005023 }
5024 }
5025}
5026
5027void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5028 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005029 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5030 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005031
Douglas Gregor70c23352010-12-09 21:44:02 +00005032 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5033 Results.EnterNewScope();
5034
5035 // Tell the result set to ignore all of the protocols we have
5036 // already seen.
5037 // FIXME: This doesn't work when caching code-completion results.
5038 for (unsigned I = 0; I != NumProtocols; ++I)
5039 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5040 Protocols[I].second))
5041 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005042
Douglas Gregor70c23352010-12-09 21:44:02 +00005043 // Add all protocols.
5044 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5045 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005046
Douglas Gregor70c23352010-12-09 21:44:02 +00005047 Results.ExitScope();
5048 }
5049
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005050 HandleCodeCompleteResults(this, CodeCompleter,
5051 CodeCompletionContext::CCC_ObjCProtocolName,
5052 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005053}
5054
5055void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005056 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5057 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005058
Douglas Gregor70c23352010-12-09 21:44:02 +00005059 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5060 Results.EnterNewScope();
5061
5062 // Add all protocols.
5063 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5064 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005065
Douglas Gregor70c23352010-12-09 21:44:02 +00005066 Results.ExitScope();
5067 }
5068
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005069 HandleCodeCompleteResults(this, CodeCompleter,
5070 CodeCompletionContext::CCC_ObjCProtocolName,
5071 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005072}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005073
5074/// \brief Add all of the Objective-C interface declarations that we find in
5075/// the given (translation unit) context.
5076static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5077 bool OnlyForwardDeclarations,
5078 bool OnlyUnimplemented,
5079 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005080 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005081
5082 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5083 DEnd = Ctx->decls_end();
5084 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005085 // Record any interfaces we find.
5086 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5087 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5088 (!OnlyUnimplemented || !Class->getImplementation()))
5089 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005090
5091 // Record any forward-declared interfaces we find.
5092 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5093 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005094 C != CEnd; ++C)
5095 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5096 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5097 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005098 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005099 }
5100 }
5101}
5102
5103void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005104 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5105 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005106 Results.EnterNewScope();
5107
5108 // Add all classes.
5109 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5110 false, Results);
5111
5112 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005113 // FIXME: Add a special context for this, use cached global completion
5114 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005115 HandleCodeCompleteResults(this, CodeCompleter,
5116 CodeCompletionContext::CCC_Other,
5117 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005118}
5119
Douglas Gregorc83c6872010-04-15 22:33:43 +00005120void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5121 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005122 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5123 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005124 Results.EnterNewScope();
5125
5126 // Make sure that we ignore the class we're currently defining.
5127 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005128 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005129 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005130 Results.Ignore(CurClass);
5131
5132 // Add all classes.
5133 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5134 false, Results);
5135
5136 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005137 // FIXME: Add a special context for this, use cached global completion
5138 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005139 HandleCodeCompleteResults(this, CodeCompleter,
5140 CodeCompletionContext::CCC_Other,
5141 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005142}
5143
5144void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005145 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5146 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005147 Results.EnterNewScope();
5148
5149 // Add all unimplemented classes.
5150 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5151 true, Results);
5152
5153 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005154 // FIXME: Add a special context for this, use cached global completion
5155 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005156 HandleCodeCompleteResults(this, CodeCompleter,
5157 CodeCompletionContext::CCC_Other,
5158 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005159}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005160
5161void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005162 IdentifierInfo *ClassName,
5163 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005164 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005165
Douglas Gregor218937c2011-02-01 19:23:04 +00005166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5167 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005168
5169 // Ignore any categories we find that have already been implemented by this
5170 // interface.
5171 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5172 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005173 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005174 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5175 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5176 Category = Category->getNextClassCategory())
5177 CategoryNames.insert(Category->getIdentifier());
5178
5179 // Add all of the categories we know about.
5180 Results.EnterNewScope();
5181 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5182 for (DeclContext::decl_iterator D = TU->decls_begin(),
5183 DEnd = TU->decls_end();
5184 D != DEnd; ++D)
5185 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5186 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005187 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005188 Results.ExitScope();
5189
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005190 HandleCodeCompleteResults(this, CodeCompleter,
5191 CodeCompletionContext::CCC_Other,
5192 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005193}
5194
5195void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005196 IdentifierInfo *ClassName,
5197 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005198 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005199
5200 // Find the corresponding interface. If we couldn't find the interface, the
5201 // program itself is ill-formed. However, we'll try to be helpful still by
5202 // providing the list of all of the categories we know about.
5203 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005204 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005205 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5206 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005207 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005208
Douglas Gregor218937c2011-02-01 19:23:04 +00005209 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5210 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005211
5212 // Add all of the categories that have have corresponding interface
5213 // declarations in this class and any of its superclasses, except for
5214 // already-implemented categories in the class itself.
5215 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5216 Results.EnterNewScope();
5217 bool IgnoreImplemented = true;
5218 while (Class) {
5219 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5220 Category = Category->getNextClassCategory())
5221 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5222 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005223 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005224
5225 Class = Class->getSuperClass();
5226 IgnoreImplemented = false;
5227 }
5228 Results.ExitScope();
5229
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005230 HandleCodeCompleteResults(this, CodeCompleter,
5231 CodeCompletionContext::CCC_Other,
5232 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005233}
Douglas Gregor322328b2009-11-18 22:32:06 +00005234
John McCalld226f652010-08-21 09:40:31 +00005235void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005236 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005237 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5238 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005239
5240 // Figure out where this @synthesize lives.
5241 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005242 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005243 if (!Container ||
5244 (!isa<ObjCImplementationDecl>(Container) &&
5245 !isa<ObjCCategoryImplDecl>(Container)))
5246 return;
5247
5248 // Ignore any properties that have already been implemented.
5249 for (DeclContext::decl_iterator D = Container->decls_begin(),
5250 DEnd = Container->decls_end();
5251 D != DEnd; ++D)
5252 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5253 Results.Ignore(PropertyImpl->getPropertyDecl());
5254
5255 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005256 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005257 Results.EnterNewScope();
5258 if (ObjCImplementationDecl *ClassImpl
5259 = dyn_cast<ObjCImplementationDecl>(Container))
5260 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005261 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005262 else
5263 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor73449212010-12-09 23:01:55 +00005264 false, CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005265 Results.ExitScope();
5266
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005267 HandleCodeCompleteResults(this, CodeCompleter,
5268 CodeCompletionContext::CCC_Other,
5269 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005270}
5271
5272void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5273 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005274 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005275 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005276 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5277 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005278
5279 // Figure out where this @synthesize lives.
5280 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005281 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005282 if (!Container ||
5283 (!isa<ObjCImplementationDecl>(Container) &&
5284 !isa<ObjCCategoryImplDecl>(Container)))
5285 return;
5286
5287 // Figure out which interface we're looking into.
5288 ObjCInterfaceDecl *Class = 0;
5289 if (ObjCImplementationDecl *ClassImpl
5290 = dyn_cast<ObjCImplementationDecl>(Container))
5291 Class = ClassImpl->getClassInterface();
5292 else
5293 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5294 ->getClassInterface();
5295
5296 // Add all of the instance variables in this class and its superclasses.
5297 Results.EnterNewScope();
5298 for(; Class; Class = Class->getSuperClass()) {
5299 // FIXME: We could screen the type of each ivar for compatibility with
5300 // the property, but is that being too paternal?
5301 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
5302 IVarEnd = Class->ivar_end();
5303 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00005304 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00005305 }
5306 Results.ExitScope();
5307
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005308 HandleCodeCompleteResults(this, CodeCompleter,
5309 CodeCompletionContext::CCC_Other,
5310 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005311}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005312
Douglas Gregor408be5a2010-08-25 01:08:01 +00005313// Mapping from selectors to the methods that implement that selector, along
5314// with the "in original class" flag.
5315typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5316 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005317
5318/// \brief Find all of the methods that reside in the given container
5319/// (and its superclasses, protocols, etc.) that meet the given
5320/// criteria. Insert those methods into the map of known methods,
5321/// indexed by selector so they can be easily found.
5322static void FindImplementableMethods(ASTContext &Context,
5323 ObjCContainerDecl *Container,
5324 bool WantInstanceMethods,
5325 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005326 KnownMethodsMap &KnownMethods,
5327 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005328 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5329 // Recurse into protocols.
5330 const ObjCList<ObjCProtocolDecl> &Protocols
5331 = IFace->getReferencedProtocols();
5332 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005333 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005334 I != E; ++I)
5335 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005336 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005337
Douglas Gregorea766182010-10-18 18:21:28 +00005338 // Add methods from any class extensions and categories.
5339 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5340 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005341 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5342 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005343 KnownMethods, false);
5344
5345 // Visit the superclass.
5346 if (IFace->getSuperClass())
5347 FindImplementableMethods(Context, IFace->getSuperClass(),
5348 WantInstanceMethods, ReturnType,
5349 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005350 }
5351
5352 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5353 // Recurse into protocols.
5354 const ObjCList<ObjCProtocolDecl> &Protocols
5355 = Category->getReferencedProtocols();
5356 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005357 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005358 I != E; ++I)
5359 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005360 KnownMethods, InOriginalClass);
5361
5362 // If this category is the original class, jump to the interface.
5363 if (InOriginalClass && Category->getClassInterface())
5364 FindImplementableMethods(Context, Category->getClassInterface(),
5365 WantInstanceMethods, ReturnType, KnownMethods,
5366 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005367 }
5368
5369 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5370 // Recurse into protocols.
5371 const ObjCList<ObjCProtocolDecl> &Protocols
5372 = Protocol->getReferencedProtocols();
5373 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5374 E = Protocols.end();
5375 I != E; ++I)
5376 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005377 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005378 }
5379
5380 // Add methods in this container. This operation occurs last because
5381 // we want the methods from this container to override any methods
5382 // we've previously seen with the same selector.
5383 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5384 MEnd = Container->meth_end();
5385 M != MEnd; ++M) {
5386 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5387 if (!ReturnType.isNull() &&
5388 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5389 continue;
5390
Douglas Gregor408be5a2010-08-25 01:08:01 +00005391 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005392 }
5393 }
5394}
5395
5396void Sema::CodeCompleteObjCMethodDecl(Scope *S,
5397 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00005398 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00005399 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005400 // Determine the return type of the method we're declaring, if
5401 // provided.
5402 QualType ReturnType = GetTypeFromParser(ReturnTy);
5403
Douglas Gregorea766182010-10-18 18:21:28 +00005404 // Determine where we should start searching for methods.
5405 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005406 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00005407 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005408 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
5409 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005410 IsInImplementation = true;
5411 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00005412 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005413 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005414 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00005415 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00005416 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005417 }
5418
5419 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00005420 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00005421 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005422 }
5423
Douglas Gregorea766182010-10-18 18:21:28 +00005424 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005425 HandleCodeCompleteResults(this, CodeCompleter,
5426 CodeCompletionContext::CCC_Other,
5427 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005428 return;
5429 }
5430
5431 // Find all of the methods that we could declare/implement here.
5432 KnownMethodsMap KnownMethods;
5433 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00005434 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005435
Douglas Gregore8f5a172010-04-07 00:21:17 +00005436 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00005437 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5439 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005440 Results.EnterNewScope();
5441 PrintingPolicy Policy(Context.PrintingPolicy);
5442 Policy.AnonymousTagLocations = false;
5443 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
5444 MEnd = KnownMethods.end();
5445 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00005446 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00005447 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005448
5449 // If the result type was not already provided, add it to the
5450 // pattern as (type).
5451 if (ReturnType.isNull()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005452 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregora63f6de2011-02-01 21:15:40 +00005453 Builder.AddTextChunk(GetCompletionTypeString(Method->getResultType(),
5454 Context,
5455 Builder.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00005456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005457 }
5458
5459 Selector Sel = Method->getSelector();
5460
5461 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00005462 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005463 Sel.getIdentifierInfoForSlot(0)->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005464
5465 // Add parameters to the pattern.
5466 unsigned I = 0;
5467 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5468 PEnd = Method->param_end();
5469 P != PEnd; (void)++P, ++I) {
5470 // Add the part of the selector name.
5471 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00005472 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00005473 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005474 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5475 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005476 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005477 (Sel.getIdentifierInfoForSlot(I)->getName()
5478 + ":").str()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005479 } else
5480 break;
5481
5482 // Add the parameter type.
Douglas Gregor218937c2011-02-01 19:23:04 +00005483 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregora63f6de2011-02-01 21:15:40 +00005484 Builder.AddTextChunk(GetCompletionTypeString((*P)->getOriginalType(),
5485 Context,
5486 Builder.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00005487 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005488
5489 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00005490 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005491 }
5492
5493 if (Method->isVariadic()) {
5494 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00005495 Builder.AddChunk(CodeCompletionString::CK_Comma);
5496 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00005497 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005498
Douglas Gregor447107d2010-05-28 00:57:46 +00005499 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005500 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00005501 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5502 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5503 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005504 if (!Method->getResultType()->isVoidType()) {
5505 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00005506 Builder.AddTextChunk("return");
5507 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5508 Builder.AddPlaceholderChunk("expression");
5509 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005510 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00005511 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00005512
Douglas Gregor218937c2011-02-01 19:23:04 +00005513 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
5514 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005515 }
5516
Douglas Gregor408be5a2010-08-25 01:08:01 +00005517 unsigned Priority = CCP_CodePattern;
5518 if (!M->second.second)
5519 Priority += CCD_InBaseClass;
5520
Douglas Gregor218937c2011-02-01 19:23:04 +00005521 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00005522 Method->isInstanceMethod()
5523 ? CXCursor_ObjCInstanceMethodDecl
5524 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00005525 }
5526
5527 Results.ExitScope();
5528
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005529 HandleCodeCompleteResults(this, CodeCompleter,
5530 CodeCompletionContext::CCC_Other,
5531 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00005532}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005533
5534void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5535 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005536 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00005537 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005538 IdentifierInfo **SelIdents,
5539 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005540 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005541 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005542 if (ExternalSource) {
5543 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5544 I != N; ++I) {
5545 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005546 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005547 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00005548
5549 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005550 }
5551 }
5552
5553 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00005554 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5556 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005557
5558 if (ReturnTy)
5559 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00005560
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005561 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005562 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5563 MEnd = MethodPool.end();
5564 M != MEnd; ++M) {
5565 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5566 &M->second.second;
5567 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005568 MethList = MethList->Next) {
5569 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5570 NumSelIdents))
5571 continue;
5572
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005573 if (AtParameterName) {
5574 // Suggest parameter names we've seen before.
5575 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5576 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5577 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005578 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00005579 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005580 Param->getIdentifier()->getName()));
5581 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00005582 }
5583 }
5584
5585 continue;
5586 }
5587
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005588 Result R(MethList->Method, 0);
5589 R.StartParameter = NumSelIdents;
5590 R.AllParametersAreInformative = false;
5591 R.DeclaringEntity = true;
5592 Results.MaybeAddResult(R, CurContext);
5593 }
5594 }
5595
5596 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005597 HandleCodeCompleteResults(this, CodeCompleter,
5598 CodeCompletionContext::CCC_Other,
5599 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00005600}
Douglas Gregor87c08a52010-08-13 22:48:40 +00005601
Douglas Gregorf29c5232010-08-24 22:20:20 +00005602void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005603 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00005604 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005605 Results.EnterNewScope();
5606
5607 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00005608 CodeCompletionBuilder Builder(Results.getAllocator());
5609 Builder.AddTypedTextChunk("if");
5610 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5611 Builder.AddPlaceholderChunk("condition");
5612 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005613
5614 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00005615 Builder.AddTypedTextChunk("ifdef");
5616 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5617 Builder.AddPlaceholderChunk("macro");
5618 Results.AddResult(Builder.TakeString());
5619
Douglas Gregorf44e8542010-08-24 19:08:16 +00005620 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00005621 Builder.AddTypedTextChunk("ifndef");
5622 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5623 Builder.AddPlaceholderChunk("macro");
5624 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005625
5626 if (InConditional) {
5627 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00005628 Builder.AddTypedTextChunk("elif");
5629 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5630 Builder.AddPlaceholderChunk("condition");
5631 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005632
5633 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00005634 Builder.AddTypedTextChunk("else");
5635 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005636
5637 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00005638 Builder.AddTypedTextChunk("endif");
5639 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005640 }
5641
5642 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00005643 Builder.AddTypedTextChunk("include");
5644 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5645 Builder.AddTextChunk("\"");
5646 Builder.AddPlaceholderChunk("header");
5647 Builder.AddTextChunk("\"");
5648 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005649
5650 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00005651 Builder.AddTypedTextChunk("include");
5652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5653 Builder.AddTextChunk("<");
5654 Builder.AddPlaceholderChunk("header");
5655 Builder.AddTextChunk(">");
5656 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005657
5658 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00005659 Builder.AddTypedTextChunk("define");
5660 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5661 Builder.AddPlaceholderChunk("macro");
5662 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005663
5664 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00005665 Builder.AddTypedTextChunk("define");
5666 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5667 Builder.AddPlaceholderChunk("macro");
5668 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5669 Builder.AddPlaceholderChunk("args");
5670 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5671 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005672
5673 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00005674 Builder.AddTypedTextChunk("undef");
5675 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5676 Builder.AddPlaceholderChunk("macro");
5677 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005678
5679 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00005680 Builder.AddTypedTextChunk("line");
5681 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5682 Builder.AddPlaceholderChunk("number");
5683 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005684
5685 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00005686 Builder.AddTypedTextChunk("line");
5687 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5688 Builder.AddPlaceholderChunk("number");
5689 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5690 Builder.AddTextChunk("\"");
5691 Builder.AddPlaceholderChunk("filename");
5692 Builder.AddTextChunk("\"");
5693 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005694
5695 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00005696 Builder.AddTypedTextChunk("error");
5697 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5698 Builder.AddPlaceholderChunk("message");
5699 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005700
5701 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00005702 Builder.AddTypedTextChunk("pragma");
5703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5704 Builder.AddPlaceholderChunk("arguments");
5705 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005706
5707 if (getLangOptions().ObjC1) {
5708 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00005709 Builder.AddTypedTextChunk("import");
5710 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5711 Builder.AddTextChunk("\"");
5712 Builder.AddPlaceholderChunk("header");
5713 Builder.AddTextChunk("\"");
5714 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005715
5716 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00005717 Builder.AddTypedTextChunk("import");
5718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5719 Builder.AddTextChunk("<");
5720 Builder.AddPlaceholderChunk("header");
5721 Builder.AddTextChunk(">");
5722 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005723 }
5724
5725 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00005726 Builder.AddTypedTextChunk("include_next");
5727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5728 Builder.AddTextChunk("\"");
5729 Builder.AddPlaceholderChunk("header");
5730 Builder.AddTextChunk("\"");
5731 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005732
5733 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00005734 Builder.AddTypedTextChunk("include_next");
5735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5736 Builder.AddTextChunk("<");
5737 Builder.AddPlaceholderChunk("header");
5738 Builder.AddTextChunk(">");
5739 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005740
5741 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00005742 Builder.AddTypedTextChunk("warning");
5743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5744 Builder.AddPlaceholderChunk("message");
5745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00005746
5747 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5748 // completions for them. And __include_macros is a Clang-internal extension
5749 // that we don't want to encourage anyone to use.
5750
5751 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5752 Results.ExitScope();
5753
Douglas Gregorf44e8542010-08-24 19:08:16 +00005754 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005755 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005756 Results.data(), Results.size());
5757}
5758
5759void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005760 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005761 S->getFnParent()? Sema::PCC_RecoveryInFunction
5762 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005763}
5764
Douglas Gregorf29c5232010-08-24 22:20:20 +00005765void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005766 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00005767 IsDefinition? CodeCompletionContext::CCC_MacroName
5768 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005769 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5770 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00005771 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005772 Results.EnterNewScope();
5773 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5774 MEnd = PP.macro_end();
5775 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00005776 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005777 M->first->getName()));
5778 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005779 }
5780 Results.ExitScope();
5781 } else if (IsDefinition) {
5782 // FIXME: Can we detect when the user just wrote an include guard above?
5783 }
5784
Douglas Gregor52779fb2010-09-23 23:01:17 +00005785 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005786 Results.data(), Results.size());
5787}
5788
Douglas Gregorf29c5232010-08-24 22:20:20 +00005789void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00005790 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00005791 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005792
5793 if (!CodeCompleter || CodeCompleter->includeMacros())
5794 AddMacroResults(PP, Results);
5795
5796 // defined (<macro>)
5797 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00005798 CodeCompletionBuilder Builder(Results.getAllocator());
5799 Builder.AddTypedTextChunk("defined");
5800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5801 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5802 Builder.AddPlaceholderChunk("macro");
5803 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5804 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00005805 Results.ExitScope();
5806
5807 HandleCodeCompleteResults(this, CodeCompleter,
5808 CodeCompletionContext::CCC_PreprocessorExpression,
5809 Results.data(), Results.size());
5810}
5811
5812void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5813 IdentifierInfo *Macro,
5814 MacroInfo *MacroInfo,
5815 unsigned Argument) {
5816 // FIXME: In the future, we could provide "overload" results, much like we
5817 // do for function calls.
5818
5819 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005820 S->getFnParent()? Sema::PCC_RecoveryInFunction
5821 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005822}
5823
Douglas Gregor55817af2010-08-25 17:04:25 +00005824void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005825 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005826 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005827 0, 0);
5828}
5829
Douglas Gregordae68752011-02-01 22:57:45 +00005830void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
John McCall0a2c5e22010-08-25 06:19:51 +00005831 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005832 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00005833 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5834 CodeCompletionDeclConsumer Consumer(Builder,
5835 Context.getTranslationUnitDecl());
5836 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5837 Consumer);
5838 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005839
5840 if (!CodeCompleter || CodeCompleter->includeMacros())
5841 AddMacroResults(PP, Builder);
5842
5843 Results.clear();
5844 Results.insert(Results.end(),
5845 Builder.data(), Builder.data() + Builder.size());
5846}