blob: e74e70c725ab1424192a71b2d0b03d0180d12ed6 [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 Gregorc5b2e582012-01-29 18:15:03 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000024#include "clang/Lex/MacroInfo.h"
25#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramer013b3662012-01-30 16:17:39 +000027#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000028#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000029#include "llvm/ADT/SmallString.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000030#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000031#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000032#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000033#include <list>
34#include <map>
35#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
37using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000038using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000039
Douglas Gregor86d9a522009-09-21 16:56:56 +000040namespace {
41 /// \brief A container of code-completion results.
42 class ResultBuilder {
43 public:
44 /// \brief The type of a name-lookup filter, which can be provided to the
45 /// name-lookup routines to specify which declarations should be included in
46 /// the result set (when it returns true) and which declarations should be
47 /// filtered out (returns false).
48 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
49
John McCall0a2c5e22010-08-25 06:19:51 +000050 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000051
52 private:
53 /// \brief The actual results we have found.
54 std::vector<Result> Results;
55
56 /// \brief A record of all of the declarations we have found and placed
57 /// into the result set, used to ensure that no declaration ever gets into
58 /// the result set twice.
59 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
60
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000061 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
62
63 /// \brief An entry in the shadow map, which is optimized to store
64 /// a single (declaration, index) mapping (the common case) but
65 /// can also store a list of (declaration, index) mappings.
66 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000068
69 /// \brief Contains either the solitary NamedDecl * or a vector
70 /// of (declaration, index) pairs.
71 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
72
73 /// \brief When the entry contains a single declaration, this is
74 /// the index associated with that entry.
75 unsigned SingleDeclIndex;
76
77 public:
78 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
79
80 void Add(NamedDecl *ND, unsigned Index) {
81 if (DeclOrVector.isNull()) {
82 // 0 - > 1 elements: just set the single element information.
83 DeclOrVector = ND;
84 SingleDeclIndex = Index;
85 return;
86 }
87
88 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
89 // 1 -> 2 elements: create the vector of results and push in the
90 // existing declaration.
91 DeclIndexPairVector *Vec = new DeclIndexPairVector;
92 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
93 DeclOrVector = Vec;
94 }
95
96 // Add the new element to the end of the vector.
97 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
98 DeclIndexPair(ND, Index));
99 }
100
101 void Destroy() {
102 if (DeclIndexPairVector *Vec
103 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
104 delete Vec;
105 DeclOrVector = ((NamedDecl *)0);
106 }
107 }
108
109 // Iteration.
110 class iterator;
111 iterator begin() const;
112 iterator end() const;
113 };
114
Douglas Gregor86d9a522009-09-21 16:56:56 +0000115 /// \brief A mapping from declaration names to the declarations that have
116 /// this name within a particular scope and their index within the list of
117 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000118 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000119
120 /// \brief The semantic analysis object for which results are being
121 /// produced.
122 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000123
124 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000125 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000126
127 /// \brief If non-NULL, a filter function used to remove any code-completion
128 /// results that are not desirable.
129 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000130
131 /// \brief Whether we should allow declarations as
132 /// nested-name-specifiers that would otherwise be filtered out.
133 bool AllowNestedNameSpecifiers;
134
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000135 /// \brief If set, the type that we would prefer our resulting value
136 /// declarations to have.
137 ///
138 /// Closely matching the preferred type gives a boost to a result's
139 /// priority.
140 CanQualType PreferredType;
141
Douglas Gregor86d9a522009-09-21 16:56:56 +0000142 /// \brief A list of shadow maps, which is used to model name hiding at
143 /// different levels of, e.g., the inheritance hierarchy.
144 std::list<ShadowMap> ShadowMaps;
145
Douglas Gregor3cdee122010-08-26 16:36:48 +0000146 /// \brief If we're potentially referring to a C++ member function, the set
147 /// of qualifiers applied to the object type.
148 Qualifiers ObjectTypeQualifiers;
149
150 /// \brief Whether the \p ObjectTypeQualifiers field is active.
151 bool HasObjectTypeQualifiers;
152
Douglas Gregor265f7492010-08-27 15:29:55 +0000153 /// \brief The selector that we prefer.
154 Selector PreferredSelector;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000157 CodeCompletionContext CompletionContext;
158
Douglas Gregorca45da02010-11-02 20:36:02 +0000159 /// \brief If we are in an instance method definition, the @implementation
160 /// object.
161 ObjCImplementationDecl *ObjCImplementation;
162
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000163 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000164
Douglas Gregor6f942b22010-09-21 16:06:22 +0000165 void MaybeAddConstructorResults(Result R);
166
Douglas Gregor86d9a522009-09-21 16:56:56 +0000167 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000168 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000169 const CodeCompletionContext &CompletionContext,
170 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000171 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
172 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000173 CompletionContext(CompletionContext),
174 ObjCImplementation(0)
175 {
176 // If this is an Objective-C instance method definition, dig out the
177 // corresponding implementation.
178 switch (CompletionContext.getKind()) {
179 case CodeCompletionContext::CCC_Expression:
180 case CodeCompletionContext::CCC_ObjCMessageReceiver:
181 case CodeCompletionContext::CCC_ParenthesizedExpression:
182 case CodeCompletionContext::CCC_Statement:
183 case CodeCompletionContext::CCC_Recovery:
184 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
185 if (Method->isInstanceMethod())
186 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
187 ObjCImplementation = Interface->getImplementation();
188 break;
189
190 default:
191 break;
192 }
193 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000194
Douglas Gregord8e8a582010-05-25 21:41:55 +0000195 /// \brief Whether we should include code patterns in the completion
196 /// results.
197 bool includeCodePatterns() const {
198 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000199 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000200 }
201
Douglas Gregor86d9a522009-09-21 16:56:56 +0000202 /// \brief Set the filter used for code-completion results.
203 void setFilter(LookupFilter Filter) {
204 this->Filter = Filter;
205 }
206
Douglas Gregor86d9a522009-09-21 16:56:56 +0000207 Result *data() { return Results.empty()? 0 : &Results.front(); }
208 unsigned size() const { return Results.size(); }
209 bool empty() const { return Results.empty(); }
210
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000211 /// \brief Specify the preferred type.
212 void setPreferredType(QualType T) {
213 PreferredType = SemaRef.Context.getCanonicalType(T);
214 }
215
Douglas Gregor3cdee122010-08-26 16:36:48 +0000216 /// \brief Set the cv-qualifiers on the object type, for us in filtering
217 /// calls to member functions.
218 ///
219 /// When there are qualifiers in this set, they will be used to filter
220 /// out member functions that aren't available (because there will be a
221 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
222 /// match.
223 void setObjectTypeQualifiers(Qualifiers Quals) {
224 ObjectTypeQualifiers = Quals;
225 HasObjectTypeQualifiers = true;
226 }
227
Douglas Gregor265f7492010-08-27 15:29:55 +0000228 /// \brief Set the preferred selector.
229 ///
230 /// When an Objective-C method declaration result is added, and that
231 /// method's selector matches this preferred selector, we give that method
232 /// a slight priority boost.
233 void setPreferredSelector(Selector Sel) {
234 PreferredSelector = Sel;
235 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000236
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000237 /// \brief Retrieve the code-completion context for which results are
238 /// being collected.
239 const CodeCompletionContext &getCompletionContext() const {
240 return CompletionContext;
241 }
242
Douglas Gregor45bcd432010-01-14 03:21:49 +0000243 /// \brief Specify whether nested-name-specifiers are allowed.
244 void allowNestedNameSpecifiers(bool Allow = true) {
245 AllowNestedNameSpecifiers = Allow;
246 }
247
Douglas Gregorb9d77572010-09-21 00:03:25 +0000248 /// \brief Return the semantic analysis object for which we are collecting
249 /// code completion results.
250 Sema &getSema() const { return SemaRef; }
251
Douglas Gregor218937c2011-02-01 19:23:04 +0000252 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000253 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000254
Douglas Gregore495b7f2010-01-14 00:20:49 +0000255 /// \brief Determine whether the given declaration is at all interesting
256 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000257 ///
258 /// \param ND the declaration that we are inspecting.
259 ///
260 /// \param AsNestedNameSpecifier will be set true if this declaration is
261 /// only interesting when it is a nested-name-specifier.
262 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000263
264 /// \brief Check whether the result is hidden by the Hiding declaration.
265 ///
266 /// \returns true if the result is hidden and cannot be found, false if
267 /// the hidden result could still be found. When false, \p R may be
268 /// modified to describe how the result can be found (e.g., via extra
269 /// qualification).
270 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
271 NamedDecl *Hiding);
272
Douglas Gregor86d9a522009-09-21 16:56:56 +0000273 /// \brief Add a new result to this result set (if it isn't already in one
274 /// of the shadow maps), or replace an existing result (for, e.g., a
275 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000276 ///
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000277 /// \param R the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000278 ///
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000279 /// \param CurContext the context in which this result will be named.
Douglas Gregor456c4a12009-09-21 20:12:40 +0000280 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000281
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000282 /// \brief Add a new result to this result set, where we already know
283 /// the hiding declation (if any).
284 ///
285 /// \param R the result to add (if it is unique).
286 ///
287 /// \param CurContext the context in which this result will be named.
288 ///
289 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000290 ///
291 /// \param InBaseClass whether the result was found in a base
292 /// class of the searched context.
293 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
294 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000295
Douglas Gregora4477812010-01-14 16:01:26 +0000296 /// \brief Add a new non-declaration result to this result set.
297 void AddResult(Result R);
298
Douglas Gregor86d9a522009-09-21 16:56:56 +0000299 /// \brief Enter into a new scope.
300 void EnterNewScope();
301
302 /// \brief Exit from the current scope.
303 void ExitScope();
304
Douglas Gregor55385fe2009-11-18 04:19:12 +0000305 /// \brief Ignore this declaration, if it is seen again.
306 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
307
Douglas Gregor86d9a522009-09-21 16:56:56 +0000308 /// \name Name lookup predicates
309 ///
310 /// These predicates can be passed to the name lookup functions to filter the
311 /// results of name lookup. All of the predicates have the same type, so that
312 ///
313 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000314 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000315 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000316 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000317 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000318 bool IsNestedNameSpecifier(NamedDecl *ND) const;
319 bool IsEnum(NamedDecl *ND) const;
320 bool IsClassOrStruct(NamedDecl *ND) const;
321 bool IsUnion(NamedDecl *ND) const;
322 bool IsNamespace(NamedDecl *ND) const;
323 bool IsNamespaceOrAlias(NamedDecl *ND) const;
324 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000325 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000326 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000327 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000328 bool IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000329 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000330 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000331 //@}
332 };
333}
334
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000335class ResultBuilder::ShadowMapEntry::iterator {
336 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
337 unsigned SingleDeclIndex;
338
339public:
340 typedef DeclIndexPair value_type;
341 typedef value_type reference;
342 typedef std::ptrdiff_t difference_type;
343 typedef std::input_iterator_tag iterator_category;
344
345 class pointer {
346 DeclIndexPair Value;
347
348 public:
349 pointer(const DeclIndexPair &Value) : Value(Value) { }
350
351 const DeclIndexPair *operator->() const {
352 return &Value;
353 }
354 };
355
356 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
357
358 iterator(NamedDecl *SingleDecl, unsigned Index)
359 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
360
361 iterator(const DeclIndexPair *Iterator)
362 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
363
364 iterator &operator++() {
365 if (DeclOrIterator.is<NamedDecl *>()) {
366 DeclOrIterator = (NamedDecl *)0;
367 SingleDeclIndex = 0;
368 return *this;
369 }
370
371 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
372 ++I;
373 DeclOrIterator = I;
374 return *this;
375 }
376
Chris Lattner66392d42010-09-04 18:12:20 +0000377 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378 iterator tmp(*this);
379 ++(*this);
380 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000381 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000382
383 reference operator*() const {
384 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
385 return reference(ND, SingleDeclIndex);
386
Douglas Gregord490f952009-12-06 21:27:58 +0000387 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000388 }
389
390 pointer operator->() const {
391 return pointer(**this);
392 }
393
394 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000395 return X.DeclOrIterator.getOpaqueValue()
396 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000397 X.SingleDeclIndex == Y.SingleDeclIndex;
398 }
399
400 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000401 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000402 }
403};
404
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000405ResultBuilder::ShadowMapEntry::iterator
406ResultBuilder::ShadowMapEntry::begin() const {
407 if (DeclOrVector.isNull())
408 return iterator();
409
410 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
411 return iterator(ND, SingleDeclIndex);
412
413 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
414}
415
416ResultBuilder::ShadowMapEntry::iterator
417ResultBuilder::ShadowMapEntry::end() const {
418 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
419 return iterator();
420
421 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
422}
423
Douglas Gregor456c4a12009-09-21 20:12:40 +0000424/// \brief Compute the qualification required to get from the current context
425/// (\p CurContext) to the target context (\p TargetContext).
426///
427/// \param Context the AST context in which the qualification will be used.
428///
429/// \param CurContext the context where an entity is being named, which is
430/// typically based on the current scope.
431///
432/// \param TargetContext the context in which the named entity actually
433/// resides.
434///
435/// \returns a nested name specifier that refers into the target context, or
436/// NULL if no qualification is needed.
437static NestedNameSpecifier *
438getRequiredQualification(ASTContext &Context,
439 DeclContext *CurContext,
440 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000442
443 for (DeclContext *CommonAncestor = TargetContext;
444 CommonAncestor && !CommonAncestor->Encloses(CurContext);
445 CommonAncestor = CommonAncestor->getLookupParent()) {
446 if (CommonAncestor->isTransparentContext() ||
447 CommonAncestor->isFunctionOrMethod())
448 continue;
449
450 TargetParents.push_back(CommonAncestor);
451 }
452
453 NestedNameSpecifier *Result = 0;
454 while (!TargetParents.empty()) {
455 DeclContext *Parent = TargetParents.back();
456 TargetParents.pop_back();
457
Douglas Gregorfb629412010-08-23 21:17:50 +0000458 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
459 if (!Namespace->getIdentifier())
460 continue;
461
Douglas Gregor456c4a12009-09-21 20:12:40 +0000462 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000463 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000464 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
465 Result = NestedNameSpecifier::Create(Context, Result,
466 false,
467 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000468 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000469 return Result;
470}
471
Douglas Gregor45bcd432010-01-14 03:21:49 +0000472bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
473 bool &AsNestedNameSpecifier) const {
474 AsNestedNameSpecifier = false;
475
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 ND = ND->getUnderlyingDecl();
477 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000478
479 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000480 if (!ND->getDeclName())
481 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000482
483 // Friend declarations and declarations introduced due to friends are never
484 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000485 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000486 return false;
487
Douglas Gregor76282942009-12-11 17:31:05 +0000488 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000489 if (isa<ClassTemplateSpecializationDecl>(ND) ||
490 isa<ClassTemplatePartialSpecializationDecl>(ND))
491 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000492
Douglas Gregor76282942009-12-11 17:31:05 +0000493 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000494 if (isa<UsingDecl>(ND))
495 return false;
496
497 // Some declarations have reserved names that we don't want to ever show.
498 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000499 // __va_list_tag is a freak of nature. Find it and skip it.
500 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000501 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000502
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000504 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000505 //
506 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000507 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000508 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000509 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000510 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
511 (ND->getLocation().isInvalid() ||
512 SemaRef.SourceMgr.isInSystemHeader(
513 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000514 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000515 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000516 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000517
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000518 // Skip out-of-line declarations and definitions.
519 // NOTE: Unless it's an Objective-C property, method, or ivar, where
520 // the contexts can be messy.
521 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
522 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
523 isa<ObjCMethodDecl>(ND)))
524 return false;
525
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000526 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
527 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
528 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000529 Filter != &ResultBuilder::IsNamespaceOrAlias &&
530 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000531 AsNestedNameSpecifier = true;
532
Douglas Gregor86d9a522009-09-21 16:56:56 +0000533 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000534 if (Filter && !(this->*Filter)(ND)) {
535 // Check whether it is interesting as a nested-name-specifier.
536 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
537 IsNestedNameSpecifier(ND) &&
538 (Filter != &ResultBuilder::IsMember ||
539 (isa<CXXRecordDecl>(ND) &&
540 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
541 AsNestedNameSpecifier = true;
542 return true;
543 }
544
Douglas Gregore495b7f2010-01-14 00:20:49 +0000545 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000546 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000547 // ... then it must be interesting!
548 return true;
549}
550
Douglas Gregor6660d842010-01-14 00:41:07 +0000551bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
552 NamedDecl *Hiding) {
553 // In C, there is no way to refer to a hidden name.
554 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
555 // name if we introduce the tag type.
556 if (!SemaRef.getLangOptions().CPlusPlus)
557 return true;
558
Sebastian Redl7a126a42010-08-31 00:36:30 +0000559 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000560
561 // There is no way to qualify a name declared in a function or method.
562 if (HiddenCtx->isFunctionOrMethod())
563 return true;
564
Sebastian Redl7a126a42010-08-31 00:36:30 +0000565 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000566 return true;
567
568 // We can refer to the result with the appropriate qualification. Do it.
569 R.Hidden = true;
570 R.QualifierIsInformative = false;
571
572 if (!R.Qualifier)
573 R.Qualifier = getRequiredQualification(SemaRef.Context,
574 CurContext,
575 R.Declaration->getDeclContext());
576 return false;
577}
578
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000579/// \brief A simplified classification of types used to determine whether two
580/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000581SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000582 switch (T->getTypeClass()) {
583 case Type::Builtin:
584 switch (cast<BuiltinType>(T)->getKind()) {
585 case BuiltinType::Void:
586 return STC_Void;
587
588 case BuiltinType::NullPtr:
589 return STC_Pointer;
590
591 case BuiltinType::Overload:
592 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000593 return STC_Other;
594
595 case BuiltinType::ObjCId:
596 case BuiltinType::ObjCClass:
597 case BuiltinType::ObjCSel:
598 return STC_ObjectiveC;
599
600 default:
601 return STC_Arithmetic;
602 }
David Blaikie7530c032012-01-17 06:56:22 +0000603
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000604 case Type::Complex:
605 return STC_Arithmetic;
606
607 case Type::Pointer:
608 return STC_Pointer;
609
610 case Type::BlockPointer:
611 return STC_Block;
612
613 case Type::LValueReference:
614 case Type::RValueReference:
615 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
616
617 case Type::ConstantArray:
618 case Type::IncompleteArray:
619 case Type::VariableArray:
620 case Type::DependentSizedArray:
621 return STC_Array;
622
623 case Type::DependentSizedExtVector:
624 case Type::Vector:
625 case Type::ExtVector:
626 return STC_Arithmetic;
627
628 case Type::FunctionProto:
629 case Type::FunctionNoProto:
630 return STC_Function;
631
632 case Type::Record:
633 return STC_Record;
634
635 case Type::Enum:
636 return STC_Arithmetic;
637
638 case Type::ObjCObject:
639 case Type::ObjCInterface:
640 case Type::ObjCObjectPointer:
641 return STC_ObjectiveC;
642
643 default:
644 return STC_Other;
645 }
646}
647
648/// \brief Get the type that a given expression will have if this declaration
649/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000650QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000651 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
652
653 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
654 return C.getTypeDeclType(Type);
655 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
656 return C.getObjCInterfaceType(Iface);
657
658 QualType T;
659 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000660 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000661 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000662 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000663 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000664 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000665 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
666 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
667 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
668 T = Property->getType();
669 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
670 T = Value->getType();
671 else
672 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000673
674 // Dig through references, function pointers, and block pointers to
675 // get down to the likely type of an expression when the entity is
676 // used.
677 do {
678 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
679 T = Ref->getPointeeType();
680 continue;
681 }
682
683 if (const PointerType *Pointer = T->getAs<PointerType>()) {
684 if (Pointer->getPointeeType()->isFunctionType()) {
685 T = Pointer->getPointeeType();
686 continue;
687 }
688
689 break;
690 }
691
692 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
693 T = Block->getPointeeType();
694 continue;
695 }
696
697 if (const FunctionType *Function = T->getAs<FunctionType>()) {
698 T = Function->getResultType();
699 continue;
700 }
701
702 break;
703 } while (true);
704
705 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000706}
707
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000708void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
709 // If this is an Objective-C method declaration whose selector matches our
710 // preferred selector, give it a priority boost.
711 if (!PreferredSelector.isNull())
712 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
713 if (PreferredSelector == Method->getSelector())
714 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000715
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000716 // If we have a preferred type, adjust the priority for results with exactly-
717 // matching or nearly-matching types.
718 if (!PreferredType.isNull()) {
719 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
720 if (!T.isNull()) {
721 CanQualType TC = SemaRef.Context.getCanonicalType(T);
722 // Check for exactly-matching types (modulo qualifiers).
723 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
724 R.Priority /= CCF_ExactTypeMatch;
725 // Check for nearly-matching types, based on classification of each.
726 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000727 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000728 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
729 R.Priority /= CCF_SimilarTypeMatch;
730 }
731 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000732}
733
Douglas Gregor6f942b22010-09-21 16:06:22 +0000734void ResultBuilder::MaybeAddConstructorResults(Result R) {
735 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
736 !CompletionContext.wantConstructorResults())
737 return;
738
739 ASTContext &Context = SemaRef.Context;
740 NamedDecl *D = R.Declaration;
741 CXXRecordDecl *Record = 0;
742 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
743 Record = ClassTemplate->getTemplatedDecl();
744 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
745 // Skip specializations and partial specializations.
746 if (isa<ClassTemplateSpecializationDecl>(Record))
747 return;
748 } else {
749 // There are no constructors here.
750 return;
751 }
752
753 Record = Record->getDefinition();
754 if (!Record)
755 return;
756
757
758 QualType RecordTy = Context.getTypeDeclType(Record);
759 DeclarationName ConstructorName
760 = Context.DeclarationNames.getCXXConstructorName(
761 Context.getCanonicalType(RecordTy));
762 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
763 Ctors.first != Ctors.second; ++Ctors.first) {
764 R.Declaration = *Ctors.first;
765 R.CursorKind = getCursorKindForDecl(R.Declaration);
766 Results.push_back(R);
767 }
768}
769
Douglas Gregore495b7f2010-01-14 00:20:49 +0000770void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
771 assert(!ShadowMaps.empty() && "Must enter into a results scope");
772
773 if (R.Kind != Result::RK_Declaration) {
774 // For non-declaration results, just add the result.
775 Results.push_back(R);
776 return;
777 }
778
779 // Look through using declarations.
780 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
781 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
782 return;
783 }
784
785 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
786 unsigned IDNS = CanonDecl->getIdentifierNamespace();
787
Douglas Gregor45bcd432010-01-14 03:21:49 +0000788 bool AsNestedNameSpecifier = false;
789 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000790 return;
791
Douglas Gregor6f942b22010-09-21 16:06:22 +0000792 // C++ constructors are never found by name lookup.
793 if (isa<CXXConstructorDecl>(R.Declaration))
794 return;
795
Douglas Gregor86d9a522009-09-21 16:56:56 +0000796 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000797 ShadowMapEntry::iterator I, IEnd;
798 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
799 if (NamePos != SMap.end()) {
800 I = NamePos->second.begin();
801 IEnd = NamePos->second.end();
802 }
803
804 for (; I != IEnd; ++I) {
805 NamedDecl *ND = I->first;
806 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000807 if (ND->getCanonicalDecl() == CanonDecl) {
808 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000809 Results[Index].Declaration = R.Declaration;
810
Douglas Gregor86d9a522009-09-21 16:56:56 +0000811 // We're done.
812 return;
813 }
814 }
815
816 // This is a new declaration in this scope. However, check whether this
817 // declaration name is hidden by a similarly-named declaration in an outer
818 // scope.
819 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
820 --SMEnd;
821 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000822 ShadowMapEntry::iterator I, IEnd;
823 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
824 if (NamePos != SM->end()) {
825 I = NamePos->second.begin();
826 IEnd = NamePos->second.end();
827 }
828 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000829 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000830 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000831 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
832 Decl::IDNS_ObjCProtocol)))
833 continue;
834
835 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000836 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000837 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000838 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000839 continue;
840
841 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000842 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000843 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000844
845 break;
846 }
847 }
848
849 // Make sure that any given declaration only shows up in the result set once.
850 if (!AllDeclsFound.insert(CanonDecl))
851 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000852
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 // If the filter is for nested-name-specifiers, then this result starts a
854 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000855 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000856 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000857 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000858 } else
859 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000860
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000862 if (R.QualifierIsInformative && !R.Qualifier &&
863 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000864 DeclContext *Ctx = R.Declaration->getDeclContext();
865 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
866 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
867 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
868 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
869 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
870 else
871 R.QualifierIsInformative = false;
872 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000873
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 // Insert this result into the set of results and into the current shadow
875 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000876 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000877 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000878
879 if (!AsNestedNameSpecifier)
880 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000881}
882
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000883void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000884 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000885 if (R.Kind != Result::RK_Declaration) {
886 // For non-declaration results, just add the result.
887 Results.push_back(R);
888 return;
889 }
890
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000891 // Look through using declarations.
892 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
893 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
894 return;
895 }
896
Douglas Gregor45bcd432010-01-14 03:21:49 +0000897 bool AsNestedNameSpecifier = false;
898 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000899 return;
900
Douglas Gregor6f942b22010-09-21 16:06:22 +0000901 // C++ constructors are never found by name lookup.
902 if (isa<CXXConstructorDecl>(R.Declaration))
903 return;
904
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000905 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
906 return;
907
908 // Make sure that any given declaration only shows up in the result set once.
909 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
910 return;
911
912 // If the filter is for nested-name-specifiers, then this result starts a
913 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000914 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000915 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000916 R.Priority = CCP_NestedNameSpecifier;
917 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
919 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000920 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000921 R.QualifierIsInformative = true;
922
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000923 // If this result is supposed to have an informative qualifier, add one.
924 if (R.QualifierIsInformative && !R.Qualifier &&
925 !R.StartsNestedNameSpecifier) {
926 DeclContext *Ctx = R.Declaration->getDeclContext();
927 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
928 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
929 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
930 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000931 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000932 else
933 R.QualifierIsInformative = false;
934 }
935
Douglas Gregor12e13132010-05-26 22:00:08 +0000936 // Adjust the priority if this result comes from a base class.
937 if (InBaseClass)
938 R.Priority += CCD_InBaseClass;
939
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000940 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000941
Douglas Gregor3cdee122010-08-26 16:36:48 +0000942 if (HasObjectTypeQualifiers)
943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
944 if (Method->isInstance()) {
945 Qualifiers MethodQuals
946 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
947 if (ObjectTypeQualifiers == MethodQuals)
948 R.Priority += CCD_ObjectQualifierMatch;
949 else if (ObjectTypeQualifiers - MethodQuals) {
950 // The method cannot be invoked, because doing so would drop
951 // qualifiers.
952 return;
953 }
954 }
955
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000956 // Insert this result into the set of results.
957 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000958
959 if (!AsNestedNameSpecifier)
960 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000961}
962
Douglas Gregora4477812010-01-14 16:01:26 +0000963void ResultBuilder::AddResult(Result R) {
964 assert(R.Kind != Result::RK_Declaration &&
965 "Declaration results need more context");
966 Results.push_back(R);
967}
968
Douglas Gregor86d9a522009-09-21 16:56:56 +0000969/// \brief Enter into a new scope.
970void ResultBuilder::EnterNewScope() {
971 ShadowMaps.push_back(ShadowMap());
972}
973
974/// \brief Exit from the current scope.
975void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000976 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
977 EEnd = ShadowMaps.back().end();
978 E != EEnd;
979 ++E)
980 E->second.Destroy();
981
Douglas Gregor86d9a522009-09-21 16:56:56 +0000982 ShadowMaps.pop_back();
983}
984
Douglas Gregor791215b2009-09-21 20:51:25 +0000985/// \brief Determines whether this given declaration will be found by
986/// ordinary name lookup.
987bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000988 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
989
Douglas Gregor791215b2009-09-21 20:51:25 +0000990 unsigned IDNS = Decl::IDNS_Ordinary;
991 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000992 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000993 else if (SemaRef.getLangOptions().ObjC1) {
994 if (isa<ObjCIvarDecl>(ND))
995 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000996 }
997
Douglas Gregor791215b2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// ordinary name lookup but is not a type name.
1003bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1004 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1005 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 return false;
1007
1008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 else if (SemaRef.getLangOptions().ObjC1) {
1012 if (isa<ObjCIvarDecl>(ND))
1013 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001014 }
1015
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001016 return ND->getIdentifierNamespace() & IDNS;
1017}
1018
Douglas Gregorf9578432010-07-28 21:50:18 +00001019bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1020 if (!IsOrdinaryNonTypeName(ND))
1021 return 0;
1022
1023 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1024 if (VD->getType()->isIntegralOrEnumerationType())
1025 return true;
1026
1027 return false;
1028}
1029
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001030/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001031/// ordinary name lookup.
1032bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001033 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1034
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035 unsigned IDNS = Decl::IDNS_Ordinary;
1036 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001037 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038
1039 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001040 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1041 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001042}
1043
Douglas Gregor86d9a522009-09-21 16:56:56 +00001044/// \brief Determines whether the given declaration is suitable as the
1045/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1046bool ResultBuilder::IsNestedNameSpecifier(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 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1052}
1053
1054/// \brief Determines whether the given declaration is an enumeration.
1055bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1056 return isa<EnumDecl>(ND);
1057}
1058
1059/// \brief Determines whether the given declaration is a class or struct.
1060bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1061 // Allow us to find class templates, too.
1062 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1063 ND = ClassTemplate->getTemplatedDecl();
1064
1065 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001066 return RD->getTagKind() == TTK_Class ||
1067 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001068
1069 return false;
1070}
1071
1072/// \brief Determines whether the given declaration is a union.
1073bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1074 // Allow us to find class templates, too.
1075 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1076 ND = ClassTemplate->getTemplatedDecl();
1077
1078 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001079 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001080
1081 return false;
1082}
1083
1084/// \brief Determines whether the given declaration is a namespace.
1085bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1086 return isa<NamespaceDecl>(ND);
1087}
1088
1089/// \brief Determines whether the given declaration is a namespace or
1090/// namespace alias.
1091bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1092 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1093}
1094
Douglas Gregor76282942009-12-11 17:31:05 +00001095/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001096bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001097 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1098 ND = Using->getTargetDecl();
1099
1100 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001101}
1102
Douglas Gregor76282942009-12-11 17:31:05 +00001103/// \brief Determines which members of a class should be visible via
1104/// "." or "->". Only value declarations, nested name specifiers, and
1105/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001106bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001107 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1108 ND = Using->getTargetDecl();
1109
Douglas Gregorce821962009-12-11 18:14:22 +00001110 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1111 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001112}
1113
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001114static bool isObjCReceiverType(ASTContext &C, QualType T) {
1115 T = C.getCanonicalType(T);
1116 switch (T->getTypeClass()) {
1117 case Type::ObjCObject:
1118 case Type::ObjCInterface:
1119 case Type::ObjCObjectPointer:
1120 return true;
1121
1122 case Type::Builtin:
1123 switch (cast<BuiltinType>(T)->getKind()) {
1124 case BuiltinType::ObjCId:
1125 case BuiltinType::ObjCClass:
1126 case BuiltinType::ObjCSel:
1127 return true;
1128
1129 default:
1130 break;
1131 }
1132 return false;
1133
1134 default:
1135 break;
1136 }
1137
1138 if (!C.getLangOptions().CPlusPlus)
1139 return false;
1140
1141 // FIXME: We could perform more analysis here to determine whether a
1142 // particular class type has any conversions to Objective-C types. For now,
1143 // just accept all class types.
1144 return T->isDependentType() || T->isRecordType();
1145}
1146
1147bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1148 QualType T = getDeclUsageType(SemaRef.Context, ND);
1149 if (T.isNull())
1150 return false;
1151
1152 T = SemaRef.Context.getBaseElementType(T);
1153 return isObjCReceiverType(SemaRef.Context, T);
1154}
1155
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001156bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const {
1157 if (IsObjCMessageReceiver(ND))
1158 return true;
1159
1160 VarDecl *Var = dyn_cast<VarDecl>(ND);
1161 if (!Var)
1162 return false;
1163
1164 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1165}
1166
Douglas Gregorfb629412010-08-23 21:17:50 +00001167bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1168 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1169 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1170 return false;
1171
1172 QualType T = getDeclUsageType(SemaRef.Context, ND);
1173 if (T.isNull())
1174 return false;
1175
1176 T = SemaRef.Context.getBaseElementType(T);
1177 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1178 T->isObjCIdType() ||
1179 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1180}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001181
Douglas Gregor52779fb2010-09-23 23:01:17 +00001182bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1183 return false;
1184}
1185
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001186/// \rief Determines whether the given declaration is an Objective-C
1187/// instance variable.
1188bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1189 return isa<ObjCIvarDecl>(ND);
1190}
1191
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001192namespace {
1193 /// \brief Visible declaration consumer that adds a code-completion result
1194 /// for each visible declaration.
1195 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1196 ResultBuilder &Results;
1197 DeclContext *CurContext;
1198
1199 public:
1200 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1201 : Results(Results), CurContext(CurContext) { }
1202
Erik Verbruggend1205962011-10-06 07:27:49 +00001203 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1204 bool InBaseClass) {
1205 bool Accessible = true;
Douglas Gregor17015ef2011-11-03 16:51:37 +00001206 if (Ctx)
1207 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1208
Erik Verbruggend1205962011-10-06 07:27:49 +00001209 ResultBuilder::Result Result(ND, 0, false, Accessible);
1210 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001211 }
1212 };
1213}
1214
Douglas Gregor86d9a522009-09-21 16:56:56 +00001215/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001216static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001217 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001218 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001219 Results.AddResult(Result("short", CCP_Type));
1220 Results.AddResult(Result("long", CCP_Type));
1221 Results.AddResult(Result("signed", CCP_Type));
1222 Results.AddResult(Result("unsigned", CCP_Type));
1223 Results.AddResult(Result("void", CCP_Type));
1224 Results.AddResult(Result("char", CCP_Type));
1225 Results.AddResult(Result("int", CCP_Type));
1226 Results.AddResult(Result("float", CCP_Type));
1227 Results.AddResult(Result("double", CCP_Type));
1228 Results.AddResult(Result("enum", CCP_Type));
1229 Results.AddResult(Result("struct", CCP_Type));
1230 Results.AddResult(Result("union", CCP_Type));
1231 Results.AddResult(Result("const", CCP_Type));
1232 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001233
Douglas Gregor86d9a522009-09-21 16:56:56 +00001234 if (LangOpts.C99) {
1235 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001236 Results.AddResult(Result("_Complex", CCP_Type));
1237 Results.AddResult(Result("_Imaginary", CCP_Type));
1238 Results.AddResult(Result("_Bool", CCP_Type));
1239 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001240 }
1241
Douglas Gregor218937c2011-02-01 19:23:04 +00001242 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001243 if (LangOpts.CPlusPlus) {
1244 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001245 Results.AddResult(Result("bool", CCP_Type +
1246 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001247 Results.AddResult(Result("class", CCP_Type));
1248 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001249
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001250 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001251 Builder.AddTypedTextChunk("typename");
1252 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1253 Builder.AddPlaceholderChunk("qualifier");
1254 Builder.AddTextChunk("::");
1255 Builder.AddPlaceholderChunk("name");
1256 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001257
Douglas Gregor86d9a522009-09-21 16:56:56 +00001258 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001259 Results.AddResult(Result("auto", CCP_Type));
1260 Results.AddResult(Result("char16_t", CCP_Type));
1261 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001262
Douglas Gregor218937c2011-02-01 19:23:04 +00001263 Builder.AddTypedTextChunk("decltype");
1264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1265 Builder.AddPlaceholderChunk("expression");
1266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001268 }
1269 }
1270
1271 // GNU extensions
1272 if (LangOpts.GNUMode) {
1273 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001274 // Results.AddResult(Result("_Decimal32"));
1275 // Results.AddResult(Result("_Decimal64"));
1276 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001277
Douglas Gregor218937c2011-02-01 19:23:04 +00001278 Builder.AddTypedTextChunk("typeof");
1279 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1280 Builder.AddPlaceholderChunk("expression");
1281 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001282
Douglas Gregor218937c2011-02-01 19:23:04 +00001283 Builder.AddTypedTextChunk("typeof");
1284 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1285 Builder.AddPlaceholderChunk("type");
1286 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1287 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001288 }
1289}
1290
John McCallf312b1e2010-08-26 23:41:50 +00001291static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001293 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001294 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 // Note: we don't suggest either "auto" or "register", because both
1296 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1297 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001298 Results.AddResult(Result("extern"));
1299 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300}
1301
John McCallf312b1e2010-08-26 23:41:50 +00001302static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001303 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001304 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001305 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001306 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001307 case Sema::PCC_Class:
1308 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001310 Results.AddResult(Result("explicit"));
1311 Results.AddResult(Result("friend"));
1312 Results.AddResult(Result("mutable"));
1313 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001314 }
1315 // Fall through
1316
John McCallf312b1e2010-08-26 23:41:50 +00001317 case Sema::PCC_ObjCInterface:
1318 case Sema::PCC_ObjCImplementation:
1319 case Sema::PCC_Namespace:
1320 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001321 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001322 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001323 break;
1324
John McCallf312b1e2010-08-26 23:41:50 +00001325 case Sema::PCC_ObjCInstanceVariableList:
1326 case Sema::PCC_Expression:
1327 case Sema::PCC_Statement:
1328 case Sema::PCC_ForInit:
1329 case Sema::PCC_Condition:
1330 case Sema::PCC_RecoveryInFunction:
1331 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001332 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001333 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001334 break;
1335 }
1336}
1337
Douglas Gregorbca403c2010-01-13 23:51:12 +00001338static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1339static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1340static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001341 ResultBuilder &Results,
1342 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001343static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001344 ResultBuilder &Results,
1345 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001346static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001347 ResultBuilder &Results,
1348 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001349static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001350
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001351static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001352 CodeCompletionBuilder Builder(Results.getAllocator());
1353 Builder.AddTypedTextChunk("typedef");
1354 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1355 Builder.AddPlaceholderChunk("type");
1356 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1357 Builder.AddPlaceholderChunk("name");
1358 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001359}
1360
John McCallf312b1e2010-08-26 23:41:50 +00001361static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001362 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001363 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001364 case Sema::PCC_Namespace:
1365 case Sema::PCC_Class:
1366 case Sema::PCC_ObjCInstanceVariableList:
1367 case Sema::PCC_Template:
1368 case Sema::PCC_MemberTemplate:
1369 case Sema::PCC_Statement:
1370 case Sema::PCC_RecoveryInFunction:
1371 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001372 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001373 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001374 return true;
1375
John McCallf312b1e2010-08-26 23:41:50 +00001376 case Sema::PCC_Expression:
1377 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001378 return LangOpts.CPlusPlus;
1379
1380 case Sema::PCC_ObjCInterface:
1381 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001382 return false;
1383
John McCallf312b1e2010-08-26 23:41:50 +00001384 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001385 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001386 }
David Blaikie7530c032012-01-17 06:56:22 +00001387
1388 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001389}
1390
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001391static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1392 const Preprocessor &PP) {
1393 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregor8ca72082011-10-18 21:20:17 +00001394 Policy.AnonymousTagLocations = false;
1395 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001396 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001397 return Policy;
1398}
1399
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001400/// \brief Retrieve a printing policy suitable for code completion.
1401static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1402 return getCompletionPrintingPolicy(S.Context, S.PP);
1403}
1404
Douglas Gregor8ca72082011-10-18 21:20:17 +00001405/// \brief Retrieve the string representation of the given type as a string
1406/// that has the appropriate lifetime for code completion.
1407///
1408/// This routine provides a fast path where we provide constant strings for
1409/// common type names.
1410static const char *GetCompletionTypeString(QualType T,
1411 ASTContext &Context,
1412 const PrintingPolicy &Policy,
1413 CodeCompletionAllocator &Allocator) {
1414 if (!T.getLocalQualifiers()) {
1415 // Built-in type names are constant strings.
1416 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1417 return BT->getName(Policy);
1418
1419 // Anonymous tag types are constant strings.
1420 if (const TagType *TagT = dyn_cast<TagType>(T))
1421 if (TagDecl *Tag = TagT->getDecl())
1422 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1423 switch (Tag->getTagKind()) {
1424 case TTK_Struct: return "struct <anonymous>";
1425 case TTK_Class: return "class <anonymous>";
1426 case TTK_Union: return "union <anonymous>";
1427 case TTK_Enum: return "enum <anonymous>";
1428 }
1429 }
1430 }
1431
1432 // Slow path: format the type as a string.
1433 std::string Result;
1434 T.getAsStringInternal(Result, Policy);
1435 return Allocator.CopyString(Result);
1436}
1437
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001438/// \brief Add a completion for "this", if we're in a member function.
1439static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1440 QualType ThisTy = S.getCurrentThisType();
1441 if (ThisTy.isNull())
1442 return;
1443
1444 CodeCompletionAllocator &Allocator = Results.getAllocator();
1445 CodeCompletionBuilder Builder(Allocator);
1446 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1447 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1448 S.Context,
1449 Policy,
1450 Allocator));
1451 Builder.AddTypedTextChunk("this");
1452 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1453}
1454
Douglas Gregor01dfea02010-01-10 23:08:15 +00001455/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001456static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001457 Scope *S,
1458 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001459 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001460 CodeCompletionAllocator &Allocator = Results.getAllocator();
1461 CodeCompletionBuilder Builder(Allocator);
1462 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001463
John McCall0a2c5e22010-08-25 06:19:51 +00001464 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001465 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001466 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001467 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001468 if (Results.includeCodePatterns()) {
1469 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001470 Builder.AddTypedTextChunk("namespace");
1471 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1472 Builder.AddPlaceholderChunk("identifier");
1473 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1474 Builder.AddPlaceholderChunk("declarations");
1475 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1476 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1477 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001478 }
1479
Douglas Gregor01dfea02010-01-10 23:08:15 +00001480 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001481 Builder.AddTypedTextChunk("namespace");
1482 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1483 Builder.AddPlaceholderChunk("name");
1484 Builder.AddChunk(CodeCompletionString::CK_Equal);
1485 Builder.AddPlaceholderChunk("namespace");
1486 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001487
1488 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001489 Builder.AddTypedTextChunk("using");
1490 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1491 Builder.AddTextChunk("namespace");
1492 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1493 Builder.AddPlaceholderChunk("identifier");
1494 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001495
1496 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001497 Builder.AddTypedTextChunk("asm");
1498 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1499 Builder.AddPlaceholderChunk("string-literal");
1500 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1501 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001502
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001503 if (Results.includeCodePatterns()) {
1504 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001505 Builder.AddTypedTextChunk("template");
1506 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1507 Builder.AddPlaceholderChunk("declaration");
1508 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001509 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001510 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001511
1512 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001513 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001514
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001515 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001516 // Fall through
1517
John McCallf312b1e2010-08-26 23:41:50 +00001518 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001519 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001520 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001521 Builder.AddTypedTextChunk("using");
1522 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1523 Builder.AddPlaceholderChunk("qualifier");
1524 Builder.AddTextChunk("::");
1525 Builder.AddPlaceholderChunk("name");
1526 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001527
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001528 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001529 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001530 Builder.AddTypedTextChunk("using");
1531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1532 Builder.AddTextChunk("typename");
1533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1534 Builder.AddPlaceholderChunk("qualifier");
1535 Builder.AddTextChunk("::");
1536 Builder.AddPlaceholderChunk("name");
1537 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001538 }
1539
John McCallf312b1e2010-08-26 23:41:50 +00001540 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001541 AddTypedefResult(Results);
1542
Douglas Gregor01dfea02010-01-10 23:08:15 +00001543 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001544 Builder.AddTypedTextChunk("public");
1545 Builder.AddChunk(CodeCompletionString::CK_Colon);
1546 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001547
1548 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001549 Builder.AddTypedTextChunk("protected");
1550 Builder.AddChunk(CodeCompletionString::CK_Colon);
1551 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001552
1553 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001554 Builder.AddTypedTextChunk("private");
1555 Builder.AddChunk(CodeCompletionString::CK_Colon);
1556 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001557 }
1558 }
1559 // Fall through
1560
John McCallf312b1e2010-08-26 23:41:50 +00001561 case Sema::PCC_Template:
1562 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001564 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001565 Builder.AddTypedTextChunk("template");
1566 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1567 Builder.AddPlaceholderChunk("parameters");
1568 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1569 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001570 }
1571
Douglas Gregorbca403c2010-01-13 23:51:12 +00001572 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1573 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001574 break;
1575
John McCallf312b1e2010-08-26 23:41:50 +00001576 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001577 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1578 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1579 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001580 break;
1581
John McCallf312b1e2010-08-26 23:41:50 +00001582 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001583 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1584 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1585 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001586 break;
1587
John McCallf312b1e2010-08-26 23:41:50 +00001588 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001589 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001590 break;
1591
John McCallf312b1e2010-08-26 23:41:50 +00001592 case Sema::PCC_RecoveryInFunction:
1593 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001594 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001595
Douglas Gregorec3310a2011-04-12 02:47:21 +00001596 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1597 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001598 Builder.AddTypedTextChunk("try");
1599 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1600 Builder.AddPlaceholderChunk("statements");
1601 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1602 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1603 Builder.AddTextChunk("catch");
1604 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1605 Builder.AddPlaceholderChunk("declaration");
1606 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1607 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1608 Builder.AddPlaceholderChunk("statements");
1609 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1610 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1611 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001612 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001613 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001614 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001615
Douglas Gregord8e8a582010-05-25 21:41:55 +00001616 if (Results.includeCodePatterns()) {
1617 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001618 Builder.AddTypedTextChunk("if");
1619 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001620 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001621 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001622 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001623 Builder.AddPlaceholderChunk("expression");
1624 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1625 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1626 Builder.AddPlaceholderChunk("statements");
1627 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1628 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1629 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001630
Douglas Gregord8e8a582010-05-25 21:41:55 +00001631 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001632 Builder.AddTypedTextChunk("switch");
1633 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001634 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001636 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001637 Builder.AddPlaceholderChunk("expression");
1638 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1639 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1640 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1641 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1642 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001643 }
1644
Douglas Gregor01dfea02010-01-10 23:08:15 +00001645 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001646 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001647 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001648 Builder.AddTypedTextChunk("case");
1649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1650 Builder.AddPlaceholderChunk("expression");
1651 Builder.AddChunk(CodeCompletionString::CK_Colon);
1652 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001653
1654 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Builder.AddTypedTextChunk("default");
1656 Builder.AddChunk(CodeCompletionString::CK_Colon);
1657 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001658 }
1659
Douglas Gregord8e8a582010-05-25 21:41:55 +00001660 if (Results.includeCodePatterns()) {
1661 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001662 Builder.AddTypedTextChunk("while");
1663 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001664 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001665 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001666 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001667 Builder.AddPlaceholderChunk("expression");
1668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1669 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1670 Builder.AddPlaceholderChunk("statements");
1671 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1672 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001674
1675 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001676 Builder.AddTypedTextChunk("do");
1677 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1678 Builder.AddPlaceholderChunk("statements");
1679 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1680 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1681 Builder.AddTextChunk("while");
1682 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1683 Builder.AddPlaceholderChunk("expression");
1684 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1685 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001686
Douglas Gregord8e8a582010-05-25 21:41:55 +00001687 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001688 Builder.AddTypedTextChunk("for");
1689 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001690 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001691 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001692 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001693 Builder.AddPlaceholderChunk("init-expression");
1694 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1695 Builder.AddPlaceholderChunk("condition");
1696 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1697 Builder.AddPlaceholderChunk("inc-expression");
1698 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1699 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1700 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1701 Builder.AddPlaceholderChunk("statements");
1702 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1703 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001705 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001706
1707 if (S->getContinueParent()) {
1708 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001709 Builder.AddTypedTextChunk("continue");
1710 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001711 }
1712
1713 if (S->getBreakParent()) {
1714 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001715 Builder.AddTypedTextChunk("break");
1716 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717 }
1718
1719 // "return expression ;" or "return ;", depending on whether we
1720 // know the function is void or not.
1721 bool isVoid = false;
1722 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1723 isVoid = Function->getResultType()->isVoidType();
1724 else if (ObjCMethodDecl *Method
1725 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1726 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001727 else if (SemaRef.getCurBlock() &&
1728 !SemaRef.getCurBlock()->ReturnType.isNull())
1729 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001730 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001731 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001732 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1733 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001734 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001735 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001736
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001737 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001738 Builder.AddTypedTextChunk("goto");
1739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1740 Builder.AddPlaceholderChunk("label");
1741 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001742
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001743 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001744 Builder.AddTypedTextChunk("using");
1745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1746 Builder.AddTextChunk("namespace");
1747 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1748 Builder.AddPlaceholderChunk("identifier");
1749 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001750 }
1751
1752 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001753 case Sema::PCC_ForInit:
1754 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001755 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001756 // Fall through: conditions and statements can have expressions.
1757
Douglas Gregor02688102010-09-14 23:59:36 +00001758 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001759 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1760 CCC == Sema::PCC_ParenthesizedExpression) {
1761 // (__bridge <type>)<expression>
1762 Builder.AddTypedTextChunk("__bridge");
1763 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1764 Builder.AddPlaceholderChunk("type");
1765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1766 Builder.AddPlaceholderChunk("expression");
1767 Results.AddResult(Result(Builder.TakeString()));
1768
1769 // (__bridge_transfer <Objective-C type>)<expression>
1770 Builder.AddTypedTextChunk("__bridge_transfer");
1771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1772 Builder.AddPlaceholderChunk("Objective-C type");
1773 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1774 Builder.AddPlaceholderChunk("expression");
1775 Results.AddResult(Result(Builder.TakeString()));
1776
1777 // (__bridge_retained <CF type>)<expression>
1778 Builder.AddTypedTextChunk("__bridge_retained");
1779 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1780 Builder.AddPlaceholderChunk("CF type");
1781 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1782 Builder.AddPlaceholderChunk("expression");
1783 Results.AddResult(Result(Builder.TakeString()));
1784 }
1785 // Fall through
1786
John McCallf312b1e2010-08-26 23:41:50 +00001787 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001788 if (SemaRef.getLangOptions().CPlusPlus) {
1789 // 'this', if we're in a non-static member function.
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001790 addThisCompletion(SemaRef, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001791
Douglas Gregor8ca72082011-10-18 21:20:17 +00001792 // true
1793 Builder.AddResultTypeChunk("bool");
1794 Builder.AddTypedTextChunk("true");
1795 Results.AddResult(Result(Builder.TakeString()));
1796
1797 // false
1798 Builder.AddResultTypeChunk("bool");
1799 Builder.AddTypedTextChunk("false");
1800 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001801
Douglas Gregorec3310a2011-04-12 02:47:21 +00001802 if (SemaRef.getLangOptions().RTTI) {
1803 // dynamic_cast < type-id > ( expression )
1804 Builder.AddTypedTextChunk("dynamic_cast");
1805 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1806 Builder.AddPlaceholderChunk("type");
1807 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1808 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1809 Builder.AddPlaceholderChunk("expression");
1810 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1811 Results.AddResult(Result(Builder.TakeString()));
1812 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001813
1814 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001815 Builder.AddTypedTextChunk("static_cast");
1816 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1817 Builder.AddPlaceholderChunk("type");
1818 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1819 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1820 Builder.AddPlaceholderChunk("expression");
1821 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1822 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001823
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001824 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001825 Builder.AddTypedTextChunk("reinterpret_cast");
1826 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1827 Builder.AddPlaceholderChunk("type");
1828 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1829 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1830 Builder.AddPlaceholderChunk("expression");
1831 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1832 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001833
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001834 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001835 Builder.AddTypedTextChunk("const_cast");
1836 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1837 Builder.AddPlaceholderChunk("type");
1838 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1839 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1840 Builder.AddPlaceholderChunk("expression");
1841 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1842 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001843
Douglas Gregorec3310a2011-04-12 02:47:21 +00001844 if (SemaRef.getLangOptions().RTTI) {
1845 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001846 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001847 Builder.AddTypedTextChunk("typeid");
1848 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1849 Builder.AddPlaceholderChunk("expression-or-type");
1850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1851 Results.AddResult(Result(Builder.TakeString()));
1852 }
1853
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001854 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001855 Builder.AddTypedTextChunk("new");
1856 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1857 Builder.AddPlaceholderChunk("type");
1858 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1859 Builder.AddPlaceholderChunk("expressions");
1860 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1861 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001862
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001863 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001864 Builder.AddTypedTextChunk("new");
1865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1866 Builder.AddPlaceholderChunk("type");
1867 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1868 Builder.AddPlaceholderChunk("size");
1869 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1870 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1871 Builder.AddPlaceholderChunk("expressions");
1872 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1873 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001874
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001875 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001876 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001877 Builder.AddTypedTextChunk("delete");
1878 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1879 Builder.AddPlaceholderChunk("expression");
1880 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001881
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001882 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001883 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001884 Builder.AddTypedTextChunk("delete");
1885 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1886 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1887 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1888 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1889 Builder.AddPlaceholderChunk("expression");
1890 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001891
Douglas Gregorec3310a2011-04-12 02:47:21 +00001892 if (SemaRef.getLangOptions().CXXExceptions) {
1893 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001894 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001895 Builder.AddTypedTextChunk("throw");
1896 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1897 Builder.AddPlaceholderChunk("expression");
1898 Results.AddResult(Result(Builder.TakeString()));
1899 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001900
Douglas Gregor12e13132010-05-26 22:00:08 +00001901 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001902
1903 if (SemaRef.getLangOptions().CPlusPlus0x) {
1904 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001905 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001906 Builder.AddTypedTextChunk("nullptr");
1907 Results.AddResult(Result(Builder.TakeString()));
1908
1909 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001910 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001911 Builder.AddTypedTextChunk("alignof");
1912 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1913 Builder.AddPlaceholderChunk("type");
1914 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1915 Results.AddResult(Result(Builder.TakeString()));
1916
1917 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001918 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001919 Builder.AddTypedTextChunk("noexcept");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1921 Builder.AddPlaceholderChunk("expression");
1922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1923 Results.AddResult(Result(Builder.TakeString()));
1924
1925 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001926 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001927 Builder.AddTypedTextChunk("sizeof...");
1928 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1929 Builder.AddPlaceholderChunk("parameter-pack");
1930 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1931 Results.AddResult(Result(Builder.TakeString()));
1932 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001933 }
1934
1935 if (SemaRef.getLangOptions().ObjC1) {
1936 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001937 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1938 // The interface can be NULL.
1939 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001940 if (ID->getSuperClass()) {
1941 std::string SuperType;
1942 SuperType = ID->getSuperClass()->getNameAsString();
1943 if (Method->isInstanceMethod())
1944 SuperType += " *";
1945
1946 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1947 Builder.AddTypedTextChunk("super");
1948 Results.AddResult(Result(Builder.TakeString()));
1949 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001950 }
1951
Douglas Gregorbca403c2010-01-13 23:51:12 +00001952 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001953 }
1954
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001955 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001956 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001957 Builder.AddTypedTextChunk("sizeof");
1958 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1959 Builder.AddPlaceholderChunk("expression-or-type");
1960 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1961 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001962 break;
1963 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001964
John McCallf312b1e2010-08-26 23:41:50 +00001965 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001966 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001967 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001968 }
1969
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001970 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1971 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001972
John McCallf312b1e2010-08-26 23:41:50 +00001973 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001974 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001975}
1976
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001977/// \brief If the given declaration has an associated type, add it as a result
1978/// type chunk.
1979static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001980 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001981 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001982 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001983 if (!ND)
1984 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001985
1986 // Skip constructors and conversion functions, which have their return types
1987 // built into their names.
1988 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1989 return;
1990
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001991 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001992 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001993 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1994 T = Function->getResultType();
1995 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1996 T = Method->getResultType();
1997 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1998 T = FunTmpl->getTemplatedDecl()->getResultType();
1999 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2000 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2001 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2002 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00002003 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002004 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002005 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002006 T = Property->getType();
2007
2008 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2009 return;
2010
Douglas Gregor8987b232011-09-27 23:30:47 +00002011 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002012 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002013}
2014
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002015static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00002016 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002017 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2018 if (Sentinel->getSentinel() == 0) {
2019 if (Context.getLangOptions().ObjC1 &&
2020 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00002021 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002022 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00002023 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002024 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002025 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002026 }
2027}
2028
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002029static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2030 std::string Result;
2031 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002032 Result += "in ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002033 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002034 Result += "inout ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002035 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002036 Result += "out ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002037 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002038 Result += "bycopy ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002039 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002040 Result += "byref ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002041 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002042 Result += "oneway ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002043 return Result;
2044}
2045
Douglas Gregor83482d12010-08-24 16:15:59 +00002046static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002047 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002048 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002049 bool SuppressName = false,
2050 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002051 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2052 if (Param->getType()->isDependentType() ||
2053 !Param->getType()->isBlockPointerType()) {
2054 // The argument for a dependent or non-block parameter is a placeholder
2055 // containing that parameter's type.
2056 std::string Result;
2057
Douglas Gregoraba48082010-08-29 19:47:46 +00002058 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002059 Result = Param->getIdentifier()->getName();
2060
John McCallf85e1932011-06-15 23:02:42 +00002061 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002062
2063 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002064 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2065 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002066 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002067 Result += Param->getIdentifier()->getName();
2068 }
2069 return Result;
2070 }
2071
2072 // The argument for a block pointer parameter is a block literal with
2073 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002074 FunctionTypeLoc *Block = 0;
2075 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002076 TypeLoc TL;
2077 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2078 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2079 while (true) {
2080 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002081 if (!SuppressBlock) {
2082 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2083 if (TypeSourceInfo *InnerTSInfo
2084 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2085 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2086 continue;
2087 }
2088 }
2089
2090 // Look through qualified types
2091 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2092 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002093 continue;
2094 }
2095 }
2096
Douglas Gregor83482d12010-08-24 16:15:59 +00002097 // Try to get the function prototype behind the block pointer type,
2098 // then we're done.
2099 if (BlockPointerTypeLoc *BlockPtr
2100 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002101 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002102 Block = dyn_cast<FunctionTypeLoc>(&TL);
2103 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002104 }
2105 break;
2106 }
2107 }
2108
2109 if (!Block) {
2110 // We were unable to find a FunctionProtoTypeLoc with parameter names
2111 // for the block; just use the parameter type as a placeholder.
2112 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002113 if (!ObjCMethodParam && Param->getIdentifier())
2114 Result = Param->getIdentifier()->getName();
2115
John McCallf85e1932011-06-15 23:02:42 +00002116 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002117
2118 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002119 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2120 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002121 if (Param->getIdentifier())
2122 Result += Param->getIdentifier()->getName();
2123 }
2124
2125 return Result;
2126 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002127
Douglas Gregor83482d12010-08-24 16:15:59 +00002128 // We have the function prototype behind the block pointer type, as it was
2129 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002130 std::string Result;
2131 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002132 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002133 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002134
2135 // Format the parameter list.
2136 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002137 if (!BlockProto || Block->getNumArgs() == 0) {
2138 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002139 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002140 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002141 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002142 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002143 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002144 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2145 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002146 Params += ", ";
2147 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2148 /*SuppressName=*/false,
2149 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002150
Douglas Gregor830072c2011-02-15 22:37:09 +00002151 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002152 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002153 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002154 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002155 }
Douglas Gregor38276252010-09-08 22:47:51 +00002156
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002157 if (SuppressBlock) {
2158 // Format as a parameter.
2159 Result = Result + " (^";
2160 if (Param->getIdentifier())
2161 Result += Param->getIdentifier()->getName();
2162 Result += ")";
2163 Result += Params;
2164 } else {
2165 // Format as a block literal argument.
2166 Result = '^' + Result;
2167 Result += Params;
2168
2169 if (Param->getIdentifier())
2170 Result += Param->getIdentifier()->getName();
2171 }
2172
Douglas Gregor83482d12010-08-24 16:15:59 +00002173 return Result;
2174}
2175
Douglas Gregor86d9a522009-09-21 16:56:56 +00002176/// \brief Add function parameter chunks to the given code completion string.
2177static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002178 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002179 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002180 CodeCompletionBuilder &Result,
2181 unsigned Start = 0,
2182 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002183 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002184 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002185
Douglas Gregor218937c2011-02-01 19:23:04 +00002186 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002187 ParmVarDecl *Param = Function->getParamDecl(P);
2188
Douglas Gregor218937c2011-02-01 19:23:04 +00002189 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002190 // When we see an optional default argument, put that argument and
2191 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002192 CodeCompletionBuilder Opt(Result.getAllocator());
2193 if (!FirstParameter)
2194 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002195 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002196 Result.AddOptionalChunk(Opt.TakeString());
2197 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002198 }
2199
Douglas Gregor218937c2011-02-01 19:23:04 +00002200 if (FirstParameter)
2201 FirstParameter = false;
2202 else
2203 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2204
2205 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002206
2207 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002208 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2209 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002210
Douglas Gregore17794f2010-08-31 05:13:43 +00002211 if (Function->isVariadic() && P == N - 1)
2212 PlaceholderStr += ", ...";
2213
Douglas Gregor86d9a522009-09-21 16:56:56 +00002214 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002215 Result.AddPlaceholderChunk(
2216 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002217 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002218
2219 if (const FunctionProtoType *Proto
2220 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002221 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002222 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002223 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002224
Douglas Gregor218937c2011-02-01 19:23:04 +00002225 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002226 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002227}
2228
2229/// \brief Add template parameter chunks to the given code completion string.
2230static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002231 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002232 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002233 CodeCompletionBuilder &Result,
2234 unsigned MaxParameters = 0,
2235 unsigned Start = 0,
2236 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002237 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002238 bool FirstParameter = true;
2239
2240 TemplateParameterList *Params = Template->getTemplateParameters();
2241 TemplateParameterList::iterator PEnd = Params->end();
2242 if (MaxParameters)
2243 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002244 for (TemplateParameterList::iterator P = Params->begin() + Start;
2245 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002246 bool HasDefaultArg = false;
2247 std::string PlaceholderStr;
2248 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2249 if (TTP->wasDeclaredWithTypename())
2250 PlaceholderStr = "typename";
2251 else
2252 PlaceholderStr = "class";
2253
2254 if (TTP->getIdentifier()) {
2255 PlaceholderStr += ' ';
2256 PlaceholderStr += TTP->getIdentifier()->getName();
2257 }
2258
2259 HasDefaultArg = TTP->hasDefaultArgument();
2260 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002261 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002262 if (NTTP->getIdentifier())
2263 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002264 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002265 HasDefaultArg = NTTP->hasDefaultArgument();
2266 } else {
2267 assert(isa<TemplateTemplateParmDecl>(*P));
2268 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2269
2270 // Since putting the template argument list into the placeholder would
2271 // be very, very long, we just use an abbreviation.
2272 PlaceholderStr = "template<...> class";
2273 if (TTP->getIdentifier()) {
2274 PlaceholderStr += ' ';
2275 PlaceholderStr += TTP->getIdentifier()->getName();
2276 }
2277
2278 HasDefaultArg = TTP->hasDefaultArgument();
2279 }
2280
Douglas Gregor218937c2011-02-01 19:23:04 +00002281 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002282 // When we see an optional default argument, put that argument and
2283 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002284 CodeCompletionBuilder Opt(Result.getAllocator());
2285 if (!FirstParameter)
2286 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002287 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002288 P - Params->begin(), true);
2289 Result.AddOptionalChunk(Opt.TakeString());
2290 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002291 }
2292
Douglas Gregor218937c2011-02-01 19:23:04 +00002293 InDefaultArg = false;
2294
Douglas Gregor86d9a522009-09-21 16:56:56 +00002295 if (FirstParameter)
2296 FirstParameter = false;
2297 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002298 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002299
2300 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002301 Result.AddPlaceholderChunk(
2302 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002303 }
2304}
2305
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002306/// \brief Add a qualifier to the given code-completion string, if the
2307/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002308static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002309AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002310 NestedNameSpecifier *Qualifier,
2311 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002312 ASTContext &Context,
2313 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002314 if (!Qualifier)
2315 return;
2316
2317 std::string PrintedNNS;
2318 {
2319 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002320 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002321 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002322 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002323 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002324 else
Douglas Gregordae68752011-02-01 22:57:45 +00002325 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002326}
2327
Douglas Gregor218937c2011-02-01 19:23:04 +00002328static void
2329AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2330 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002331 const FunctionProtoType *Proto
2332 = Function->getType()->getAs<FunctionProtoType>();
2333 if (!Proto || !Proto->getTypeQuals())
2334 return;
2335
Douglas Gregora63f6de2011-02-01 21:15:40 +00002336 // FIXME: Add ref-qualifier!
2337
2338 // Handle single qualifiers without copying
2339 if (Proto->getTypeQuals() == Qualifiers::Const) {
2340 Result.AddInformativeChunk(" const");
2341 return;
2342 }
2343
2344 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2345 Result.AddInformativeChunk(" volatile");
2346 return;
2347 }
2348
2349 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2350 Result.AddInformativeChunk(" restrict");
2351 return;
2352 }
2353
2354 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002355 std::string QualsStr;
2356 if (Proto->getTypeQuals() & Qualifiers::Const)
2357 QualsStr += " const";
2358 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2359 QualsStr += " volatile";
2360 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2361 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002362 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002363}
2364
Douglas Gregor6f942b22010-09-21 16:06:22 +00002365/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002366static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2367 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002368 typedef CodeCompletionString::Chunk Chunk;
2369
2370 DeclarationName Name = ND->getDeclName();
2371 if (!Name)
2372 return;
2373
2374 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002375 case DeclarationName::CXXOperatorName: {
2376 const char *OperatorName = 0;
2377 switch (Name.getCXXOverloadedOperator()) {
2378 case OO_None:
2379 case OO_Conditional:
2380 case NUM_OVERLOADED_OPERATORS:
2381 OperatorName = "operator";
2382 break;
2383
2384#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2385 case OO_##Name: OperatorName = "operator" Spelling; break;
2386#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2387#include "clang/Basic/OperatorKinds.def"
2388
2389 case OO_New: OperatorName = "operator new"; break;
2390 case OO_Delete: OperatorName = "operator delete"; break;
2391 case OO_Array_New: OperatorName = "operator new[]"; break;
2392 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2393 case OO_Call: OperatorName = "operator()"; break;
2394 case OO_Subscript: OperatorName = "operator[]"; break;
2395 }
2396 Result.AddTypedTextChunk(OperatorName);
2397 break;
2398 }
2399
Douglas Gregor6f942b22010-09-21 16:06:22 +00002400 case DeclarationName::Identifier:
2401 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002402 case DeclarationName::CXXDestructorName:
2403 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002404 Result.AddTypedTextChunk(
2405 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002406 break;
2407
2408 case DeclarationName::CXXUsingDirective:
2409 case DeclarationName::ObjCZeroArgSelector:
2410 case DeclarationName::ObjCOneArgSelector:
2411 case DeclarationName::ObjCMultiArgSelector:
2412 break;
2413
2414 case DeclarationName::CXXConstructorName: {
2415 CXXRecordDecl *Record = 0;
2416 QualType Ty = Name.getCXXNameType();
2417 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2418 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2419 else if (const InjectedClassNameType *InjectedTy
2420 = Ty->getAs<InjectedClassNameType>())
2421 Record = InjectedTy->getDecl();
2422 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002423 Result.AddTypedTextChunk(
2424 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002425 break;
2426 }
2427
Douglas Gregordae68752011-02-01 22:57:45 +00002428 Result.AddTypedTextChunk(
2429 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002430 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002431 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002432 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002433 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002434 }
2435 break;
2436 }
2437 }
2438}
2439
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002440CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2441 CodeCompletionAllocator &Allocator) {
2442 return CreateCodeCompletionString(S.Context, S.PP, Allocator);
2443}
2444
Douglas Gregor86d9a522009-09-21 16:56:56 +00002445/// \brief If possible, create a new code completion string for the given
2446/// result.
2447///
2448/// \returns Either a new, heap-allocated code completion string describing
2449/// how to use this result, or NULL to indicate that the string or name of the
2450/// result is all that is needed.
2451CodeCompletionString *
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002452CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2453 Preprocessor &PP,
Douglas Gregordae68752011-02-01 22:57:45 +00002454 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002455 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002456 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002457
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002458 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregor218937c2011-02-01 19:23:04 +00002459 if (Kind == RK_Pattern) {
2460 Pattern->Priority = Priority;
2461 Pattern->Availability = Availability;
2462 return Pattern;
2463 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002464
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002465 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002466 Result.AddTypedTextChunk(Keyword);
2467 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002468 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002469
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002470 if (Kind == RK_Macro) {
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002471 MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002472 assert(MI && "Not a macro?");
2473
Douglas Gregordae68752011-02-01 22:57:45 +00002474 Result.AddTypedTextChunk(
2475 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002476
2477 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002478 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002479
2480 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002481 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002482 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002483
2484 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2485 if (MI->isC99Varargs()) {
2486 --AEnd;
2487
2488 if (A == AEnd) {
2489 Result.AddPlaceholderChunk("...");
2490 }
Douglas Gregore4244702011-07-30 08:17:44 +00002491 }
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002492
Douglas Gregore4244702011-07-30 08:17:44 +00002493 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002494 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002495 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002496
2497 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002498 SmallString<32> Arg = (*A)->getName();
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002499 if (MI->isC99Varargs())
2500 Arg += ", ...";
2501 else
2502 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002503 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002504 break;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002505 }
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002506
2507 // Non-variadic macros are simple.
2508 Result.AddPlaceholderChunk(
2509 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregore4244702011-07-30 08:17:44 +00002510 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002511 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2512 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002513 }
2514
Douglas Gregord8e8a582010-05-25 21:41:55 +00002515 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002516 NamedDecl *ND = Declaration;
2517
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002518 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002519 Result.AddTypedTextChunk(
2520 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002521 Result.AddTextChunk("::");
2522 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002523 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002524
2525 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2526 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2527 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2528 }
2529 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002530
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002531 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002532
Douglas Gregor86d9a522009-09-21 16:56:56 +00002533 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002534 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002535 Ctx, Policy);
2536 AddTypedNameChunk(Ctx, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002537 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002538 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002540 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002541 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002542 }
2543
2544 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002545 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002546 Ctx, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002547 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002548 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002549
Douglas Gregor86d9a522009-09-21 16:56:56 +00002550 // Figure out which template parameters are deduced (or have default
2551 // arguments).
Benjamin Kramer013b3662012-01-30 16:17:39 +00002552 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002553 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002554 unsigned LastDeducibleArgument;
2555 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2556 --LastDeducibleArgument) {
2557 if (!Deduced[LastDeducibleArgument - 1]) {
2558 // C++0x: Figure out if the template argument has a default. If so,
2559 // the user doesn't need to type this argument.
2560 // FIXME: We need to abstract template parameters better!
2561 bool HasDefaultArg = false;
2562 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002563 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002564 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2565 HasDefaultArg = TTP->hasDefaultArgument();
2566 else if (NonTypeTemplateParmDecl *NTTP
2567 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2568 HasDefaultArg = NTTP->hasDefaultArgument();
2569 else {
2570 assert(isa<TemplateTemplateParmDecl>(Param));
2571 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002572 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002573 }
2574
2575 if (!HasDefaultArg)
2576 break;
2577 }
2578 }
2579
2580 if (LastDeducibleArgument) {
2581 // Some of the function template arguments cannot be deduced from a
2582 // function call, so we introduce an explicit template argument list
2583 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002584 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002585 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002586 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002587 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002588 }
2589
2590 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002591 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002592 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002593 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002594 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002595 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002596 }
2597
2598 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002599 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002600 Ctx, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002601 Result.AddTypedTextChunk(
2602 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002603 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002604 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002605 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2606 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002607 }
2608
Douglas Gregor9630eb62009-11-17 16:44:22 +00002609 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002610 Selector Sel = Method->getSelector();
2611 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002612 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002613 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002614 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002615 }
2616
Douglas Gregor813d8342011-02-18 22:29:55 +00002617 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002618 SelName += ':';
2619 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002620 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002621 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002622 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002623
2624 // If there is only one parameter, and we're past it, add an empty
2625 // typed-text chunk since there is nothing to type.
2626 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002627 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002628 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002629 unsigned Idx = 0;
2630 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2631 PEnd = Method->param_end();
2632 P != PEnd; (void)++P, ++Idx) {
2633 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002634 std::string Keyword;
2635 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002636 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002637 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002638 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002639 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002640 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002641 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002642 else
Douglas Gregordae68752011-02-01 22:57:45 +00002643 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002644 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002645
2646 // If we're before the starting parameter, skip the placeholder.
2647 if (Idx < StartParameter)
2648 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002649
2650 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002651
2652 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002653 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002654 else {
John McCallf85e1932011-06-15 23:02:42 +00002655 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002656 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2657 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002658 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002659 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002660 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002661 }
2662
Douglas Gregore17794f2010-08-31 05:13:43 +00002663 if (Method->isVariadic() && (P + 1) == PEnd)
2664 Arg += ", ...";
2665
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002666 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002667 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002668 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002669 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002670 else
Douglas Gregordae68752011-02-01 22:57:45 +00002671 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002672 }
2673
Douglas Gregor2a17af02009-12-23 00:21:46 +00002674 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002675 if (Method->param_size() == 0) {
2676 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002677 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002678 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002679 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002680 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002681 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002682 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002683
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002684 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002685 }
2686
Douglas Gregor218937c2011-02-01 19:23:04 +00002687 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002688 }
2689
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002690 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002691 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002692 Ctx, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002693
Douglas Gregordae68752011-02-01 22:57:45 +00002694 Result.AddTypedTextChunk(
2695 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002696 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002697}
2698
Douglas Gregor86d802e2009-09-23 00:34:09 +00002699CodeCompletionString *
2700CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2701 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002702 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002703 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002704 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002705 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002706
Douglas Gregor218937c2011-02-01 19:23:04 +00002707 // FIXME: Set priority, availability appropriately.
2708 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002709 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002710 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002711 const FunctionProtoType *Proto
2712 = dyn_cast<FunctionProtoType>(getFunctionType());
2713 if (!FDecl && !Proto) {
2714 // Function without a prototype. Just give the return type and a
2715 // highlighted ellipsis.
2716 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002717 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002718 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002719 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002720 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2721 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2722 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2723 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002724 }
2725
2726 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002727 Result.AddTextChunk(
2728 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002729 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002730 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002731 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002732 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002733
Douglas Gregor218937c2011-02-01 19:23:04 +00002734 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002735 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2736 for (unsigned I = 0; I != NumParams; ++I) {
2737 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002738 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002739
2740 std::string ArgString;
2741 QualType ArgType;
2742
2743 if (FDecl) {
2744 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2745 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2746 } else {
2747 ArgType = Proto->getArgType(I);
2748 }
2749
John McCallf85e1932011-06-15 23:02:42 +00002750 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002751
2752 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002753 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002754 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002755 else
Douglas Gregordae68752011-02-01 22:57:45 +00002756 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002757 }
2758
2759 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002760 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002761 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002762 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002763 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002764 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002765 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002766 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002767
Douglas Gregor218937c2011-02-01 19:23:04 +00002768 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002769}
2770
Chris Lattner5f9e2722011-07-23 10:55:15 +00002771unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002772 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002773 bool PreferredTypeIsPointer) {
2774 unsigned Priority = CCP_Macro;
2775
Douglas Gregorb05496d2010-09-20 21:11:48 +00002776 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2777 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2778 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002779 Priority = CCP_Constant;
2780 if (PreferredTypeIsPointer)
2781 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002782 }
2783 // Treat "YES", "NO", "true", and "false" as constants.
2784 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2785 MacroName.equals("true") || MacroName.equals("false"))
2786 Priority = CCP_Constant;
2787 // Treat "bool" as a type.
2788 else if (MacroName.equals("bool"))
2789 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2790
Douglas Gregor1827e102010-08-16 16:18:59 +00002791
2792 return Priority;
2793}
2794
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002795CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2796 if (!D)
2797 return CXCursor_UnexposedDecl;
2798
2799 switch (D->getKind()) {
2800 case Decl::Enum: return CXCursor_EnumDecl;
2801 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2802 case Decl::Field: return CXCursor_FieldDecl;
2803 case Decl::Function:
2804 return CXCursor_FunctionDecl;
2805 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2806 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002807 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregor375bb142011-12-27 22:43:10 +00002808
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00002809 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002810 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2811 case Decl::ObjCMethod:
2812 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2813 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2814 case Decl::CXXMethod: return CXCursor_CXXMethod;
2815 case Decl::CXXConstructor: return CXCursor_Constructor;
2816 case Decl::CXXDestructor: return CXCursor_Destructor;
2817 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2818 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00002819 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002820 case Decl::ParmVar: return CXCursor_ParmDecl;
2821 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002822 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002823 case Decl::Var: return CXCursor_VarDecl;
2824 case Decl::Namespace: return CXCursor_Namespace;
2825 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2826 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2827 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2828 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2829 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2830 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002831 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002832 case Decl::ClassTemplatePartialSpecialization:
2833 return CXCursor_ClassTemplatePartialSpecialization;
2834 case Decl::UsingDirective: return CXCursor_UsingDirective;
2835
2836 case Decl::Using:
2837 case Decl::UnresolvedUsingValue:
2838 case Decl::UnresolvedUsingTypename:
2839 return CXCursor_UsingDeclaration;
2840
Douglas Gregor352697a2011-06-03 23:08:58 +00002841 case Decl::ObjCPropertyImpl:
2842 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2843 case ObjCPropertyImplDecl::Dynamic:
2844 return CXCursor_ObjCDynamicDecl;
2845
2846 case ObjCPropertyImplDecl::Synthesize:
2847 return CXCursor_ObjCSynthesizeDecl;
2848 }
Douglas Gregor352697a2011-06-03 23:08:58 +00002849
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002850 default:
2851 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2852 switch (TD->getTagKind()) {
2853 case TTK_Struct: return CXCursor_StructDecl;
2854 case TTK_Class: return CXCursor_ClassDecl;
2855 case TTK_Union: return CXCursor_UnionDecl;
2856 case TTK_Enum: return CXCursor_EnumDecl;
2857 }
2858 }
2859 }
2860
2861 return CXCursor_UnexposedDecl;
2862}
2863
Douglas Gregor590c7d52010-07-08 20:55:51 +00002864static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2865 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002866 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002867
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002868 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002869
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002870 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2871 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002872 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002873 Results.AddResult(Result(M->first,
2874 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002875 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002876 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002877 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002878
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002879 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002880
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002881}
2882
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002883static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2884 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002885 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002886
2887 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002888
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002889 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2890 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2891 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2892 Results.AddResult(Result("__func__", CCP_Constant));
2893 Results.ExitScope();
2894}
2895
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002896static void HandleCodeCompleteResults(Sema *S,
2897 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002898 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002899 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002900 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002901 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002902 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002903}
2904
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002905static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2906 Sema::ParserCompletionContext PCC) {
2907 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002908 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002909 return CodeCompletionContext::CCC_TopLevel;
2910
John McCallf312b1e2010-08-26 23:41:50 +00002911 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002912 return CodeCompletionContext::CCC_ClassStructUnion;
2913
John McCallf312b1e2010-08-26 23:41:50 +00002914 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002915 return CodeCompletionContext::CCC_ObjCInterface;
2916
John McCallf312b1e2010-08-26 23:41:50 +00002917 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002918 return CodeCompletionContext::CCC_ObjCImplementation;
2919
John McCallf312b1e2010-08-26 23:41:50 +00002920 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002921 return CodeCompletionContext::CCC_ObjCIvarList;
2922
John McCallf312b1e2010-08-26 23:41:50 +00002923 case Sema::PCC_Template:
2924 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002925 if (S.CurContext->isFileContext())
2926 return CodeCompletionContext::CCC_TopLevel;
David Blaikie7530c032012-01-17 06:56:22 +00002927 if (S.CurContext->isRecord())
Douglas Gregor52779fb2010-09-23 23:01:17 +00002928 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie7530c032012-01-17 06:56:22 +00002929 return CodeCompletionContext::CCC_Other;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002930
John McCallf312b1e2010-08-26 23:41:50 +00002931 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002932 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002933
John McCallf312b1e2010-08-26 23:41:50 +00002934 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002935 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2936 S.getLangOptions().ObjC1)
2937 return CodeCompletionContext::CCC_ParenthesizedExpression;
2938 else
2939 return CodeCompletionContext::CCC_Expression;
2940
2941 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002942 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002943 return CodeCompletionContext::CCC_Expression;
2944
John McCallf312b1e2010-08-26 23:41:50 +00002945 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002946 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002947
John McCallf312b1e2010-08-26 23:41:50 +00002948 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002949 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002950
2951 case Sema::PCC_ParenthesizedExpression:
2952 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002953
2954 case Sema::PCC_LocalDeclarationSpecifiers:
2955 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002956 }
David Blaikie7530c032012-01-17 06:56:22 +00002957
2958 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002959}
2960
Douglas Gregorf6961522010-08-27 21:18:54 +00002961/// \brief If we're in a C++ virtual member function, add completion results
2962/// that invoke the functions we override, since it's common to invoke the
2963/// overridden function as well as adding new functionality.
2964///
2965/// \param S The semantic analysis object for which we are generating results.
2966///
2967/// \param InContext This context in which the nested-name-specifier preceding
2968/// the code-completion point
2969static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2970 ResultBuilder &Results) {
2971 // Look through blocks.
2972 DeclContext *CurContext = S.CurContext;
2973 while (isa<BlockDecl>(CurContext))
2974 CurContext = CurContext->getParent();
2975
2976
2977 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2978 if (!Method || !Method->isVirtual())
2979 return;
2980
2981 // We need to have names for all of the parameters, if we're going to
2982 // generate a forwarding call.
2983 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2984 PEnd = Method->param_end();
2985 P != PEnd;
2986 ++P) {
2987 if (!(*P)->getDeclName())
2988 return;
2989 }
2990
Douglas Gregor8987b232011-09-27 23:30:47 +00002991 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002992 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2993 MEnd = Method->end_overridden_methods();
2994 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002995 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002996 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2997 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2998 continue;
2999
3000 // If we need a nested-name-specifier, add one now.
3001 if (!InContext) {
3002 NestedNameSpecifier *NNS
3003 = getRequiredQualification(S.Context, CurContext,
3004 Overridden->getDeclContext());
3005 if (NNS) {
3006 std::string Str;
3007 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00003008 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003009 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003010 }
3011 } else if (!InContext->Equals(Overridden->getDeclContext()))
3012 continue;
3013
Douglas Gregordae68752011-02-01 22:57:45 +00003014 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003015 Overridden->getNameAsString()));
3016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003017 bool FirstParam = true;
3018 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3019 PEnd = Method->param_end();
3020 P != PEnd; ++P) {
3021 if (FirstParam)
3022 FirstParam = false;
3023 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003024 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003025
Douglas Gregordae68752011-02-01 22:57:45 +00003026 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003027 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003028 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3030 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003031 CCP_SuperCompletion,
3032 CXCursor_CXXMethod));
3033 Results.Ignore(Overridden);
3034 }
3035}
3036
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003037void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3038 ModuleIdPath Path) {
3039 typedef CodeCompletionResult Result;
3040 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3041 CodeCompletionContext::CCC_Other);
3042 Results.EnterNewScope();
3043
3044 CodeCompletionAllocator &Allocator = Results.getAllocator();
3045 CodeCompletionBuilder Builder(Allocator);
3046 typedef CodeCompletionResult Result;
3047 if (Path.empty()) {
3048 // Enumerate all top-level modules.
3049 llvm::SmallVector<Module *, 8> Modules;
3050 PP.getHeaderSearchInfo().collectAllModules(Modules);
3051 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3052 Builder.AddTypedTextChunk(
3053 Builder.getAllocator().CopyString(Modules[I]->Name));
3054 Results.AddResult(Result(Builder.TakeString(),
3055 CCP_Declaration,
3056 CXCursor_NotImplemented,
3057 Modules[I]->isAvailable()
3058 ? CXAvailability_Available
3059 : CXAvailability_NotAvailable));
3060 }
3061 } else {
3062 // Load the named module.
3063 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3064 Module::AllVisible,
3065 /*IsInclusionDirective=*/false);
3066 // Enumerate submodules.
3067 if (Mod) {
3068 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3069 SubEnd = Mod->submodule_end();
3070 Sub != SubEnd; ++Sub) {
3071
3072 Builder.AddTypedTextChunk(
3073 Builder.getAllocator().CopyString((*Sub)->Name));
3074 Results.AddResult(Result(Builder.TakeString(),
3075 CCP_Declaration,
3076 CXCursor_NotImplemented,
3077 (*Sub)->isAvailable()
3078 ? CXAvailability_Available
3079 : CXAvailability_NotAvailable));
3080 }
3081 }
3082 }
3083 Results.ExitScope();
3084 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3085 Results.data(),Results.size());
3086}
3087
Douglas Gregor01dfea02010-01-10 23:08:15 +00003088void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003089 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003090 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003091 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003092 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003093 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003094
Douglas Gregor01dfea02010-01-10 23:08:15 +00003095 // Determine how to filter results, e.g., so that the names of
3096 // values (functions, enumerators, function templates, etc.) are
3097 // only allowed where we can have an expression.
3098 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003099 case PCC_Namespace:
3100 case PCC_Class:
3101 case PCC_ObjCInterface:
3102 case PCC_ObjCImplementation:
3103 case PCC_ObjCInstanceVariableList:
3104 case PCC_Template:
3105 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003106 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003107 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003108 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3109 break;
3110
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003111 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003112 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003113 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003114 case PCC_ForInit:
3115 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003116 if (WantTypesInContext(CompletionContext, getLangOptions()))
3117 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3118 else
3119 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003120
3121 if (getLangOptions().CPlusPlus)
3122 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003123 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003124
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003125 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003126 // Unfiltered
3127 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003128 }
3129
Douglas Gregor3cdee122010-08-26 16:36:48 +00003130 // If we are in a C++ non-static member function, check the qualifiers on
3131 // the member function to filter/prioritize the results list.
3132 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3133 if (CurMethod->isInstance())
3134 Results.setObjectTypeQualifiers(
3135 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3136
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003137 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003138 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3139 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003140
Douglas Gregorbca403c2010-01-13 23:51:12 +00003141 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003142 Results.ExitScope();
3143
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003144 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003145 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003146 case PCC_Expression:
3147 case PCC_Statement:
3148 case PCC_RecoveryInFunction:
3149 if (S->getFnParent())
3150 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3151 break;
3152
3153 case PCC_Namespace:
3154 case PCC_Class:
3155 case PCC_ObjCInterface:
3156 case PCC_ObjCImplementation:
3157 case PCC_ObjCInstanceVariableList:
3158 case PCC_Template:
3159 case PCC_MemberTemplate:
3160 case PCC_ForInit:
3161 case PCC_Condition:
3162 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003163 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003164 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003165 }
3166
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003167 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003168 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003169
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003170 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003171 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003172}
3173
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003174static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3175 ParsedType Receiver,
3176 IdentifierInfo **SelIdents,
3177 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003178 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003179 bool IsSuper,
3180 ResultBuilder &Results);
3181
3182void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3183 bool AllowNonIdentifiers,
3184 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003185 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003186 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003187 AllowNestedNameSpecifiers
3188 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3189 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003190 Results.EnterNewScope();
3191
3192 // Type qualifiers can come after names.
3193 Results.AddResult(Result("const"));
3194 Results.AddResult(Result("volatile"));
3195 if (getLangOptions().C99)
3196 Results.AddResult(Result("restrict"));
3197
3198 if (getLangOptions().CPlusPlus) {
3199 if (AllowNonIdentifiers) {
3200 Results.AddResult(Result("operator"));
3201 }
3202
3203 // Add nested-name-specifiers.
3204 if (AllowNestedNameSpecifiers) {
3205 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003206 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003207 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3208 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3209 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003210 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003211 }
3212 }
3213 Results.ExitScope();
3214
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003215 // If we're in a context where we might have an expression (rather than a
3216 // declaration), and what we've seen so far is an Objective-C type that could
3217 // be a receiver of a class message, this may be a class message send with
3218 // the initial opening bracket '[' missing. Add appropriate completions.
3219 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3220 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3221 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3222 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3223 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3224 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3225 DS.getTypeQualifiers() == 0 &&
3226 S &&
3227 (S->getFlags() & Scope::DeclScope) != 0 &&
3228 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3229 Scope::FunctionPrototypeScope |
3230 Scope::AtCatchScope)) == 0) {
3231 ParsedType T = DS.getRepAsType();
3232 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003233 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003234 }
3235
Douglas Gregor4497dd42010-08-24 04:59:56 +00003236 // Note that we intentionally suppress macro results here, since we do not
3237 // encourage using macros to produce the names of entities.
3238
Douglas Gregor52779fb2010-09-23 23:01:17 +00003239 HandleCodeCompleteResults(this, CodeCompleter,
3240 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003241 Results.data(), Results.size());
3242}
3243
Douglas Gregorfb629412010-08-23 21:17:50 +00003244struct Sema::CodeCompleteExpressionData {
3245 CodeCompleteExpressionData(QualType PreferredType = QualType())
3246 : PreferredType(PreferredType), IntegralConstantExpression(false),
3247 ObjCCollection(false) { }
3248
3249 QualType PreferredType;
3250 bool IntegralConstantExpression;
3251 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003252 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003253};
3254
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003255/// \brief Perform code-completion in an expression context when we know what
3256/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003257///
3258/// \param IntegralConstantExpression Only permit integral constant
3259/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003260void Sema::CodeCompleteExpression(Scope *S,
3261 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003262 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003263 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3264 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003265 if (Data.ObjCCollection)
3266 Results.setFilter(&ResultBuilder::IsObjCCollection);
3267 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003268 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003269 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003270 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3271 else
3272 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003273
3274 if (!Data.PreferredType.isNull())
3275 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3276
3277 // Ignore any declarations that we were told that we don't care about.
3278 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3279 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003280
3281 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003282 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3283 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003284
3285 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003286 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003287 Results.ExitScope();
3288
Douglas Gregor590c7d52010-07-08 20:55:51 +00003289 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003290 if (!Data.PreferredType.isNull())
3291 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3292 || Data.PreferredType->isMemberPointerType()
3293 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003294
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003295 if (S->getFnParent() &&
3296 !Data.ObjCCollection &&
3297 !Data.IntegralConstantExpression)
3298 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3299
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003300 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003301 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003302 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003303 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3304 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003305 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003306}
3307
Douglas Gregorac5fd842010-09-18 01:28:11 +00003308void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3309 if (E.isInvalid())
3310 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3311 else if (getLangOptions().ObjC1)
3312 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003313}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003314
Douglas Gregor73449212010-12-09 23:01:55 +00003315/// \brief The set of properties that have already been added, referenced by
3316/// property name.
3317typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3318
Douglas Gregor95ac6552009-11-18 01:29:26 +00003319static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003320 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003321 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003322 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003323 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003324 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003325 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003326
3327 // Add properties in this container.
3328 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3329 PEnd = Container->prop_end();
3330 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003331 ++P) {
3332 if (AddedProperties.insert(P->getIdentifier()))
3333 Results.MaybeAddResult(Result(*P, 0), CurContext);
3334 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003335
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003336 // Add nullary methods
3337 if (AllowNullaryMethods) {
3338 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003339 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003340 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3341 MEnd = Container->meth_end();
3342 M != MEnd; ++M) {
3343 if (M->getSelector().isUnarySelector())
3344 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3345 if (AddedProperties.insert(Name)) {
3346 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003347 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003348 Builder.AddTypedTextChunk(
3349 Results.getAllocator().CopyString(Name->getName()));
3350
3351 CXAvailabilityKind Availability = CXAvailability_Available;
3352 switch (M->getAvailability()) {
3353 case AR_Available:
3354 case AR_NotYetIntroduced:
3355 Availability = CXAvailability_Available;
3356 break;
3357
3358 case AR_Deprecated:
3359 Availability = CXAvailability_Deprecated;
3360 break;
3361
3362 case AR_Unavailable:
3363 Availability = CXAvailability_NotAvailable;
3364 break;
3365 }
3366
3367 Results.MaybeAddResult(Result(Builder.TakeString(),
3368 CCP_MemberDeclaration + CCD_MethodAsProperty,
3369 M->isInstanceMethod()
3370 ? CXCursor_ObjCInstanceMethodDecl
3371 : CXCursor_ObjCClassMethodDecl,
3372 Availability),
3373 CurContext);
3374 }
3375 }
3376 }
3377
3378
Douglas Gregor95ac6552009-11-18 01:29:26 +00003379 // Add properties in referenced protocols.
3380 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3381 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3382 PEnd = Protocol->protocol_end();
3383 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003384 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3385 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003386 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003387 if (AllowCategories) {
3388 // Look through categories.
3389 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3390 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003391 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3392 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003393 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003394
3395 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003396 for (ObjCInterfaceDecl::all_protocol_iterator
3397 I = IFace->all_referenced_protocol_begin(),
3398 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003399 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3400 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003401
3402 // Look in the superclass.
3403 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003404 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3405 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003406 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003407 } else if (const ObjCCategoryDecl *Category
3408 = dyn_cast<ObjCCategoryDecl>(Container)) {
3409 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003410 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3411 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003412 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003413 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3414 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003415 }
3416}
3417
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003418void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003419 SourceLocation OpLoc,
3420 bool IsArrow) {
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003421 if (!Base || !CodeCompleter)
Douglas Gregor81b747b2009-09-17 21:32:03 +00003422 return;
3423
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003424 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3425 if (ConvertedBase.isInvalid())
3426 return;
3427 Base = ConvertedBase.get();
3428
John McCall0a2c5e22010-08-25 06:19:51 +00003429 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003430
Douglas Gregor81b747b2009-09-17 21:32:03 +00003431 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003432
3433 if (IsArrow) {
3434 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3435 BaseType = Ptr->getPointeeType();
3436 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003437 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003438 else
3439 return;
3440 }
3441
Douglas Gregor3da626b2011-07-07 16:03:39 +00003442 enum CodeCompletionContext::Kind contextKind;
3443
3444 if (IsArrow) {
3445 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3446 }
3447 else {
3448 if (BaseType->isObjCObjectPointerType() ||
3449 BaseType->isObjCObjectOrInterfaceType()) {
3450 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3451 }
3452 else {
3453 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3454 }
3455 }
3456
Douglas Gregor218937c2011-02-01 19:23:04 +00003457 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003458 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003459 BaseType),
3460 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003461 Results.EnterNewScope();
3462 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003463 // Indicate that we are performing a member access, and the cv-qualifiers
3464 // for the base object type.
3465 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3466
Douglas Gregor95ac6552009-11-18 01:29:26 +00003467 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003468 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003469 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003470 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3471 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003472
Douglas Gregor95ac6552009-11-18 01:29:26 +00003473 if (getLangOptions().CPlusPlus) {
3474 if (!Results.empty()) {
3475 // The "template" keyword can follow "->" or "." in the grammar.
3476 // However, we only want to suggest the template keyword if something
3477 // is dependent.
3478 bool IsDependent = BaseType->isDependentType();
3479 if (!IsDependent) {
3480 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3481 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3482 IsDependent = Ctx->isDependentContext();
3483 break;
3484 }
3485 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003486
Douglas Gregor95ac6552009-11-18 01:29:26 +00003487 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003488 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003489 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003490 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003491 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3492 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003493 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003494
3495 // Add property results based on our interface.
3496 const ObjCObjectPointerType *ObjCPtr
3497 = BaseType->getAsObjCInterfacePointerType();
3498 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003499 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3500 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003501 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003502
3503 // Add properties from the protocols in a qualified interface.
3504 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3505 E = ObjCPtr->qual_end();
3506 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003507 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3508 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003509 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003510 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003511 // Objective-C instance variable access.
3512 ObjCInterfaceDecl *Class = 0;
3513 if (const ObjCObjectPointerType *ObjCPtr
3514 = BaseType->getAs<ObjCObjectPointerType>())
3515 Class = ObjCPtr->getInterfaceDecl();
3516 else
John McCallc12c5bb2010-05-15 11:32:37 +00003517 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003518
3519 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003520 if (Class) {
3521 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3522 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003523 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3524 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003525 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003526 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003527
3528 // FIXME: How do we cope with isa?
3529
3530 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003531
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003532 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003533 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003534 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003535 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003536}
3537
Douglas Gregor374929f2009-09-18 15:37:17 +00003538void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3539 if (!CodeCompleter)
3540 return;
3541
John McCall0a2c5e22010-08-25 06:19:51 +00003542 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003543 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003544 enum CodeCompletionContext::Kind ContextKind
3545 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003546 switch ((DeclSpec::TST)TagSpec) {
3547 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003548 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003549 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003550 break;
3551
3552 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003553 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003554 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003555 break;
3556
3557 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003558 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003559 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003560 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003561 break;
3562
3563 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003564 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003565 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003566
Douglas Gregor218937c2011-02-01 19:23:04 +00003567 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003568 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003569
3570 // First pass: look for tags.
3571 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003572 LookupVisibleDecls(S, LookupTagName, Consumer,
3573 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003574
Douglas Gregor8071e422010-08-15 06:18:01 +00003575 if (CodeCompleter->includeGlobals()) {
3576 // Second pass: look for nested name specifiers.
3577 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3578 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3579 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003580
Douglas Gregor52779fb2010-09-23 23:01:17 +00003581 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003582 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003583}
3584
Douglas Gregor1a480c42010-08-27 17:35:51 +00003585void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003586 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3587 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003588 Results.EnterNewScope();
3589 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3590 Results.AddResult("const");
3591 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3592 Results.AddResult("volatile");
3593 if (getLangOptions().C99 &&
3594 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3595 Results.AddResult("restrict");
3596 Results.ExitScope();
3597 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003598 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003599 Results.data(), Results.size());
3600}
3601
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003602void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003603 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003604 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003605
John McCall781472f2010-08-25 08:40:02 +00003606 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003607 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3608 if (!type->isEnumeralType()) {
3609 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003610 Data.IntegralConstantExpression = true;
3611 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003612 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003613 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003614
3615 // Code-complete the cases of a switch statement over an enumeration type
3616 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003617 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003618
3619 // Determine which enumerators we have already seen in the switch statement.
3620 // FIXME: Ideally, we would also be able to look *past* the code-completion
3621 // token, in case we are code-completing in the middle of the switch and not
3622 // at the end. However, we aren't able to do so at the moment.
3623 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003624 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003625 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3626 SC = SC->getNextSwitchCase()) {
3627 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3628 if (!Case)
3629 continue;
3630
3631 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3632 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3633 if (EnumConstantDecl *Enumerator
3634 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3635 // We look into the AST of the case statement to determine which
3636 // enumerator was named. Alternatively, we could compute the value of
3637 // the integral constant expression, then compare it against the
3638 // values of each enumerator. However, value-based approach would not
3639 // work as well with C++ templates where enumerators declared within a
3640 // template are type- and value-dependent.
3641 EnumeratorsSeen.insert(Enumerator);
3642
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003643 // If this is a qualified-id, keep track of the nested-name-specifier
3644 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003645 //
3646 // switch (TagD.getKind()) {
3647 // case TagDecl::TK_enum:
3648 // break;
3649 // case XXX
3650 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003651 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003652 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3653 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003654 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003655 }
3656 }
3657
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003658 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3659 // If there are no prior enumerators in C++, check whether we have to
3660 // qualify the names of the enumerators that we suggest, because they
3661 // may not be visible in this scope.
Douglas Gregorb223d8c2012-02-01 05:02:47 +00003662 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003663 }
3664
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003665 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003666 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3667 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003668 Results.EnterNewScope();
3669 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3670 EEnd = Enum->enumerator_end();
3671 E != EEnd; ++E) {
3672 if (EnumeratorsSeen.count(*E))
3673 continue;
3674
Douglas Gregor5c722c702011-02-18 23:30:37 +00003675 CodeCompletionResult R(*E, Qualifier);
3676 R.Priority = CCP_EnumInCase;
3677 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003678 }
3679 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003680
Douglas Gregor3da626b2011-07-07 16:03:39 +00003681 //We need to make sure we're setting the right context,
3682 //so only say we include macros if the code completer says we do
3683 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3684 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003685 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003686 kind = CodeCompletionContext::CCC_OtherWithMacros;
3687 }
3688
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003689 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003690 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003691 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003692}
3693
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003694namespace {
3695 struct IsBetterOverloadCandidate {
3696 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003697 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003698
3699 public:
John McCall5769d612010-02-08 23:07:23 +00003700 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3701 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003702
3703 bool
3704 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003705 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003706 }
3707 };
3708}
3709
Douglas Gregord28dcd72010-05-30 06:10:08 +00003710static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3711 if (NumArgs && !Args)
3712 return true;
3713
3714 for (unsigned I = 0; I != NumArgs; ++I)
3715 if (!Args[I])
3716 return true;
3717
3718 return false;
3719}
3720
Richard Trieuf81e5a92011-09-09 02:00:50 +00003721void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3722 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003723 if (!CodeCompleter)
3724 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003725
3726 // When we're code-completing for a call, we fall back to ordinary
3727 // name code-completion whenever we can't produce specific
3728 // results. We may want to revisit this strategy in the future,
3729 // e.g., by merging the two kinds of results.
3730
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003731 Expr *Fn = (Expr *)FnIn;
3732 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003733
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003734 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003735 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003736 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003737 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003738 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003739 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003740
John McCall3b4294e2009-12-16 12:17:52 +00003741 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003742 SourceLocation Loc = Fn->getExprLoc();
3743 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003744
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003745 // FIXME: What if we're calling something that isn't a function declaration?
3746 // FIXME: What if we're calling a pseudo-destructor?
3747 // FIXME: What if we're calling a member function?
3748
Douglas Gregorc0265402010-01-21 15:46:19 +00003749 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003750 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003751
John McCall3b4294e2009-12-16 12:17:52 +00003752 Expr *NakedFn = Fn->IgnoreParenCasts();
3753 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3754 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3755 /*PartialOverloading=*/ true);
3756 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3757 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003758 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003759 if (!getLangOptions().CPlusPlus ||
3760 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003761 Results.push_back(ResultCandidate(FDecl));
3762 else
John McCall86820f52010-01-26 01:37:31 +00003763 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003764 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3765 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003766 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003767 }
John McCall3b4294e2009-12-16 12:17:52 +00003768 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003769
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003770 QualType ParamType;
3771
Douglas Gregorc0265402010-01-21 15:46:19 +00003772 if (!CandidateSet.empty()) {
3773 // Sort the overload candidate set by placing the best overloads first.
3774 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003775 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003776
Douglas Gregorc0265402010-01-21 15:46:19 +00003777 // Add the remaining viable overload candidates as code-completion reslults.
3778 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3779 CandEnd = CandidateSet.end();
3780 Cand != CandEnd; ++Cand) {
3781 if (Cand->Viable)
3782 Results.push_back(ResultCandidate(Cand->Function));
3783 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003784
3785 // From the viable candidates, try to determine the type of this parameter.
3786 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3787 if (const FunctionType *FType = Results[I].getFunctionType())
3788 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3789 if (NumArgs < Proto->getNumArgs()) {
3790 if (ParamType.isNull())
3791 ParamType = Proto->getArgType(NumArgs);
3792 else if (!Context.hasSameUnqualifiedType(
3793 ParamType.getNonReferenceType(),
3794 Proto->getArgType(NumArgs).getNonReferenceType())) {
3795 ParamType = QualType();
3796 break;
3797 }
3798 }
3799 }
3800 } else {
3801 // Try to determine the parameter type from the type of the expression
3802 // being called.
3803 QualType FunctionType = Fn->getType();
3804 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3805 FunctionType = Ptr->getPointeeType();
3806 else if (const BlockPointerType *BlockPtr
3807 = FunctionType->getAs<BlockPointerType>())
3808 FunctionType = BlockPtr->getPointeeType();
3809 else if (const MemberPointerType *MemPtr
3810 = FunctionType->getAs<MemberPointerType>())
3811 FunctionType = MemPtr->getPointeeType();
3812
3813 if (const FunctionProtoType *Proto
3814 = FunctionType->getAs<FunctionProtoType>()) {
3815 if (NumArgs < Proto->getNumArgs())
3816 ParamType = Proto->getArgType(NumArgs);
3817 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003818 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003819
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003820 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003821 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003822 else
3823 CodeCompleteExpression(S, ParamType);
3824
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003825 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003826 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3827 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003828}
3829
John McCalld226f652010-08-21 09:40:31 +00003830void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3831 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003832 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003833 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003834 return;
3835 }
3836
3837 CodeCompleteExpression(S, VD->getType());
3838}
3839
3840void Sema::CodeCompleteReturn(Scope *S) {
3841 QualType ResultType;
3842 if (isa<BlockDecl>(CurContext)) {
3843 if (BlockScopeInfo *BSI = getCurBlock())
3844 ResultType = BSI->ReturnType;
3845 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3846 ResultType = Function->getResultType();
3847 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3848 ResultType = Method->getResultType();
3849
3850 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003851 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003852 else
3853 CodeCompleteExpression(S, ResultType);
3854}
3855
Douglas Gregord2d8be62011-07-30 08:36:53 +00003856void Sema::CodeCompleteAfterIf(Scope *S) {
3857 typedef CodeCompletionResult Result;
3858 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3859 mapCodeCompletionContext(*this, PCC_Statement));
3860 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3861 Results.EnterNewScope();
3862
3863 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3864 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3865 CodeCompleter->includeGlobals());
3866
3867 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3868
3869 // "else" block
3870 CodeCompletionBuilder Builder(Results.getAllocator());
3871 Builder.AddTypedTextChunk("else");
3872 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3873 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3874 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3875 Builder.AddPlaceholderChunk("statements");
3876 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3877 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3878 Results.AddResult(Builder.TakeString());
3879
3880 // "else if" block
3881 Builder.AddTypedTextChunk("else");
3882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3883 Builder.AddTextChunk("if");
3884 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3885 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3886 if (getLangOptions().CPlusPlus)
3887 Builder.AddPlaceholderChunk("condition");
3888 else
3889 Builder.AddPlaceholderChunk("expression");
3890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3891 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3892 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3893 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3894 Builder.AddPlaceholderChunk("statements");
3895 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3896 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3897 Results.AddResult(Builder.TakeString());
3898
3899 Results.ExitScope();
3900
3901 if (S->getFnParent())
3902 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3903
3904 if (CodeCompleter->includeMacros())
3905 AddMacroResults(PP, Results);
3906
3907 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3908 Results.data(),Results.size());
3909}
3910
Richard Trieuf81e5a92011-09-09 02:00:50 +00003911void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003912 if (LHS)
3913 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3914 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003915 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003916}
3917
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003918void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003919 bool EnteringContext) {
3920 if (!SS.getScopeRep() || !CodeCompleter)
3921 return;
3922
Douglas Gregor86d9a522009-09-21 16:56:56 +00003923 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3924 if (!Ctx)
3925 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003926
3927 // Try to instantiate any non-dependent declaration contexts before
3928 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003929 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003930 return;
3931
Douglas Gregor218937c2011-02-01 19:23:04 +00003932 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3933 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003934 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003935
Douglas Gregor86d9a522009-09-21 16:56:56 +00003936 // The "template" keyword can follow "::" in the grammar, but only
3937 // put it into the grammar if the nested-name-specifier is dependent.
3938 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3939 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003940 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003941
3942 // Add calls to overridden virtual functions, if there are any.
3943 //
3944 // FIXME: This isn't wonderful, because we don't know whether we're actually
3945 // in a context that permits expressions. This is a general issue with
3946 // qualified-id completions.
3947 if (!EnteringContext)
3948 MaybeAddOverrideCalls(*this, Ctx, Results);
3949 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003950
Douglas Gregorf6961522010-08-27 21:18:54 +00003951 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3952 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3953
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003954 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003955 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003956 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003957}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003958
3959void Sema::CodeCompleteUsing(Scope *S) {
3960 if (!CodeCompleter)
3961 return;
3962
Douglas Gregor218937c2011-02-01 19:23:04 +00003963 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003964 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3965 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003966 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003967
3968 // If we aren't in class scope, we could see the "namespace" keyword.
3969 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003970 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003971
3972 // After "using", we can see anything that would start a
3973 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003974 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003975 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3976 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003977 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003978
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003979 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003980 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003981 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003982}
3983
3984void Sema::CodeCompleteUsingDirective(Scope *S) {
3985 if (!CodeCompleter)
3986 return;
3987
Douglas Gregor86d9a522009-09-21 16:56:56 +00003988 // After "using namespace", we expect to see a namespace name or namespace
3989 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003990 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3991 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003992 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003993 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003994 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003995 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3996 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003997 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003998 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003999 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004000 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004001}
4002
4003void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4004 if (!CodeCompleter)
4005 return;
4006
Douglas Gregor86d9a522009-09-21 16:56:56 +00004007 DeclContext *Ctx = (DeclContext *)S->getEntity();
4008 if (!S->getParent())
4009 Ctx = Context.getTranslationUnitDecl();
4010
Douglas Gregor52779fb2010-09-23 23:01:17 +00004011 bool SuppressedGlobalResults
4012 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4013
Douglas Gregor218937c2011-02-01 19:23:04 +00004014 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004015 SuppressedGlobalResults
4016 ? CodeCompletionContext::CCC_Namespace
4017 : CodeCompletionContext::CCC_Other,
4018 &ResultBuilder::IsNamespace);
4019
4020 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00004021 // We only want to see those namespaces that have already been defined
4022 // within this scope, because its likely that the user is creating an
4023 // extended namespace declaration. Keep track of the most recent
4024 // definition of each namespace.
4025 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4026 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4027 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4028 NS != NSEnd; ++NS)
4029 OrigToLatest[NS->getOriginalNamespace()] = *NS;
4030
4031 // Add the most recent definition (or extended definition) of each
4032 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004033 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004034 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4035 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
4036 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00004037 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00004038 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004039 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004040 }
4041
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004042 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004043 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004044 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004045}
4046
4047void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4048 if (!CodeCompleter)
4049 return;
4050
Douglas Gregor86d9a522009-09-21 16:56:56 +00004051 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004052 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4053 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004054 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004055 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004056 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4057 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004058 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004059 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004060 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004061}
4062
Douglas Gregored8d3222009-09-18 20:05:18 +00004063void Sema::CodeCompleteOperatorName(Scope *S) {
4064 if (!CodeCompleter)
4065 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004066
John McCall0a2c5e22010-08-25 06:19:51 +00004067 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004068 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4069 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004070 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004071 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004072
Douglas Gregor86d9a522009-09-21 16:56:56 +00004073 // Add the names of overloadable operators.
4074#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4075 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004076 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004077#include "clang/Basic/OperatorKinds.def"
4078
4079 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004080 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004081 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004082 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4083 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004084
4085 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004086 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004087 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004088
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004089 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004090 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004091 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004092}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004093
Douglas Gregor0133f522010-08-28 00:00:50 +00004094void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004095 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004096 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004097 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004098 CXXConstructorDecl *Constructor
4099 = static_cast<CXXConstructorDecl *>(ConstructorD);
4100 if (!Constructor)
4101 return;
4102
Douglas Gregor218937c2011-02-01 19:23:04 +00004103 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004104 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004105 Results.EnterNewScope();
4106
4107 // Fill in any already-initialized fields or base classes.
4108 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4109 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4110 for (unsigned I = 0; I != NumInitializers; ++I) {
4111 if (Initializers[I]->isBaseInitializer())
4112 InitializedBases.insert(
4113 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4114 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004115 InitializedFields.insert(cast<FieldDecl>(
4116 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004117 }
4118
4119 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004120 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004121 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004122 CXXRecordDecl *ClassDecl = Constructor->getParent();
4123 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4124 BaseEnd = ClassDecl->bases_end();
4125 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004126 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4127 SawLastInitializer
4128 = NumInitializers > 0 &&
4129 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4130 Context.hasSameUnqualifiedType(Base->getType(),
4131 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004132 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004133 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004134
Douglas Gregor218937c2011-02-01 19:23:04 +00004135 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004136 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004137 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4139 Builder.AddPlaceholderChunk("args");
4140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4141 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004142 SawLastInitializer? CCP_NextInitializer
4143 : CCP_MemberDeclaration));
4144 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004145 }
4146
4147 // Add completions for virtual base classes.
4148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4149 BaseEnd = ClassDecl->vbases_end();
4150 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004151 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4152 SawLastInitializer
4153 = NumInitializers > 0 &&
4154 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4155 Context.hasSameUnqualifiedType(Base->getType(),
4156 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004157 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004158 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004159
Douglas Gregor218937c2011-02-01 19:23:04 +00004160 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004161 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004162 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004163 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4164 Builder.AddPlaceholderChunk("args");
4165 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4166 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004167 SawLastInitializer? CCP_NextInitializer
4168 : CCP_MemberDeclaration));
4169 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004170 }
4171
4172 // Add completions for members.
4173 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4174 FieldEnd = ClassDecl->field_end();
4175 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004176 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4177 SawLastInitializer
4178 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004179 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4180 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004181 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004182 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004183
4184 if (!Field->getDeclName())
4185 continue;
4186
Douglas Gregordae68752011-02-01 22:57:45 +00004187 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004188 Field->getIdentifier()->getName()));
4189 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4190 Builder.AddPlaceholderChunk("args");
4191 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4192 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004193 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004194 : CCP_MemberDeclaration,
4195 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004196 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004197 }
4198 Results.ExitScope();
4199
Douglas Gregor52779fb2010-09-23 23:01:17 +00004200 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004201 Results.data(), Results.size());
4202}
4203
Douglas Gregor81f3bff2012-02-15 15:34:24 +00004204/// \brief Determine whether this scope denotes a namespace.
4205static bool isNamespaceScope(Scope *S) {
4206 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
4207 if (!DC)
4208 return false;
4209
4210 return DC->isFileContext();
4211}
4212
4213void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4214 bool AfterAmpersand) {
4215 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4216 CodeCompletionContext::CCC_Other);
4217 Results.EnterNewScope();
4218
4219 // Note what has already been captured.
4220 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4221 bool IncludedThis = false;
4222 for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4223 CEnd = Intro.Captures.end();
4224 C != CEnd; ++C) {
4225 if (C->Kind == LCK_This) {
4226 IncludedThis = true;
4227 continue;
4228 }
4229
4230 Known.insert(C->Id);
4231 }
4232
4233 // Look for other capturable variables.
4234 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4235 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4236 D != DEnd; ++D) {
4237 VarDecl *Var = dyn_cast<VarDecl>(*D);
4238 if (!Var ||
4239 !Var->hasLocalStorage() ||
4240 Var->hasAttr<BlocksAttr>())
4241 continue;
4242
4243 if (Known.insert(Var->getIdentifier()))
4244 Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
4245 }
4246 }
4247
4248 // Add 'this', if it would be valid.
4249 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4250 addThisCompletion(*this, Results);
4251
4252 Results.ExitScope();
4253
4254 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4255 Results.data(), Results.size());
4256}
4257
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004258// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4259// true or false.
4260#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004261static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004262 ResultBuilder &Results,
4263 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004264 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004265 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004266 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004267
Douglas Gregor218937c2011-02-01 19:23:04 +00004268 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004269 if (LangOpts.ObjC2) {
4270 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004271 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4272 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4273 Builder.AddPlaceholderChunk("property");
4274 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004275
4276 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004277 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4278 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4279 Builder.AddPlaceholderChunk("property");
4280 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004281 }
4282}
4283
Douglas Gregorbca403c2010-01-13 23:51:12 +00004284static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004285 ResultBuilder &Results,
4286 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004287 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004288
4289 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004290 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004291
4292 if (LangOpts.ObjC2) {
4293 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004294 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004295
4296 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004297 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004298
4299 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004300 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004301 }
4302}
4303
Douglas Gregorbca403c2010-01-13 23:51:12 +00004304static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004305 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004306 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004307
4308 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004309 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4310 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4311 Builder.AddPlaceholderChunk("name");
4312 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004313
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004314 if (Results.includeCodePatterns()) {
4315 // @interface name
4316 // FIXME: Could introduce the whole pattern, including superclasses and
4317 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004318 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4319 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4320 Builder.AddPlaceholderChunk("class");
4321 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004322
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004323 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004324 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4325 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4326 Builder.AddPlaceholderChunk("protocol");
4327 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004328
4329 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004330 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4331 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4332 Builder.AddPlaceholderChunk("class");
4333 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004334 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004335
4336 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004337 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4338 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4339 Builder.AddPlaceholderChunk("alias");
4340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4341 Builder.AddPlaceholderChunk("class");
4342 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004343}
4344
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004345void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004346 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004347 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4348 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004349 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004350 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004351 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004352 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004353 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004354 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004355 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004356 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004357 HandleCodeCompleteResults(this, CodeCompleter,
4358 CodeCompletionContext::CCC_Other,
4359 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004360}
4361
Douglas Gregorbca403c2010-01-13 23:51:12 +00004362static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004363 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004364 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004365
4366 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004367 const char *EncodeType = "char[]";
4368 if (Results.getSema().getLangOptions().CPlusPlus ||
4369 Results.getSema().getLangOptions().ConstStrings)
4370 EncodeType = " const char[]";
4371 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004372 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4373 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4374 Builder.AddPlaceholderChunk("type-name");
4375 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4376 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004377
4378 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004379 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004380 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4382 Builder.AddPlaceholderChunk("protocol-name");
4383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4384 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004385
4386 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004387 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004388 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4389 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4390 Builder.AddPlaceholderChunk("selector");
4391 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4392 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004393}
4394
Douglas Gregorbca403c2010-01-13 23:51:12 +00004395static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004396 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004397 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004398
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004399 if (Results.includeCodePatterns()) {
4400 // @try { statements } @catch ( declaration ) { statements } @finally
4401 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004402 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4403 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4404 Builder.AddPlaceholderChunk("statements");
4405 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4406 Builder.AddTextChunk("@catch");
4407 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4408 Builder.AddPlaceholderChunk("parameter");
4409 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4410 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4411 Builder.AddPlaceholderChunk("statements");
4412 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4413 Builder.AddTextChunk("@finally");
4414 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4415 Builder.AddPlaceholderChunk("statements");
4416 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4417 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004418 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004419
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004420 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004421 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4422 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4423 Builder.AddPlaceholderChunk("expression");
4424 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004425
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004426 if (Results.includeCodePatterns()) {
4427 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004428 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4429 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4430 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4431 Builder.AddPlaceholderChunk("expression");
4432 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4433 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4434 Builder.AddPlaceholderChunk("statements");
4435 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4436 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004437 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004438}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004439
Douglas Gregorbca403c2010-01-13 23:51:12 +00004440static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004441 ResultBuilder &Results,
4442 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004443 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004444 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4445 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4446 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004447 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004448 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004449}
4450
4451void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004452 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4453 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004454 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004455 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004456 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004457 HandleCodeCompleteResults(this, CodeCompleter,
4458 CodeCompletionContext::CCC_Other,
4459 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004460}
4461
4462void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004463 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4464 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004465 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004466 AddObjCStatementResults(Results, false);
4467 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004468 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004469 HandleCodeCompleteResults(this, CodeCompleter,
4470 CodeCompletionContext::CCC_Other,
4471 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004472}
4473
4474void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004475 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4476 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004477 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004478 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004479 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004480 HandleCodeCompleteResults(this, CodeCompleter,
4481 CodeCompletionContext::CCC_Other,
4482 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004483}
4484
Douglas Gregor988358f2009-11-19 00:14:45 +00004485/// \brief Determine whether the addition of the given flag to an Objective-C
4486/// property's attributes will cause a conflict.
4487static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4488 // Check if we've already added this flag.
4489 if (Attributes & NewFlag)
4490 return true;
4491
4492 Attributes |= NewFlag;
4493
4494 // Check for collisions with "readonly".
4495 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4496 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4497 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004498 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004499 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004500 ObjCDeclSpec::DQ_PR_retain |
4501 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004502 return true;
4503
John McCallf85e1932011-06-15 23:02:42 +00004504 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004505 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004506 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004507 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004508 ObjCDeclSpec::DQ_PR_retain|
4509 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004510 if (AssignCopyRetMask &&
4511 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004512 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004513 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004514 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4515 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004516 return true;
4517
4518 return false;
4519}
4520
Douglas Gregora93b1082009-11-18 23:08:07 +00004521void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004522 if (!CodeCompleter)
4523 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004524
Steve Naroffece8e712009-10-08 21:55:05 +00004525 unsigned Attributes = ODS.getPropertyAttributes();
4526
John McCall0a2c5e22010-08-25 06:19:51 +00004527 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004528 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4529 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004530 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004531 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004532 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004533 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004534 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004535 if (!ObjCPropertyFlagConflicts(Attributes,
4536 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4537 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004538 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004539 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004540 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004541 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004542 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4543 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004544 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004545 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004546 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004547 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004548 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4549 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004550 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004551 CodeCompletionBuilder Setter(Results.getAllocator());
4552 Setter.AddTypedTextChunk("setter");
4553 Setter.AddTextChunk(" = ");
4554 Setter.AddPlaceholderChunk("method");
4555 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004556 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004557 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004558 CodeCompletionBuilder Getter(Results.getAllocator());
4559 Getter.AddTypedTextChunk("getter");
4560 Getter.AddTextChunk(" = ");
4561 Getter.AddPlaceholderChunk("method");
4562 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004563 }
Steve Naroffece8e712009-10-08 21:55:05 +00004564 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004565 HandleCodeCompleteResults(this, CodeCompleter,
4566 CodeCompletionContext::CCC_Other,
4567 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004568}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004569
Douglas Gregor4ad96852009-11-19 07:41:15 +00004570/// \brief Descripts the kind of Objective-C method that we want to find
4571/// via code completion.
4572enum ObjCMethodKind {
4573 MK_Any, //< Any kind of method, provided it means other specified criteria.
4574 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4575 MK_OneArgSelector //< One-argument selector.
4576};
4577
Douglas Gregor458433d2010-08-26 15:07:07 +00004578static bool isAcceptableObjCSelector(Selector Sel,
4579 ObjCMethodKind WantKind,
4580 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004581 unsigned NumSelIdents,
4582 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004583 if (NumSelIdents > Sel.getNumArgs())
4584 return false;
4585
4586 switch (WantKind) {
4587 case MK_Any: break;
4588 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4589 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4590 }
4591
Douglas Gregorcf544262010-11-17 21:36:08 +00004592 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4593 return false;
4594
Douglas Gregor458433d2010-08-26 15:07:07 +00004595 for (unsigned I = 0; I != NumSelIdents; ++I)
4596 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4597 return false;
4598
4599 return true;
4600}
4601
Douglas Gregor4ad96852009-11-19 07:41:15 +00004602static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4603 ObjCMethodKind WantKind,
4604 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004605 unsigned NumSelIdents,
4606 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004607 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004608 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004609}
Douglas Gregord36adf52010-09-16 16:06:31 +00004610
4611namespace {
4612 /// \brief A set of selectors, which is used to avoid introducing multiple
4613 /// completions with the same selector into the result set.
4614 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4615}
4616
Douglas Gregor36ecb042009-11-17 23:22:23 +00004617/// \brief Add all of the Objective-C methods in the given Objective-C
4618/// container to the set of results.
4619///
4620/// The container will be a class, protocol, category, or implementation of
4621/// any of the above. This mether will recurse to include methods from
4622/// the superclasses of classes along with their categories, protocols, and
4623/// implementations.
4624///
4625/// \param Container the container in which we'll look to find methods.
4626///
4627/// \param WantInstance whether to add instance methods (only); if false, this
4628/// routine will add factory methods (only).
4629///
4630/// \param CurContext the context in which we're performing the lookup that
4631/// finds methods.
4632///
Douglas Gregorcf544262010-11-17 21:36:08 +00004633/// \param AllowSameLength Whether we allow a method to be added to the list
4634/// when it has the same number of parameters as we have selector identifiers.
4635///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004636/// \param Results the structure into which we'll add results.
4637static void AddObjCMethods(ObjCContainerDecl *Container,
4638 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004639 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004640 IdentifierInfo **SelIdents,
4641 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004642 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004643 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004644 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004645 ResultBuilder &Results,
4646 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004647 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004648 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4649 MEnd = Container->meth_end();
4650 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004651 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4652 // Check whether the selector identifiers we've been given are a
4653 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004654 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4655 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004656 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004657
Douglas Gregord36adf52010-09-16 16:06:31 +00004658 if (!Selectors.insert((*M)->getSelector()))
4659 continue;
4660
Douglas Gregord3c68542009-11-19 01:08:35 +00004661 Result R = Result(*M, 0);
4662 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004663 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004664 if (!InOriginalClass)
4665 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004666 Results.MaybeAddResult(R, CurContext);
4667 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004668 }
4669
Douglas Gregore396c7b2010-09-16 15:34:59 +00004670 // Visit the protocols of protocols.
4671 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004672 if (Protocol->hasDefinition()) {
4673 const ObjCList<ObjCProtocolDecl> &Protocols
4674 = Protocol->getReferencedProtocols();
4675 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4676 E = Protocols.end();
4677 I != E; ++I)
4678 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4679 NumSelIdents, CurContext, Selectors, AllowSameLength,
4680 Results, false);
4681 }
Douglas Gregore396c7b2010-09-16 15:34:59 +00004682 }
4683
Douglas Gregor36ecb042009-11-17 23:22:23 +00004684 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00004685 if (!IFace || !IFace->hasDefinition())
Douglas Gregor36ecb042009-11-17 23:22:23 +00004686 return;
4687
4688 // Add methods in protocols.
4689 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4690 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4691 E = Protocols.end();
4692 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004693 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004694 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004695
4696 // Add methods in categories.
4697 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4698 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004699 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004700 NumSelIdents, CurContext, Selectors, AllowSameLength,
4701 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004702
4703 // Add a categories protocol methods.
4704 const ObjCList<ObjCProtocolDecl> &Protocols
4705 = CatDecl->getReferencedProtocols();
4706 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4707 E = Protocols.end();
4708 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004709 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004710 NumSelIdents, CurContext, Selectors, AllowSameLength,
4711 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004712
4713 // Add methods in category implementations.
4714 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004715 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004716 NumSelIdents, CurContext, Selectors, AllowSameLength,
4717 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004718 }
4719
4720 // Add methods in superclass.
4721 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004722 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004723 SelIdents, NumSelIdents, CurContext, Selectors,
4724 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004725
4726 // Add methods in our implementation, if any.
4727 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004728 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004729 NumSelIdents, CurContext, Selectors, AllowSameLength,
4730 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004731}
4732
4733
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004734void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004735 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004736
4737 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004738 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004739 if (!Class) {
4740 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004741 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004742 Class = Category->getClassInterface();
4743
4744 if (!Class)
4745 return;
4746 }
4747
4748 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004749 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4750 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004751 Results.EnterNewScope();
4752
Douglas Gregord36adf52010-09-16 16:06:31 +00004753 VisitedSelectorSet Selectors;
4754 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004755 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004756 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004757 HandleCodeCompleteResults(this, CodeCompleter,
4758 CodeCompletionContext::CCC_Other,
4759 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004760}
4761
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004762void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004763 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004764
4765 // Try to find the interface where setters might live.
4766 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004767 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004768 if (!Class) {
4769 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004770 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004771 Class = Category->getClassInterface();
4772
4773 if (!Class)
4774 return;
4775 }
4776
4777 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004778 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4779 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004780 Results.EnterNewScope();
4781
Douglas Gregord36adf52010-09-16 16:06:31 +00004782 VisitedSelectorSet Selectors;
4783 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004784 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004785
4786 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004787 HandleCodeCompleteResults(this, CodeCompleter,
4788 CodeCompletionContext::CCC_Other,
4789 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004790}
4791
Douglas Gregorafc45782011-02-15 22:19:42 +00004792void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4793 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004794 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004795 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4796 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004797 Results.EnterNewScope();
4798
4799 // Add context-sensitive, Objective-C parameter-passing keywords.
4800 bool AddedInOut = false;
4801 if ((DS.getObjCDeclQualifier() &
4802 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4803 Results.AddResult("in");
4804 Results.AddResult("inout");
4805 AddedInOut = true;
4806 }
4807 if ((DS.getObjCDeclQualifier() &
4808 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4809 Results.AddResult("out");
4810 if (!AddedInOut)
4811 Results.AddResult("inout");
4812 }
4813 if ((DS.getObjCDeclQualifier() &
4814 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4815 ObjCDeclSpec::DQ_Oneway)) == 0) {
4816 Results.AddResult("bycopy");
4817 Results.AddResult("byref");
4818 Results.AddResult("oneway");
4819 }
4820
Douglas Gregorafc45782011-02-15 22:19:42 +00004821 // If we're completing the return type of an Objective-C method and the
4822 // identifier IBAction refers to a macro, provide a completion item for
4823 // an action, e.g.,
4824 // IBAction)<#selector#>:(id)sender
4825 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4826 Context.Idents.get("IBAction").hasMacroDefinition()) {
4827 typedef CodeCompletionString::Chunk Chunk;
4828 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4829 CXAvailability_Available);
4830 Builder.AddTypedTextChunk("IBAction");
4831 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4832 Builder.AddPlaceholderChunk("selector");
4833 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4834 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4835 Builder.AddTextChunk("id");
4836 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4837 Builder.AddTextChunk("sender");
4838 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4839 }
4840
Douglas Gregord32b0222010-08-24 01:06:58 +00004841 // Add various builtin type names and specifiers.
4842 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4843 Results.ExitScope();
4844
4845 // Add the various type names
4846 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4847 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4848 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4849 CodeCompleter->includeGlobals());
4850
4851 if (CodeCompleter->includeMacros())
4852 AddMacroResults(PP, Results);
4853
4854 HandleCodeCompleteResults(this, CodeCompleter,
4855 CodeCompletionContext::CCC_Type,
4856 Results.data(), Results.size());
4857}
4858
Douglas Gregor22f56992010-04-06 19:22:33 +00004859/// \brief When we have an expression with type "id", we may assume
4860/// that it has some more-specific class type based on knowledge of
4861/// common uses of Objective-C. This routine returns that class type,
4862/// or NULL if no better result could be determined.
4863static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004864 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004865 if (!Msg)
4866 return 0;
4867
4868 Selector Sel = Msg->getSelector();
4869 if (Sel.isNull())
4870 return 0;
4871
4872 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4873 if (!Id)
4874 return 0;
4875
4876 ObjCMethodDecl *Method = Msg->getMethodDecl();
4877 if (!Method)
4878 return 0;
4879
4880 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004881 ObjCInterfaceDecl *IFace = 0;
4882 switch (Msg->getReceiverKind()) {
4883 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004884 if (const ObjCObjectType *ObjType
4885 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4886 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004887 break;
4888
4889 case ObjCMessageExpr::Instance: {
4890 QualType T = Msg->getInstanceReceiver()->getType();
4891 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4892 IFace = Ptr->getInterfaceDecl();
4893 break;
4894 }
4895
4896 case ObjCMessageExpr::SuperInstance:
4897 case ObjCMessageExpr::SuperClass:
4898 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004899 }
4900
4901 if (!IFace)
4902 return 0;
4903
4904 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4905 if (Method->isInstanceMethod())
4906 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4907 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004908 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004909 .Case("autorelease", IFace)
4910 .Case("copy", IFace)
4911 .Case("copyWithZone", IFace)
4912 .Case("mutableCopy", IFace)
4913 .Case("mutableCopyWithZone", IFace)
4914 .Case("awakeFromCoder", IFace)
4915 .Case("replacementObjectFromCoder", IFace)
4916 .Case("class", IFace)
4917 .Case("classForCoder", IFace)
4918 .Case("superclass", Super)
4919 .Default(0);
4920
4921 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4922 .Case("new", IFace)
4923 .Case("alloc", IFace)
4924 .Case("allocWithZone", IFace)
4925 .Case("class", IFace)
4926 .Case("superclass", Super)
4927 .Default(0);
4928}
4929
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004930// Add a special completion for a message send to "super", which fills in the
4931// most likely case of forwarding all of our arguments to the superclass
4932// function.
4933///
4934/// \param S The semantic analysis object.
4935///
4936/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4937/// the "super" keyword. Otherwise, we just need to provide the arguments.
4938///
4939/// \param SelIdents The identifiers in the selector that have already been
4940/// provided as arguments for a send to "super".
4941///
4942/// \param NumSelIdents The number of identifiers in \p SelIdents.
4943///
4944/// \param Results The set of results to augment.
4945///
4946/// \returns the Objective-C method declaration that would be invoked by
4947/// this "super" completion. If NULL, no completion was added.
4948static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4949 IdentifierInfo **SelIdents,
4950 unsigned NumSelIdents,
4951 ResultBuilder &Results) {
4952 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4953 if (!CurMethod)
4954 return 0;
4955
4956 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4957 if (!Class)
4958 return 0;
4959
4960 // Try to find a superclass method with the same selector.
4961 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004962 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4963 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004964 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4965 CurMethod->isInstanceMethod());
4966
Douglas Gregor78bcd912011-02-16 00:51:18 +00004967 // Check in categories or class extensions.
4968 if (!SuperMethod) {
4969 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4970 Category = Category->getNextClassCategory())
4971 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4972 CurMethod->isInstanceMethod())))
4973 break;
4974 }
4975 }
4976
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004977 if (!SuperMethod)
4978 return 0;
4979
4980 // Check whether the superclass method has the same signature.
4981 if (CurMethod->param_size() != SuperMethod->param_size() ||
4982 CurMethod->isVariadic() != SuperMethod->isVariadic())
4983 return 0;
4984
4985 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4986 CurPEnd = CurMethod->param_end(),
4987 SuperP = SuperMethod->param_begin();
4988 CurP != CurPEnd; ++CurP, ++SuperP) {
4989 // Make sure the parameter types are compatible.
4990 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4991 (*SuperP)->getType()))
4992 return 0;
4993
4994 // Make sure we have a parameter name to forward!
4995 if (!(*CurP)->getIdentifier())
4996 return 0;
4997 }
4998
4999 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00005000 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005001
5002 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00005003 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5004 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005005
5006 // If we need the "super" keyword, add it (plus some spacing).
5007 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005008 Builder.AddTypedTextChunk("super");
5009 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005010 }
5011
5012 Selector Sel = CurMethod->getSelector();
5013 if (Sel.isUnarySelector()) {
5014 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00005015 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005016 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005017 else
Douglas Gregordae68752011-02-01 22:57:45 +00005018 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005019 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005020 } else {
5021 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5022 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5023 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005024 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005025
5026 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005027 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005028 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005029 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005030 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005031 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005032 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005033 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005034 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005035 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005036 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00005037 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005038 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005039 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005040 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005041 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005042 }
5043 }
5044 }
5045
Douglas Gregor218937c2011-02-01 19:23:04 +00005046 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005047 SuperMethod->isInstanceMethod()
5048 ? CXCursor_ObjCInstanceMethodDecl
5049 : CXCursor_ObjCClassMethodDecl));
5050 return SuperMethod;
5051}
5052
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005053void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005054 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005055 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5056 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005057 getLangOptions().CPlusPlus0x
5058 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5059 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005060
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005061 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5062 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00005063 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5064 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005065
5066 // If we are in an Objective-C method inside a class that has a superclass,
5067 // add "super" as an option.
5068 if (ObjCMethodDecl *Method = getCurMethodDecl())
5069 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005070 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005071 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005072
5073 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
5074 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005075
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005076 if (getLangOptions().CPlusPlus0x)
5077 addThisCompletion(*this, Results);
5078
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005079 Results.ExitScope();
5080
5081 if (CodeCompleter->includeMacros())
5082 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00005083 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005084 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005085
5086}
5087
Douglas Gregor2725ca82010-04-21 19:57:20 +00005088void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5089 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005090 unsigned NumSelIdents,
5091 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00005092 ObjCInterfaceDecl *CDecl = 0;
5093 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5094 // Figure out which interface we're in.
5095 CDecl = CurMethod->getClassInterface();
5096 if (!CDecl)
5097 return;
5098
5099 // Find the superclass of this class.
5100 CDecl = CDecl->getSuperClass();
5101 if (!CDecl)
5102 return;
5103
5104 if (CurMethod->isInstanceMethod()) {
5105 // We are inside an instance method, which means that the message
5106 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005107 // current object.
5108 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005109 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005110 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005111 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005112 }
5113
5114 // Fall through to send to the superclass in CDecl.
5115 } else {
5116 // "super" may be the name of a type or variable. Figure out which
5117 // it is.
5118 IdentifierInfo *Super = &Context.Idents.get("super");
5119 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5120 LookupOrdinaryName);
5121 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5122 // "super" names an interface. Use it.
5123 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005124 if (const ObjCObjectType *Iface
5125 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5126 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005127 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5128 // "super" names an unresolved type; we can't be more specific.
5129 } else {
5130 // Assume that "super" names some kind of value and parse that way.
5131 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005132 SourceLocation TemplateKWLoc;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005133 UnqualifiedId id;
5134 id.setIdentifier(Super, SuperLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005135 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5136 false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005137 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005138 SelIdents, NumSelIdents,
5139 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005140 }
5141
5142 // Fall through
5143 }
5144
John McCallb3d87482010-08-24 05:47:05 +00005145 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005146 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005147 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005148 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005149 NumSelIdents, AtArgumentExpression,
5150 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005151}
5152
Douglas Gregorb9d77572010-09-21 00:03:25 +00005153/// \brief Given a set of code-completion results for the argument of a message
5154/// send, determine the preferred type (if any) for that argument expression.
5155static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5156 unsigned NumSelIdents) {
5157 typedef CodeCompletionResult Result;
5158 ASTContext &Context = Results.getSema().Context;
5159
5160 QualType PreferredType;
5161 unsigned BestPriority = CCP_Unlikely * 2;
5162 Result *ResultsData = Results.data();
5163 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5164 Result &R = ResultsData[I];
5165 if (R.Kind == Result::RK_Declaration &&
5166 isa<ObjCMethodDecl>(R.Declaration)) {
5167 if (R.Priority <= BestPriority) {
5168 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5169 if (NumSelIdents <= Method->param_size()) {
5170 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5171 ->getType();
5172 if (R.Priority < BestPriority || PreferredType.isNull()) {
5173 BestPriority = R.Priority;
5174 PreferredType = MyPreferredType;
5175 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5176 MyPreferredType)) {
5177 PreferredType = QualType();
5178 }
5179 }
5180 }
5181 }
5182 }
5183
5184 return PreferredType;
5185}
5186
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005187static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5188 ParsedType Receiver,
5189 IdentifierInfo **SelIdents,
5190 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005191 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005192 bool IsSuper,
5193 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005194 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005195 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005196
Douglas Gregor24a069f2009-11-17 17:59:40 +00005197 // If the given name refers to an interface type, retrieve the
5198 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005199 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005200 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005201 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005202 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5203 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005204 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005205
Douglas Gregor36ecb042009-11-17 23:22:23 +00005206 // Add all of the factory methods in this Objective-C class, its protocols,
5207 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005208 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005209
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005210 // If this is a send-to-super, try to add the special "super" send
5211 // completion.
5212 if (IsSuper) {
5213 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005214 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5215 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005216 Results.Ignore(SuperMethod);
5217 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005218
Douglas Gregor265f7492010-08-27 15:29:55 +00005219 // If we're inside an Objective-C method definition, prefer its selector to
5220 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005221 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005222 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005223
Douglas Gregord36adf52010-09-16 16:06:31 +00005224 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005225 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005226 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005227 SemaRef.CurContext, Selectors, AtArgumentExpression,
5228 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005229 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005230 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005231
Douglas Gregor719770d2010-04-06 17:30:22 +00005232 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005233 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005234 if (SemaRef.ExternalSource) {
5235 for (uint32_t I = 0,
5236 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005237 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005238 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5239 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005240 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005241
5242 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005243 }
5244 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005245
5246 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5247 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005248 M != MEnd; ++M) {
5249 for (ObjCMethodList *MethList = &M->second.second;
5250 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005251 MethList = MethList->Next) {
5252 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5253 NumSelIdents))
5254 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005255
Douglas Gregor13438f92010-04-06 16:40:00 +00005256 Result R(MethList->Method, 0);
5257 R.StartParameter = NumSelIdents;
5258 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005259 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005260 }
5261 }
5262 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005263
5264 Results.ExitScope();
5265}
Douglas Gregor13438f92010-04-06 16:40:00 +00005266
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005267void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5268 IdentifierInfo **SelIdents,
5269 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005270 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005271 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005272
5273 QualType T = this->GetTypeFromParser(Receiver);
5274
Douglas Gregor218937c2011-02-01 19:23:04 +00005275 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005276 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005277 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005278
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005279 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5280 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005281
5282 // If we're actually at the argument expression (rather than prior to the
5283 // selector), we're actually performing code completion for an expression.
5284 // Determine whether we have a single, best method. If so, we can
5285 // code-complete the expression using the corresponding parameter type as
5286 // our preferred type, improving completion results.
5287 if (AtArgumentExpression) {
5288 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005289 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005290 if (PreferredType.isNull())
5291 CodeCompleteOrdinaryName(S, PCC_Expression);
5292 else
5293 CodeCompleteExpression(S, PreferredType);
5294 return;
5295 }
5296
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005297 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005298 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005299 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005300}
5301
Richard Trieuf81e5a92011-09-09 02:00:50 +00005302void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005303 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005304 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005305 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005306 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005307 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005308
5309 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005310
Douglas Gregor36ecb042009-11-17 23:22:23 +00005311 // If necessary, apply function/array conversion to the receiver.
5312 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005313 if (RecExpr) {
5314 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5315 if (Conv.isInvalid()) // conversion failed. bail.
5316 return;
5317 RecExpr = Conv.take();
5318 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005319 QualType ReceiverType = RecExpr? RecExpr->getType()
5320 : Super? Context.getObjCObjectPointerType(
5321 Context.getObjCInterfaceType(Super))
5322 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005323
Douglas Gregorda892642010-11-08 21:12:30 +00005324 // If we're messaging an expression with type "id" or "Class", check
5325 // whether we know something special about the receiver that allows
5326 // us to assume a more-specific receiver type.
5327 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5328 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5329 if (ReceiverType->isObjCClassType())
5330 return CodeCompleteObjCClassMessage(S,
5331 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5332 SelIdents, NumSelIdents,
5333 AtArgumentExpression, Super);
5334
5335 ReceiverType = Context.getObjCObjectPointerType(
5336 Context.getObjCInterfaceType(IFace));
5337 }
5338
Douglas Gregor36ecb042009-11-17 23:22:23 +00005339 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005340 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005341 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005342 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005343
Douglas Gregor36ecb042009-11-17 23:22:23 +00005344 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005345
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005346 // If this is a send-to-super, try to add the special "super" send
5347 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005348 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005349 if (ObjCMethodDecl *SuperMethod
5350 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5351 Results))
5352 Results.Ignore(SuperMethod);
5353 }
5354
Douglas Gregor265f7492010-08-27 15:29:55 +00005355 // If we're inside an Objective-C method definition, prefer its selector to
5356 // others.
5357 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5358 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005359
Douglas Gregord36adf52010-09-16 16:06:31 +00005360 // Keep track of the selectors we've already added.
5361 VisitedSelectorSet Selectors;
5362
Douglas Gregorf74a4192009-11-18 00:06:18 +00005363 // Handle messages to Class. This really isn't a message to an instance
5364 // method, so we treat it the same way we would treat a message send to a
5365 // class method.
5366 if (ReceiverType->isObjCClassType() ||
5367 ReceiverType->isObjCQualifiedClassType()) {
5368 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5369 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005370 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005371 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005372 }
5373 }
5374 // Handle messages to a qualified ID ("id<foo>").
5375 else if (const ObjCObjectPointerType *QualID
5376 = ReceiverType->getAsObjCQualifiedIdType()) {
5377 // Search protocols for instance methods.
5378 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5379 E = QualID->qual_end();
5380 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005381 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005382 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005383 }
5384 // Handle messages to a pointer to interface type.
5385 else if (const ObjCObjectPointerType *IFacePtr
5386 = ReceiverType->getAsObjCInterfacePointerType()) {
5387 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005388 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005389 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5390 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005391
5392 // Search protocols for instance methods.
5393 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5394 E = IFacePtr->qual_end();
5395 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005396 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005397 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005398 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005399 // Handle messages to "id".
5400 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005401 // We're messaging "id", so provide all instance methods we know
5402 // about as code-completion results.
5403
5404 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005405 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005406 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005407 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5408 I != N; ++I) {
5409 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005410 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005411 continue;
5412
Sebastian Redldb9d2142010-08-02 23:18:59 +00005413 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005414 }
5415 }
5416
Sebastian Redldb9d2142010-08-02 23:18:59 +00005417 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5418 MEnd = MethodPool.end();
5419 M != MEnd; ++M) {
5420 for (ObjCMethodList *MethList = &M->second.first;
5421 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005422 MethList = MethList->Next) {
5423 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5424 NumSelIdents))
5425 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005426
5427 if (!Selectors.insert(MethList->Method->getSelector()))
5428 continue;
5429
Douglas Gregor13438f92010-04-06 16:40:00 +00005430 Result R(MethList->Method, 0);
5431 R.StartParameter = NumSelIdents;
5432 R.AllParametersAreInformative = false;
5433 Results.MaybeAddResult(R, CurContext);
5434 }
5435 }
5436 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005437 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005438
5439
5440 // If we're actually at the argument expression (rather than prior to the
5441 // selector), we're actually performing code completion for an expression.
5442 // Determine whether we have a single, best method. If so, we can
5443 // code-complete the expression using the corresponding parameter type as
5444 // our preferred type, improving completion results.
5445 if (AtArgumentExpression) {
5446 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5447 NumSelIdents);
5448 if (PreferredType.isNull())
5449 CodeCompleteOrdinaryName(S, PCC_Expression);
5450 else
5451 CodeCompleteExpression(S, PreferredType);
5452 return;
5453 }
5454
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005455 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005456 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005457 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005458}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005459
Douglas Gregorfb629412010-08-23 21:17:50 +00005460void Sema::CodeCompleteObjCForCollection(Scope *S,
5461 DeclGroupPtrTy IterationVar) {
5462 CodeCompleteExpressionData Data;
5463 Data.ObjCCollection = true;
5464
5465 if (IterationVar.getAsOpaquePtr()) {
5466 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5467 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5468 if (*I)
5469 Data.IgnoreDecls.push_back(*I);
5470 }
5471 }
5472
5473 CodeCompleteExpression(S, Data);
5474}
5475
Douglas Gregor458433d2010-08-26 15:07:07 +00005476void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5477 unsigned NumSelIdents) {
5478 // If we have an external source, load the entire class method
5479 // pool from the AST file.
5480 if (ExternalSource) {
5481 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5482 I != N; ++I) {
5483 Selector Sel = ExternalSource->GetExternalSelector(I);
5484 if (Sel.isNull() || MethodPool.count(Sel))
5485 continue;
5486
5487 ReadMethodPool(Sel);
5488 }
5489 }
5490
Douglas Gregor218937c2011-02-01 19:23:04 +00005491 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5492 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005493 Results.EnterNewScope();
5494 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5495 MEnd = MethodPool.end();
5496 M != MEnd; ++M) {
5497
5498 Selector Sel = M->first;
5499 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5500 continue;
5501
Douglas Gregor218937c2011-02-01 19:23:04 +00005502 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005503 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005504 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005505 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005506 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005507 continue;
5508 }
5509
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005510 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005511 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005512 if (I == NumSelIdents) {
5513 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005514 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005515 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005516 Accumulator.clear();
5517 }
5518 }
5519
Benjamin Kramera0651c52011-07-26 16:59:25 +00005520 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005521 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005522 }
Douglas Gregordae68752011-02-01 22:57:45 +00005523 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005524 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005525 }
5526 Results.ExitScope();
5527
5528 HandleCodeCompleteResults(this, CodeCompleter,
5529 CodeCompletionContext::CCC_SelectorName,
5530 Results.data(), Results.size());
5531}
5532
Douglas Gregor55385fe2009-11-18 04:19:12 +00005533/// \brief Add all of the protocol declarations that we find in the given
5534/// (translation unit) context.
5535static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005536 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005537 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005538 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005539
5540 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5541 DEnd = Ctx->decls_end();
5542 D != DEnd; ++D) {
5543 // Record any protocols we find.
5544 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005545 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregor608300b2010-01-14 16:14:35 +00005546 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005547 }
5548}
5549
5550void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5551 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005552 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5553 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005554
Douglas Gregor70c23352010-12-09 21:44:02 +00005555 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5556 Results.EnterNewScope();
5557
5558 // Tell the result set to ignore all of the protocols we have
5559 // already seen.
5560 // FIXME: This doesn't work when caching code-completion results.
5561 for (unsigned I = 0; I != NumProtocols; ++I)
5562 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5563 Protocols[I].second))
5564 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005565
Douglas Gregor70c23352010-12-09 21:44:02 +00005566 // Add all protocols.
5567 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5568 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005569
Douglas Gregor70c23352010-12-09 21:44:02 +00005570 Results.ExitScope();
5571 }
5572
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005573 HandleCodeCompleteResults(this, CodeCompleter,
5574 CodeCompletionContext::CCC_ObjCProtocolName,
5575 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005576}
5577
5578void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005579 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5580 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005581
Douglas Gregor70c23352010-12-09 21:44:02 +00005582 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5583 Results.EnterNewScope();
5584
5585 // Add all protocols.
5586 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5587 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005588
Douglas Gregor70c23352010-12-09 21:44:02 +00005589 Results.ExitScope();
5590 }
5591
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005592 HandleCodeCompleteResults(this, CodeCompleter,
5593 CodeCompletionContext::CCC_ObjCProtocolName,
5594 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005595}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005596
5597/// \brief Add all of the Objective-C interface declarations that we find in
5598/// the given (translation unit) context.
5599static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5600 bool OnlyForwardDeclarations,
5601 bool OnlyUnimplemented,
5602 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005603 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005604
5605 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5606 DEnd = Ctx->decls_end();
5607 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005608 // Record any interfaces we find.
5609 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregor7723fec2011-12-15 20:29:51 +00005610 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005611 (!OnlyUnimplemented || !Class->getImplementation()))
5612 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005613 }
5614}
5615
5616void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005617 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5618 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005619 Results.EnterNewScope();
5620
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005621 if (CodeCompleter->includeGlobals()) {
5622 // Add all classes.
5623 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5624 false, Results);
5625 }
5626
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005627 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005628
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005629 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005630 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005631 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005632}
5633
Douglas Gregorc83c6872010-04-15 22:33:43 +00005634void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5635 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005636 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005637 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005638 Results.EnterNewScope();
5639
5640 // Make sure that we ignore the class we're currently defining.
5641 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005642 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005643 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005644 Results.Ignore(CurClass);
5645
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005646 if (CodeCompleter->includeGlobals()) {
5647 // Add all classes.
5648 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5649 false, Results);
5650 }
5651
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005652 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005653
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005654 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005655 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005656 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005657}
5658
5659void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005660 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5661 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005662 Results.EnterNewScope();
5663
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005664 if (CodeCompleter->includeGlobals()) {
5665 // Add all unimplemented classes.
5666 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5667 true, Results);
5668 }
5669
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005670 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005671
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005672 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005673 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005674 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005675}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005676
5677void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005678 IdentifierInfo *ClassName,
5679 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005680 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005681
Douglas Gregor218937c2011-02-01 19:23:04 +00005682 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005683 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005684
5685 // Ignore any categories we find that have already been implemented by this
5686 // interface.
5687 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5688 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005689 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005690 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5691 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5692 Category = Category->getNextClassCategory())
5693 CategoryNames.insert(Category->getIdentifier());
5694
5695 // Add all of the categories we know about.
5696 Results.EnterNewScope();
5697 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5698 for (DeclContext::decl_iterator D = TU->decls_begin(),
5699 DEnd = TU->decls_end();
5700 D != DEnd; ++D)
5701 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5702 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005703 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005704 Results.ExitScope();
5705
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005706 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005707 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005708 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005709}
5710
5711void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005712 IdentifierInfo *ClassName,
5713 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005714 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005715
5716 // Find the corresponding interface. If we couldn't find the interface, the
5717 // program itself is ill-formed. However, we'll try to be helpful still by
5718 // providing the list of all of the categories we know about.
5719 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005720 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005721 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5722 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005723 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005724
Douglas Gregor218937c2011-02-01 19:23:04 +00005725 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005726 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005727
5728 // Add all of the categories that have have corresponding interface
5729 // declarations in this class and any of its superclasses, except for
5730 // already-implemented categories in the class itself.
5731 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5732 Results.EnterNewScope();
5733 bool IgnoreImplemented = true;
5734 while (Class) {
5735 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5736 Category = Category->getNextClassCategory())
5737 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5738 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005739 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005740
5741 Class = Class->getSuperClass();
5742 IgnoreImplemented = false;
5743 }
5744 Results.ExitScope();
5745
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005746 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005747 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005748 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005749}
Douglas Gregor322328b2009-11-18 22:32:06 +00005750
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005751void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005752 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005753 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5754 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005755
5756 // Figure out where this @synthesize lives.
5757 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005758 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005759 if (!Container ||
5760 (!isa<ObjCImplementationDecl>(Container) &&
5761 !isa<ObjCCategoryImplDecl>(Container)))
5762 return;
5763
5764 // Ignore any properties that have already been implemented.
5765 for (DeclContext::decl_iterator D = Container->decls_begin(),
5766 DEnd = Container->decls_end();
5767 D != DEnd; ++D)
5768 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5769 Results.Ignore(PropertyImpl->getPropertyDecl());
5770
5771 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005772 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005773 Results.EnterNewScope();
5774 if (ObjCImplementationDecl *ClassImpl
5775 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005776 AddObjCProperties(ClassImpl->getClassInterface(), false,
5777 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005778 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005779 else
5780 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005781 false, /*AllowNullaryMethods=*/false, CurContext,
5782 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005783 Results.ExitScope();
5784
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005785 HandleCodeCompleteResults(this, CodeCompleter,
5786 CodeCompletionContext::CCC_Other,
5787 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005788}
5789
5790void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005791 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005792 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005793 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5794 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005795
5796 // Figure out where this @synthesize lives.
5797 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005798 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005799 if (!Container ||
5800 (!isa<ObjCImplementationDecl>(Container) &&
5801 !isa<ObjCCategoryImplDecl>(Container)))
5802 return;
5803
5804 // Figure out which interface we're looking into.
5805 ObjCInterfaceDecl *Class = 0;
5806 if (ObjCImplementationDecl *ClassImpl
5807 = dyn_cast<ObjCImplementationDecl>(Container))
5808 Class = ClassImpl->getClassInterface();
5809 else
5810 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5811 ->getClassInterface();
5812
Douglas Gregore8426052011-04-18 14:40:46 +00005813 // Determine the type of the property we're synthesizing.
5814 QualType PropertyType = Context.getObjCIdType();
5815 if (Class) {
5816 if (ObjCPropertyDecl *Property
5817 = Class->FindPropertyDeclaration(PropertyName)) {
5818 PropertyType
5819 = Property->getType().getNonReferenceType().getUnqualifiedType();
5820
5821 // Give preference to ivars
5822 Results.setPreferredType(PropertyType);
5823 }
5824 }
5825
Douglas Gregor322328b2009-11-18 22:32:06 +00005826 // Add all of the instance variables in this class and its superclasses.
5827 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005828 bool SawSimilarlyNamedIvar = false;
5829 std::string NameWithPrefix;
5830 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005831 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005832 std::string NameWithSuffix = PropertyName->getName().str();
5833 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005834 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005835 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5836 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005837 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5838
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005839 // Determine whether we've seen an ivar with a name similar to the
5840 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005841 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005842 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005843 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005844 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005845
5846 // Reduce the priority of this result by one, to give it a slight
5847 // advantage over other results whose names don't match so closely.
5848 if (Results.size() &&
5849 Results.data()[Results.size() - 1].Kind
5850 == CodeCompletionResult::RK_Declaration &&
5851 Results.data()[Results.size() - 1].Declaration == Ivar)
5852 Results.data()[Results.size() - 1].Priority--;
5853 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005854 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005855 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005856
5857 if (!SawSimilarlyNamedIvar) {
5858 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005859 // an ivar of the appropriate type.
5860 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005861 typedef CodeCompletionResult Result;
5862 CodeCompletionAllocator &Allocator = Results.getAllocator();
5863 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5864
Douglas Gregor8987b232011-09-27 23:30:47 +00005865 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005866 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005867 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005868 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5869 Results.AddResult(Result(Builder.TakeString(), Priority,
5870 CXCursor_ObjCIvarDecl));
5871 }
5872
Douglas Gregor322328b2009-11-18 22:32:06 +00005873 Results.ExitScope();
5874
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005875 HandleCodeCompleteResults(this, CodeCompleter,
5876 CodeCompletionContext::CCC_Other,
5877 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005878}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005879
Douglas Gregor408be5a2010-08-25 01:08:01 +00005880// Mapping from selectors to the methods that implement that selector, along
5881// with the "in original class" flag.
5882typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5883 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005884
5885/// \brief Find all of the methods that reside in the given container
5886/// (and its superclasses, protocols, etc.) that meet the given
5887/// criteria. Insert those methods into the map of known methods,
5888/// indexed by selector so they can be easily found.
5889static void FindImplementableMethods(ASTContext &Context,
5890 ObjCContainerDecl *Container,
5891 bool WantInstanceMethods,
5892 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005893 KnownMethodsMap &KnownMethods,
5894 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005895 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5896 // Recurse into protocols.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00005897 if (!IFace->hasDefinition())
5898 return;
5899
Douglas Gregore8f5a172010-04-07 00:21:17 +00005900 const ObjCList<ObjCProtocolDecl> &Protocols
5901 = IFace->getReferencedProtocols();
5902 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005903 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005904 I != E; ++I)
5905 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005906 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005907
Douglas Gregorea766182010-10-18 18:21:28 +00005908 // Add methods from any class extensions and categories.
5909 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5910 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005911 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5912 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005913 KnownMethods, false);
5914
5915 // Visit the superclass.
5916 if (IFace->getSuperClass())
5917 FindImplementableMethods(Context, IFace->getSuperClass(),
5918 WantInstanceMethods, ReturnType,
5919 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005920 }
5921
5922 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5923 // Recurse into protocols.
5924 const ObjCList<ObjCProtocolDecl> &Protocols
5925 = Category->getReferencedProtocols();
5926 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005927 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005928 I != E; ++I)
5929 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005930 KnownMethods, InOriginalClass);
5931
5932 // If this category is the original class, jump to the interface.
5933 if (InOriginalClass && Category->getClassInterface())
5934 FindImplementableMethods(Context, Category->getClassInterface(),
5935 WantInstanceMethods, ReturnType, KnownMethods,
5936 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005937 }
5938
5939 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005940 if (Protocol->hasDefinition()) {
5941 // Recurse into protocols.
5942 const ObjCList<ObjCProtocolDecl> &Protocols
5943 = Protocol->getReferencedProtocols();
5944 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5945 E = Protocols.end();
5946 I != E; ++I)
5947 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5948 KnownMethods, false);
5949 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005950 }
5951
5952 // Add methods in this container. This operation occurs last because
5953 // we want the methods from this container to override any methods
5954 // we've previously seen with the same selector.
5955 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5956 MEnd = Container->meth_end();
5957 M != MEnd; ++M) {
5958 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5959 if (!ReturnType.isNull() &&
5960 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5961 continue;
5962
Douglas Gregor408be5a2010-08-25 01:08:01 +00005963 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005964 }
5965 }
5966}
5967
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005968/// \brief Add the parenthesized return or parameter type chunk to a code
5969/// completion string.
5970static void AddObjCPassingTypeChunk(QualType Type,
5971 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005972 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005973 CodeCompletionBuilder &Builder) {
5974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005975 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005976 Builder.getAllocator()));
5977 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5978}
5979
5980/// \brief Determine whether the given class is or inherits from a class by
5981/// the given name.
5982static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005983 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005984 if (!Class)
5985 return false;
5986
5987 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5988 return true;
5989
5990 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5991}
5992
5993/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5994/// Key-Value Observing (KVO).
5995static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5996 bool IsInstanceMethod,
5997 QualType ReturnType,
5998 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005999 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006000 ResultBuilder &Results) {
6001 IdentifierInfo *PropName = Property->getIdentifier();
6002 if (!PropName || PropName->getLength() == 0)
6003 return;
6004
Douglas Gregor8987b232011-09-27 23:30:47 +00006005 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6006
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006007 // Builder that will create each code completion.
6008 typedef CodeCompletionResult Result;
6009 CodeCompletionAllocator &Allocator = Results.getAllocator();
6010 CodeCompletionBuilder Builder(Allocator);
6011
6012 // The selector table.
6013 SelectorTable &Selectors = Context.Selectors;
6014
6015 // The property name, copied into the code completion allocation region
6016 // on demand.
6017 struct KeyHolder {
6018 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006019 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006020 const char *CopiedKey;
6021
Chris Lattner5f9e2722011-07-23 10:55:15 +00006022 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006023 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6024
6025 operator const char *() {
6026 if (CopiedKey)
6027 return CopiedKey;
6028
6029 return CopiedKey = Allocator.CopyString(Key);
6030 }
6031 } Key(Allocator, PropName->getName());
6032
6033 // The uppercased name of the property name.
6034 std::string UpperKey = PropName->getName();
6035 if (!UpperKey.empty())
6036 UpperKey[0] = toupper(UpperKey[0]);
6037
6038 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6039 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6040 Property->getType());
6041 bool ReturnTypeMatchesVoid
6042 = ReturnType.isNull() || ReturnType->isVoidType();
6043
6044 // Add the normal accessor -(type)key.
6045 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00006046 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006047 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6048 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006049 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006050
6051 Builder.AddTypedTextChunk(Key);
6052 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6053 CXCursor_ObjCInstanceMethodDecl));
6054 }
6055
6056 // If we have an integral or boolean property (or the user has provided
6057 // an integral or boolean return type), add the accessor -(type)isKey.
6058 if (IsInstanceMethod &&
6059 ((!ReturnType.isNull() &&
6060 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6061 (ReturnType.isNull() &&
6062 (Property->getType()->isIntegerType() ||
6063 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006064 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006065 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006066 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006067 if (ReturnType.isNull()) {
6068 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6069 Builder.AddTextChunk("BOOL");
6070 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6071 }
6072
6073 Builder.AddTypedTextChunk(
6074 Allocator.CopyString(SelectorId->getName()));
6075 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6076 CXCursor_ObjCInstanceMethodDecl));
6077 }
6078 }
6079
6080 // Add the normal mutator.
6081 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6082 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006083 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006084 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006085 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006086 if (ReturnType.isNull()) {
6087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6088 Builder.AddTextChunk("void");
6089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6090 }
6091
6092 Builder.AddTypedTextChunk(
6093 Allocator.CopyString(SelectorId->getName()));
6094 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00006095 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006096 Builder.AddTextChunk(Key);
6097 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6098 CXCursor_ObjCInstanceMethodDecl));
6099 }
6100 }
6101
6102 // Indexed and unordered accessors
6103 unsigned IndexedGetterPriority = CCP_CodePattern;
6104 unsigned IndexedSetterPriority = CCP_CodePattern;
6105 unsigned UnorderedGetterPriority = CCP_CodePattern;
6106 unsigned UnorderedSetterPriority = CCP_CodePattern;
6107 if (const ObjCObjectPointerType *ObjCPointer
6108 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6109 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6110 // If this interface type is not provably derived from a known
6111 // collection, penalize the corresponding completions.
6112 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6113 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6114 if (!InheritsFromClassNamed(IFace, "NSArray"))
6115 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6116 }
6117
6118 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6119 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6120 if (!InheritsFromClassNamed(IFace, "NSSet"))
6121 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6122 }
6123 }
6124 } else {
6125 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6126 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6127 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6128 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6129 }
6130
6131 // Add -(NSUInteger)countOf<key>
6132 if (IsInstanceMethod &&
6133 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006134 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006135 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006136 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006137 if (ReturnType.isNull()) {
6138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6139 Builder.AddTextChunk("NSUInteger");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 }
6142
6143 Builder.AddTypedTextChunk(
6144 Allocator.CopyString(SelectorId->getName()));
6145 Results.AddResult(Result(Builder.TakeString(),
6146 std::min(IndexedGetterPriority,
6147 UnorderedGetterPriority),
6148 CXCursor_ObjCInstanceMethodDecl));
6149 }
6150 }
6151
6152 // Indexed getters
6153 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6154 if (IsInstanceMethod &&
6155 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006156 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006157 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006158 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006159 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006160 if (ReturnType.isNull()) {
6161 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6162 Builder.AddTextChunk("id");
6163 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6164 }
6165
6166 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6167 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6168 Builder.AddTextChunk("NSUInteger");
6169 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6170 Builder.AddTextChunk("index");
6171 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6172 CXCursor_ObjCInstanceMethodDecl));
6173 }
6174 }
6175
6176 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6177 if (IsInstanceMethod &&
6178 (ReturnType.isNull() ||
6179 (ReturnType->isObjCObjectPointerType() &&
6180 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6181 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6182 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006183 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006184 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006185 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006186 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006187 if (ReturnType.isNull()) {
6188 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6189 Builder.AddTextChunk("NSArray *");
6190 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6191 }
6192
6193 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6194 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6195 Builder.AddTextChunk("NSIndexSet *");
6196 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6197 Builder.AddTextChunk("indexes");
6198 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6199 CXCursor_ObjCInstanceMethodDecl));
6200 }
6201 }
6202
6203 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6204 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006205 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006206 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006207 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006208 &Context.Idents.get("range")
6209 };
6210
Douglas Gregore74c25c2011-05-04 23:50:46 +00006211 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006212 if (ReturnType.isNull()) {
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddTextChunk("void");
6215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6216 }
6217
6218 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddPlaceholderChunk("object-type");
6221 Builder.AddTextChunk(" **");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 Builder.AddTextChunk("buffer");
6224 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6225 Builder.AddTypedTextChunk("range:");
6226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6227 Builder.AddTextChunk("NSRange");
6228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6229 Builder.AddTextChunk("inRange");
6230 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6231 CXCursor_ObjCInstanceMethodDecl));
6232 }
6233 }
6234
6235 // Mutable indexed accessors
6236
6237 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6238 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006239 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006240 IdentifierInfo *SelectorIds[2] = {
6241 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006242 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006243 };
6244
Douglas Gregore74c25c2011-05-04 23:50:46 +00006245 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006246 if (ReturnType.isNull()) {
6247 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6248 Builder.AddTextChunk("void");
6249 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6250 }
6251
6252 Builder.AddTypedTextChunk("insertObject:");
6253 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6254 Builder.AddPlaceholderChunk("object-type");
6255 Builder.AddTextChunk(" *");
6256 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6257 Builder.AddTextChunk("object");
6258 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6259 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6260 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6261 Builder.AddPlaceholderChunk("NSUInteger");
6262 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6263 Builder.AddTextChunk("index");
6264 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6265 CXCursor_ObjCInstanceMethodDecl));
6266 }
6267 }
6268
6269 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6270 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006271 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006273 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006274 &Context.Idents.get("atIndexes")
6275 };
6276
Douglas Gregore74c25c2011-05-04 23:50:46 +00006277 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006278 if (ReturnType.isNull()) {
6279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6280 Builder.AddTextChunk("void");
6281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6282 }
6283
6284 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6286 Builder.AddTextChunk("NSArray *");
6287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6288 Builder.AddTextChunk("array");
6289 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6290 Builder.AddTypedTextChunk("atIndexes:");
6291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6292 Builder.AddPlaceholderChunk("NSIndexSet *");
6293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6294 Builder.AddTextChunk("indexes");
6295 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6296 CXCursor_ObjCInstanceMethodDecl));
6297 }
6298 }
6299
6300 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6301 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006302 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006303 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006304 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006305 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006306 if (ReturnType.isNull()) {
6307 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6308 Builder.AddTextChunk("void");
6309 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6310 }
6311
6312 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6313 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6314 Builder.AddTextChunk("NSUInteger");
6315 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6316 Builder.AddTextChunk("index");
6317 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6318 CXCursor_ObjCInstanceMethodDecl));
6319 }
6320 }
6321
6322 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6323 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006324 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006325 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006326 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006327 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006328 if (ReturnType.isNull()) {
6329 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6330 Builder.AddTextChunk("void");
6331 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6332 }
6333
6334 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6335 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6336 Builder.AddTextChunk("NSIndexSet *");
6337 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6338 Builder.AddTextChunk("indexes");
6339 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6340 CXCursor_ObjCInstanceMethodDecl));
6341 }
6342 }
6343
6344 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6345 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006346 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006347 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006348 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006349 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006350 &Context.Idents.get("withObject")
6351 };
6352
Douglas Gregore74c25c2011-05-04 23:50:46 +00006353 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006354 if (ReturnType.isNull()) {
6355 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6356 Builder.AddTextChunk("void");
6357 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6358 }
6359
6360 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6362 Builder.AddPlaceholderChunk("NSUInteger");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 Builder.AddTextChunk("index");
6365 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6366 Builder.AddTypedTextChunk("withObject:");
6367 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6368 Builder.AddTextChunk("id");
6369 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6370 Builder.AddTextChunk("object");
6371 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6372 CXCursor_ObjCInstanceMethodDecl));
6373 }
6374 }
6375
6376 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6377 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006378 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006379 = (Twine("replace") + UpperKey + "AtIndexes").str();
6380 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006382 &Context.Idents.get(SelectorName1),
6383 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006384 };
6385
Douglas Gregore74c25c2011-05-04 23:50:46 +00006386 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006387 if (ReturnType.isNull()) {
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddTextChunk("void");
6390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391 }
6392
6393 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6394 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6395 Builder.AddPlaceholderChunk("NSIndexSet *");
6396 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6397 Builder.AddTextChunk("indexes");
6398 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6399 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6400 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6401 Builder.AddTextChunk("NSArray *");
6402 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6403 Builder.AddTextChunk("array");
6404 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6405 CXCursor_ObjCInstanceMethodDecl));
6406 }
6407 }
6408
6409 // Unordered getters
6410 // - (NSEnumerator *)enumeratorOfKey
6411 if (IsInstanceMethod &&
6412 (ReturnType.isNull() ||
6413 (ReturnType->isObjCObjectPointerType() &&
6414 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6415 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6416 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006417 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006418 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006419 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006420 if (ReturnType.isNull()) {
6421 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6422 Builder.AddTextChunk("NSEnumerator *");
6423 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6424 }
6425
6426 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6427 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6428 CXCursor_ObjCInstanceMethodDecl));
6429 }
6430 }
6431
6432 // - (type *)memberOfKey:(type *)object
6433 if (IsInstanceMethod &&
6434 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006435 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006436 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006437 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006438 if (ReturnType.isNull()) {
6439 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6440 Builder.AddPlaceholderChunk("object-type");
6441 Builder.AddTextChunk(" *");
6442 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6443 }
6444
6445 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6446 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6447 if (ReturnType.isNull()) {
6448 Builder.AddPlaceholderChunk("object-type");
6449 Builder.AddTextChunk(" *");
6450 } else {
6451 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006452 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006453 Builder.getAllocator()));
6454 }
6455 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6456 Builder.AddTextChunk("object");
6457 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6458 CXCursor_ObjCInstanceMethodDecl));
6459 }
6460 }
6461
6462 // Mutable unordered accessors
6463 // - (void)addKeyObject:(type *)object
6464 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006465 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006466 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006467 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006468 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006469 if (ReturnType.isNull()) {
6470 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6471 Builder.AddTextChunk("void");
6472 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6473 }
6474
6475 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6476 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6477 Builder.AddPlaceholderChunk("object-type");
6478 Builder.AddTextChunk(" *");
6479 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6480 Builder.AddTextChunk("object");
6481 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6482 CXCursor_ObjCInstanceMethodDecl));
6483 }
6484 }
6485
6486 // - (void)addKey:(NSSet *)objects
6487 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006488 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006489 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006490 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006491 if (ReturnType.isNull()) {
6492 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6493 Builder.AddTextChunk("void");
6494 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6495 }
6496
6497 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6498 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6499 Builder.AddTextChunk("NSSet *");
6500 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6501 Builder.AddTextChunk("objects");
6502 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6503 CXCursor_ObjCInstanceMethodDecl));
6504 }
6505 }
6506
6507 // - (void)removeKeyObject:(type *)object
6508 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006509 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006510 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006511 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006512 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006513 if (ReturnType.isNull()) {
6514 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6515 Builder.AddTextChunk("void");
6516 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6517 }
6518
6519 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6520 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6521 Builder.AddPlaceholderChunk("object-type");
6522 Builder.AddTextChunk(" *");
6523 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6524 Builder.AddTextChunk("object");
6525 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6526 CXCursor_ObjCInstanceMethodDecl));
6527 }
6528 }
6529
6530 // - (void)removeKey:(NSSet *)objects
6531 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006532 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006533 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006534 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006535 if (ReturnType.isNull()) {
6536 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6537 Builder.AddTextChunk("void");
6538 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6539 }
6540
6541 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6542 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6543 Builder.AddTextChunk("NSSet *");
6544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6545 Builder.AddTextChunk("objects");
6546 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6547 CXCursor_ObjCInstanceMethodDecl));
6548 }
6549 }
6550
6551 // - (void)intersectKey:(NSSet *)objects
6552 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006553 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006554 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006555 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006556 if (ReturnType.isNull()) {
6557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6558 Builder.AddTextChunk("void");
6559 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6560 }
6561
6562 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6563 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564 Builder.AddTextChunk("NSSet *");
6565 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6566 Builder.AddTextChunk("objects");
6567 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6568 CXCursor_ObjCInstanceMethodDecl));
6569 }
6570 }
6571
6572 // Key-Value Observing
6573 // + (NSSet *)keyPathsForValuesAffectingKey
6574 if (!IsInstanceMethod &&
6575 (ReturnType.isNull() ||
6576 (ReturnType->isObjCObjectPointerType() &&
6577 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6578 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6579 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006580 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006581 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006582 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006583 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006584 if (ReturnType.isNull()) {
6585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6586 Builder.AddTextChunk("NSSet *");
6587 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6588 }
6589
6590 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6591 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006592 CXCursor_ObjCClassMethodDecl));
6593 }
6594 }
6595
6596 // + (BOOL)automaticallyNotifiesObserversForKey
6597 if (!IsInstanceMethod &&
6598 (ReturnType.isNull() ||
6599 ReturnType->isIntegerType() ||
6600 ReturnType->isBooleanType())) {
6601 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006602 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006603 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6604 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6605 if (ReturnType.isNull()) {
6606 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6607 Builder.AddTextChunk("BOOL");
6608 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6609 }
6610
6611 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6612 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6613 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006614 }
6615 }
6616}
6617
Douglas Gregore8f5a172010-04-07 00:21:17 +00006618void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6619 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006620 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006621 // Determine the return type of the method we're declaring, if
6622 // provided.
6623 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006624 Decl *IDecl = 0;
6625 if (CurContext->isObjCContainer()) {
6626 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6627 IDecl = cast<Decl>(OCD);
6628 }
Douglas Gregorea766182010-10-18 18:21:28 +00006629 // Determine where we should start searching for methods.
6630 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006631 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006632 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006633 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6634 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006635 IsInImplementation = true;
6636 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006637 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006638 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006639 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006640 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006641 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006642 }
6643
6644 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006645 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006646 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006647 }
6648
Douglas Gregorea766182010-10-18 18:21:28 +00006649 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006650 HandleCodeCompleteResults(this, CodeCompleter,
6651 CodeCompletionContext::CCC_Other,
6652 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006653 return;
6654 }
6655
6656 // Find all of the methods that we could declare/implement here.
6657 KnownMethodsMap KnownMethods;
6658 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006659 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006660
Douglas Gregore8f5a172010-04-07 00:21:17 +00006661 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006662 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006663 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6664 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006665 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006666 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006667 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6668 MEnd = KnownMethods.end();
6669 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006670 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006671 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006672
6673 // If the result type was not already provided, add it to the
6674 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006675 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006676 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6677 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006678
6679 Selector Sel = Method->getSelector();
6680
6681 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006682 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006683 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006684
6685 // Add parameters to the pattern.
6686 unsigned I = 0;
6687 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6688 PEnd = Method->param_end();
6689 P != PEnd; (void)++P, ++I) {
6690 // Add the part of the selector name.
6691 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006692 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006693 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006694 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6695 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006696 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006697 } else
6698 break;
6699
6700 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006701 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6702 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006703
6704 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006705 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006706 }
6707
6708 if (Method->isVariadic()) {
6709 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006710 Builder.AddChunk(CodeCompletionString::CK_Comma);
6711 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006712 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006713
Douglas Gregor447107d2010-05-28 00:57:46 +00006714 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006715 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006716 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6717 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6718 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006719 if (!Method->getResultType()->isVoidType()) {
6720 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006721 Builder.AddTextChunk("return");
6722 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6723 Builder.AddPlaceholderChunk("expression");
6724 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006725 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006726 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006727
Douglas Gregor218937c2011-02-01 19:23:04 +00006728 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6729 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006730 }
6731
Douglas Gregor408be5a2010-08-25 01:08:01 +00006732 unsigned Priority = CCP_CodePattern;
6733 if (!M->second.second)
6734 Priority += CCD_InBaseClass;
6735
Douglas Gregor218937c2011-02-01 19:23:04 +00006736 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006737 Method->isInstanceMethod()
6738 ? CXCursor_ObjCInstanceMethodDecl
6739 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006740 }
6741
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006742 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6743 // the properties in this class and its categories.
6744 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006745 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006746 Containers.push_back(SearchDecl);
6747
Douglas Gregore74c25c2011-05-04 23:50:46 +00006748 VisitedSelectorSet KnownSelectors;
6749 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6750 MEnd = KnownMethods.end();
6751 M != MEnd; ++M)
6752 KnownSelectors.insert(M->first);
6753
6754
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006755 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6756 if (!IFace)
6757 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6758 IFace = Category->getClassInterface();
6759
6760 if (IFace) {
6761 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6762 Category = Category->getNextClassCategory())
6763 Containers.push_back(Category);
6764 }
6765
6766 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6767 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6768 PEnd = Containers[I]->prop_end();
6769 P != PEnd; ++P) {
6770 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006771 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006772 }
6773 }
6774 }
6775
Douglas Gregore8f5a172010-04-07 00:21:17 +00006776 Results.ExitScope();
6777
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006778 HandleCodeCompleteResults(this, CodeCompleter,
6779 CodeCompletionContext::CCC_Other,
6780 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006781}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006782
6783void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6784 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006785 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006786 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006787 IdentifierInfo **SelIdents,
6788 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006789 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006790 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006791 if (ExternalSource) {
6792 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6793 I != N; ++I) {
6794 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006795 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006796 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006797
6798 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006799 }
6800 }
6801
6802 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006803 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006804 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6805 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006806
6807 if (ReturnTy)
6808 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006809
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006810 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006811 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6812 MEnd = MethodPool.end();
6813 M != MEnd; ++M) {
6814 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6815 &M->second.second;
6816 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006817 MethList = MethList->Next) {
6818 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6819 NumSelIdents))
6820 continue;
6821
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006822 if (AtParameterName) {
6823 // Suggest parameter names we've seen before.
6824 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6825 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6826 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006827 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006828 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006829 Param->getIdentifier()->getName()));
6830 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006831 }
6832 }
6833
6834 continue;
6835 }
6836
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006837 Result R(MethList->Method, 0);
6838 R.StartParameter = NumSelIdents;
6839 R.AllParametersAreInformative = false;
6840 R.DeclaringEntity = true;
6841 Results.MaybeAddResult(R, CurContext);
6842 }
6843 }
6844
6845 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006846 HandleCodeCompleteResults(this, CodeCompleter,
6847 CodeCompletionContext::CCC_Other,
6848 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006849}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006850
Douglas Gregorf29c5232010-08-24 22:20:20 +00006851void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006852 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006853 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006854 Results.EnterNewScope();
6855
6856 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006857 CodeCompletionBuilder Builder(Results.getAllocator());
6858 Builder.AddTypedTextChunk("if");
6859 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6860 Builder.AddPlaceholderChunk("condition");
6861 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006862
6863 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006864 Builder.AddTypedTextChunk("ifdef");
6865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6866 Builder.AddPlaceholderChunk("macro");
6867 Results.AddResult(Builder.TakeString());
6868
Douglas Gregorf44e8542010-08-24 19:08:16 +00006869 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006870 Builder.AddTypedTextChunk("ifndef");
6871 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6872 Builder.AddPlaceholderChunk("macro");
6873 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006874
6875 if (InConditional) {
6876 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006877 Builder.AddTypedTextChunk("elif");
6878 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6879 Builder.AddPlaceholderChunk("condition");
6880 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006881
6882 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006883 Builder.AddTypedTextChunk("else");
6884 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006885
6886 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006887 Builder.AddTypedTextChunk("endif");
6888 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006889 }
6890
6891 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006892 Builder.AddTypedTextChunk("include");
6893 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6894 Builder.AddTextChunk("\"");
6895 Builder.AddPlaceholderChunk("header");
6896 Builder.AddTextChunk("\"");
6897 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006898
6899 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006900 Builder.AddTypedTextChunk("include");
6901 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6902 Builder.AddTextChunk("<");
6903 Builder.AddPlaceholderChunk("header");
6904 Builder.AddTextChunk(">");
6905 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006906
6907 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006908 Builder.AddTypedTextChunk("define");
6909 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6910 Builder.AddPlaceholderChunk("macro");
6911 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006912
6913 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006914 Builder.AddTypedTextChunk("define");
6915 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6916 Builder.AddPlaceholderChunk("macro");
6917 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6918 Builder.AddPlaceholderChunk("args");
6919 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6920 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006921
6922 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006923 Builder.AddTypedTextChunk("undef");
6924 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6925 Builder.AddPlaceholderChunk("macro");
6926 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006927
6928 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006929 Builder.AddTypedTextChunk("line");
6930 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6931 Builder.AddPlaceholderChunk("number");
6932 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006933
6934 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006935 Builder.AddTypedTextChunk("line");
6936 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6937 Builder.AddPlaceholderChunk("number");
6938 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6939 Builder.AddTextChunk("\"");
6940 Builder.AddPlaceholderChunk("filename");
6941 Builder.AddTextChunk("\"");
6942 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006943
6944 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006945 Builder.AddTypedTextChunk("error");
6946 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6947 Builder.AddPlaceholderChunk("message");
6948 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006949
6950 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006951 Builder.AddTypedTextChunk("pragma");
6952 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6953 Builder.AddPlaceholderChunk("arguments");
6954 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006955
6956 if (getLangOptions().ObjC1) {
6957 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006958 Builder.AddTypedTextChunk("import");
6959 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6960 Builder.AddTextChunk("\"");
6961 Builder.AddPlaceholderChunk("header");
6962 Builder.AddTextChunk("\"");
6963 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006964
6965 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006966 Builder.AddTypedTextChunk("import");
6967 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6968 Builder.AddTextChunk("<");
6969 Builder.AddPlaceholderChunk("header");
6970 Builder.AddTextChunk(">");
6971 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006972 }
6973
6974 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006975 Builder.AddTypedTextChunk("include_next");
6976 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6977 Builder.AddTextChunk("\"");
6978 Builder.AddPlaceholderChunk("header");
6979 Builder.AddTextChunk("\"");
6980 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006981
6982 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006983 Builder.AddTypedTextChunk("include_next");
6984 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6985 Builder.AddTextChunk("<");
6986 Builder.AddPlaceholderChunk("header");
6987 Builder.AddTextChunk(">");
6988 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006989
6990 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006991 Builder.AddTypedTextChunk("warning");
6992 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6993 Builder.AddPlaceholderChunk("message");
6994 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006995
6996 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6997 // completions for them. And __include_macros is a Clang-internal extension
6998 // that we don't want to encourage anyone to use.
6999
7000 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7001 Results.ExitScope();
7002
Douglas Gregorf44e8542010-08-24 19:08:16 +00007003 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00007004 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00007005 Results.data(), Results.size());
7006}
7007
7008void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00007009 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00007010 S->getFnParent()? Sema::PCC_RecoveryInFunction
7011 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00007012}
7013
Douglas Gregorf29c5232010-08-24 22:20:20 +00007014void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00007015 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007016 IsDefinition? CodeCompletionContext::CCC_MacroName
7017 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007018 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7019 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00007020 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007021 Results.EnterNewScope();
7022 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7023 MEnd = PP.macro_end();
7024 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00007025 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00007026 M->first->getName()));
7027 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007028 }
7029 Results.ExitScope();
7030 } else if (IsDefinition) {
7031 // FIXME: Can we detect when the user just wrote an include guard above?
7032 }
7033
Douglas Gregor52779fb2010-09-23 23:01:17 +00007034 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007035 Results.data(), Results.size());
7036}
7037
Douglas Gregorf29c5232010-08-24 22:20:20 +00007038void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00007039 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007040 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00007041
7042 if (!CodeCompleter || CodeCompleter->includeMacros())
7043 AddMacroResults(PP, Results);
7044
7045 // defined (<macro>)
7046 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00007047 CodeCompletionBuilder Builder(Results.getAllocator());
7048 Builder.AddTypedTextChunk("defined");
7049 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7050 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7051 Builder.AddPlaceholderChunk("macro");
7052 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7053 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00007054 Results.ExitScope();
7055
7056 HandleCodeCompleteResults(this, CodeCompleter,
7057 CodeCompletionContext::CCC_PreprocessorExpression,
7058 Results.data(), Results.size());
7059}
7060
7061void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7062 IdentifierInfo *Macro,
7063 MacroInfo *MacroInfo,
7064 unsigned Argument) {
7065 // FIXME: In the future, we could provide "overload" results, much like we
7066 // do for function calls.
7067
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00007068 // Now just ignore this. There will be another code-completion callback
7069 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00007070}
7071
Douglas Gregor55817af2010-08-25 17:04:25 +00007072void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00007073 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00007074 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00007075 0, 0);
7076}
7077
Douglas Gregordae68752011-02-01 22:57:45 +00007078void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00007079 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00007080 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00007081 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7082 CodeCompletionDeclConsumer Consumer(Builder,
7083 Context.getTranslationUnitDecl());
7084 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7085 Consumer);
7086 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00007087
7088 if (!CodeCompleter || CodeCompleter->includeMacros())
7089 AddMacroResults(PP, Builder);
7090
7091 Results.clear();
7092 Results.insert(Results.end(),
7093 Builder.data(), Builder.data() + Builder.size());
7094}