blob: 74a4958d9326934910c3fa6a3fd89f9cd846755d [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;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000126
127 CodeCompletionTUInfo &CCTUInfo;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000128
129 /// \brief If non-NULL, a filter function used to remove any code-completion
130 /// results that are not desirable.
131 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000132
133 /// \brief Whether we should allow declarations as
134 /// nested-name-specifiers that would otherwise be filtered out.
135 bool AllowNestedNameSpecifiers;
136
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000137 /// \brief If set, the type that we would prefer our resulting value
138 /// declarations to have.
139 ///
140 /// Closely matching the preferred type gives a boost to a result's
141 /// priority.
142 CanQualType PreferredType;
143
Douglas Gregor86d9a522009-09-21 16:56:56 +0000144 /// \brief A list of shadow maps, which is used to model name hiding at
145 /// different levels of, e.g., the inheritance hierarchy.
146 std::list<ShadowMap> ShadowMaps;
147
Douglas Gregor3cdee122010-08-26 16:36:48 +0000148 /// \brief If we're potentially referring to a C++ member function, the set
149 /// of qualifiers applied to the object type.
150 Qualifiers ObjectTypeQualifiers;
151
152 /// \brief Whether the \p ObjectTypeQualifiers field is active.
153 bool HasObjectTypeQualifiers;
154
Douglas Gregor265f7492010-08-27 15:29:55 +0000155 /// \brief The selector that we prefer.
156 Selector PreferredSelector;
157
Douglas Gregorca45da02010-11-02 20:36:02 +0000158 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000159 CodeCompletionContext CompletionContext;
160
James Dennetta40f7922012-06-14 03:11:41 +0000161 /// \brief If we are in an instance method definition, the \@implementation
Douglas Gregorca45da02010-11-02 20:36:02 +0000162 /// object.
163 ObjCImplementationDecl *ObjCImplementation;
164
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000165 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000166
Douglas Gregor6f942b22010-09-21 16:06:22 +0000167 void MaybeAddConstructorResults(Result R);
168
Douglas Gregor86d9a522009-09-21 16:56:56 +0000169 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000170 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000171 CodeCompletionTUInfo &CCTUInfo,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000172 const CodeCompletionContext &CompletionContext,
173 LookupFilter Filter = 0)
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000174 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
175 Filter(Filter),
Douglas Gregor218937c2011-02-01 19:23:04 +0000176 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000177 CompletionContext(CompletionContext),
178 ObjCImplementation(0)
179 {
180 // If this is an Objective-C instance method definition, dig out the
181 // corresponding implementation.
182 switch (CompletionContext.getKind()) {
183 case CodeCompletionContext::CCC_Expression:
184 case CodeCompletionContext::CCC_ObjCMessageReceiver:
185 case CodeCompletionContext::CCC_ParenthesizedExpression:
186 case CodeCompletionContext::CCC_Statement:
187 case CodeCompletionContext::CCC_Recovery:
188 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
189 if (Method->isInstanceMethod())
190 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
191 ObjCImplementation = Interface->getImplementation();
192 break;
193
194 default:
195 break;
196 }
197 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000198
Douglas Gregord8e8a582010-05-25 21:41:55 +0000199 /// \brief Whether we should include code patterns in the completion
200 /// results.
201 bool includeCodePatterns() const {
202 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000203 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000204 }
205
Douglas Gregor86d9a522009-09-21 16:56:56 +0000206 /// \brief Set the filter used for code-completion results.
207 void setFilter(LookupFilter Filter) {
208 this->Filter = Filter;
209 }
210
Douglas Gregor86d9a522009-09-21 16:56:56 +0000211 Result *data() { return Results.empty()? 0 : &Results.front(); }
212 unsigned size() const { return Results.size(); }
213 bool empty() const { return Results.empty(); }
214
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000215 /// \brief Specify the preferred type.
216 void setPreferredType(QualType T) {
217 PreferredType = SemaRef.Context.getCanonicalType(T);
218 }
219
Douglas Gregor3cdee122010-08-26 16:36:48 +0000220 /// \brief Set the cv-qualifiers on the object type, for us in filtering
221 /// calls to member functions.
222 ///
223 /// When there are qualifiers in this set, they will be used to filter
224 /// out member functions that aren't available (because there will be a
225 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
226 /// match.
227 void setObjectTypeQualifiers(Qualifiers Quals) {
228 ObjectTypeQualifiers = Quals;
229 HasObjectTypeQualifiers = true;
230 }
231
Douglas Gregor265f7492010-08-27 15:29:55 +0000232 /// \brief Set the preferred selector.
233 ///
234 /// When an Objective-C method declaration result is added, and that
235 /// method's selector matches this preferred selector, we give that method
236 /// a slight priority boost.
237 void setPreferredSelector(Selector Sel) {
238 PreferredSelector = Sel;
239 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000240
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000241 /// \brief Retrieve the code-completion context for which results are
242 /// being collected.
243 const CodeCompletionContext &getCompletionContext() const {
244 return CompletionContext;
245 }
246
Douglas Gregor45bcd432010-01-14 03:21:49 +0000247 /// \brief Specify whether nested-name-specifiers are allowed.
248 void allowNestedNameSpecifiers(bool Allow = true) {
249 AllowNestedNameSpecifiers = Allow;
250 }
251
Douglas Gregorb9d77572010-09-21 00:03:25 +0000252 /// \brief Return the semantic analysis object for which we are collecting
253 /// code completion results.
254 Sema &getSema() const { return SemaRef; }
255
Douglas Gregor218937c2011-02-01 19:23:04 +0000256 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000257 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000258
259 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000260
Douglas Gregore495b7f2010-01-14 00:20:49 +0000261 /// \brief Determine whether the given declaration is at all interesting
262 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000263 ///
264 /// \param ND the declaration that we are inspecting.
265 ///
266 /// \param AsNestedNameSpecifier will be set true if this declaration is
267 /// only interesting when it is a nested-name-specifier.
268 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000269
270 /// \brief Check whether the result is hidden by the Hiding declaration.
271 ///
272 /// \returns true if the result is hidden and cannot be found, false if
273 /// the hidden result could still be found. When false, \p R may be
274 /// modified to describe how the result can be found (e.g., via extra
275 /// qualification).
276 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
277 NamedDecl *Hiding);
278
Douglas Gregor86d9a522009-09-21 16:56:56 +0000279 /// \brief Add a new result to this result set (if it isn't already in one
280 /// of the shadow maps), or replace an existing result (for, e.g., a
281 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000282 ///
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000283 /// \param R the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000284 ///
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000285 /// \param CurContext the context in which this result will be named.
Douglas Gregor456c4a12009-09-21 20:12:40 +0000286 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000287
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000288 /// \brief Add a new result to this result set, where we already know
289 /// the hiding declation (if any).
290 ///
291 /// \param R the result to add (if it is unique).
292 ///
293 /// \param CurContext the context in which this result will be named.
294 ///
295 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000296 ///
297 /// \param InBaseClass whether the result was found in a base
298 /// class of the searched context.
299 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
300 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000301
Douglas Gregora4477812010-01-14 16:01:26 +0000302 /// \brief Add a new non-declaration result to this result set.
303 void AddResult(Result R);
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \brief Enter into a new scope.
306 void EnterNewScope();
307
308 /// \brief Exit from the current scope.
309 void ExitScope();
310
Douglas Gregor55385fe2009-11-18 04:19:12 +0000311 /// \brief Ignore this declaration, if it is seen again.
312 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
313
Douglas Gregor86d9a522009-09-21 16:56:56 +0000314 /// \name Name lookup predicates
315 ///
316 /// These predicates can be passed to the name lookup functions to filter the
317 /// results of name lookup. All of the predicates have the same type, so that
318 ///
319 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000320 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000321 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000322 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000323 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000324 bool IsNestedNameSpecifier(NamedDecl *ND) const;
325 bool IsEnum(NamedDecl *ND) const;
326 bool IsClassOrStruct(NamedDecl *ND) const;
327 bool IsUnion(NamedDecl *ND) const;
328 bool IsNamespace(NamedDecl *ND) const;
329 bool IsNamespaceOrAlias(NamedDecl *ND) const;
330 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000331 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000332 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000333 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000334 bool IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000335 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000336 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000337 //@}
338 };
339}
340
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000341class ResultBuilder::ShadowMapEntry::iterator {
342 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
343 unsigned SingleDeclIndex;
344
345public:
346 typedef DeclIndexPair value_type;
347 typedef value_type reference;
348 typedef std::ptrdiff_t difference_type;
349 typedef std::input_iterator_tag iterator_category;
350
351 class pointer {
352 DeclIndexPair Value;
353
354 public:
355 pointer(const DeclIndexPair &Value) : Value(Value) { }
356
357 const DeclIndexPair *operator->() const {
358 return &Value;
359 }
360 };
361
362 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
363
364 iterator(NamedDecl *SingleDecl, unsigned Index)
365 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
366
367 iterator(const DeclIndexPair *Iterator)
368 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
369
370 iterator &operator++() {
371 if (DeclOrIterator.is<NamedDecl *>()) {
372 DeclOrIterator = (NamedDecl *)0;
373 SingleDeclIndex = 0;
374 return *this;
375 }
376
377 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
378 ++I;
379 DeclOrIterator = I;
380 return *this;
381 }
382
Chris Lattner66392d42010-09-04 18:12:20 +0000383 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 iterator tmp(*this);
385 ++(*this);
386 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000387 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000388
389 reference operator*() const {
390 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
391 return reference(ND, SingleDeclIndex);
392
Douglas Gregord490f952009-12-06 21:27:58 +0000393 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000394 }
395
396 pointer operator->() const {
397 return pointer(**this);
398 }
399
400 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000401 return X.DeclOrIterator.getOpaqueValue()
402 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000403 X.SingleDeclIndex == Y.SingleDeclIndex;
404 }
405
406 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000407 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000408 }
409};
410
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000411ResultBuilder::ShadowMapEntry::iterator
412ResultBuilder::ShadowMapEntry::begin() const {
413 if (DeclOrVector.isNull())
414 return iterator();
415
416 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
417 return iterator(ND, SingleDeclIndex);
418
419 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
420}
421
422ResultBuilder::ShadowMapEntry::iterator
423ResultBuilder::ShadowMapEntry::end() const {
424 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
425 return iterator();
426
427 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
428}
429
Douglas Gregor456c4a12009-09-21 20:12:40 +0000430/// \brief Compute the qualification required to get from the current context
431/// (\p CurContext) to the target context (\p TargetContext).
432///
433/// \param Context the AST context in which the qualification will be used.
434///
435/// \param CurContext the context where an entity is being named, which is
436/// typically based on the current scope.
437///
438/// \param TargetContext the context in which the named entity actually
439/// resides.
440///
441/// \returns a nested name specifier that refers into the target context, or
442/// NULL if no qualification is needed.
443static NestedNameSpecifier *
444getRequiredQualification(ASTContext &Context,
445 DeclContext *CurContext,
446 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000447 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000448
449 for (DeclContext *CommonAncestor = TargetContext;
450 CommonAncestor && !CommonAncestor->Encloses(CurContext);
451 CommonAncestor = CommonAncestor->getLookupParent()) {
452 if (CommonAncestor->isTransparentContext() ||
453 CommonAncestor->isFunctionOrMethod())
454 continue;
455
456 TargetParents.push_back(CommonAncestor);
457 }
458
459 NestedNameSpecifier *Result = 0;
460 while (!TargetParents.empty()) {
461 DeclContext *Parent = TargetParents.back();
462 TargetParents.pop_back();
463
Douglas Gregorfb629412010-08-23 21:17:50 +0000464 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
465 if (!Namespace->getIdentifier())
466 continue;
467
Douglas Gregor456c4a12009-09-21 20:12:40 +0000468 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000469 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000470 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
471 Result = NestedNameSpecifier::Create(Context, Result,
472 false,
473 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000474 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000475 return Result;
476}
477
Douglas Gregor45bcd432010-01-14 03:21:49 +0000478bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
479 bool &AsNestedNameSpecifier) const {
480 AsNestedNameSpecifier = false;
481
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 ND = ND->getUnderlyingDecl();
483 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000484
485 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000486 if (!ND->getDeclName())
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
489 // Friend declarations and declarations introduced due to friends are never
490 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000491 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000492 return false;
493
Douglas Gregor76282942009-12-11 17:31:05 +0000494 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000495 if (isa<ClassTemplateSpecializationDecl>(ND) ||
496 isa<ClassTemplatePartialSpecializationDecl>(ND))
497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregor76282942009-12-11 17:31:05 +0000499 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000500 if (isa<UsingDecl>(ND))
501 return false;
502
503 // Some declarations have reserved names that we don't want to ever show.
504 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000505 // __va_list_tag is a freak of nature. Find it and skip it.
506 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000507 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000508
Douglas Gregorf52cede2009-10-09 22:16:47 +0000509 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000510 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000511 //
512 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000513 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000514 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000515 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000516 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
517 (ND->getLocation().isInvalid() ||
518 SemaRef.SourceMgr.isInSystemHeader(
519 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000520 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000521 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000522 }
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000523
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000524 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
525 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
526 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000527 Filter != &ResultBuilder::IsNamespaceOrAlias &&
528 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000529 AsNestedNameSpecifier = true;
530
Douglas Gregor86d9a522009-09-21 16:56:56 +0000531 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000532 if (Filter && !(this->*Filter)(ND)) {
533 // Check whether it is interesting as a nested-name-specifier.
David Blaikie4e4d0842012-03-11 07:00:24 +0000534 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor45bcd432010-01-14 03:21:49 +0000535 IsNestedNameSpecifier(ND) &&
536 (Filter != &ResultBuilder::IsMember ||
537 (isa<CXXRecordDecl>(ND) &&
538 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
539 AsNestedNameSpecifier = true;
540 return true;
541 }
542
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000544 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000545 // ... then it must be interesting!
546 return true;
547}
548
Douglas Gregor6660d842010-01-14 00:41:07 +0000549bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
550 NamedDecl *Hiding) {
551 // In C, there is no way to refer to a hidden name.
552 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
553 // name if we introduce the tag type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000554 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor6660d842010-01-14 00:41:07 +0000555 return true;
556
Sebastian Redl7a126a42010-08-31 00:36:30 +0000557 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000558
559 // There is no way to qualify a name declared in a function or method.
560 if (HiddenCtx->isFunctionOrMethod())
561 return true;
562
Sebastian Redl7a126a42010-08-31 00:36:30 +0000563 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000564 return true;
565
566 // We can refer to the result with the appropriate qualification. Do it.
567 R.Hidden = true;
568 R.QualifierIsInformative = false;
569
570 if (!R.Qualifier)
571 R.Qualifier = getRequiredQualification(SemaRef.Context,
572 CurContext,
573 R.Declaration->getDeclContext());
574 return false;
575}
576
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000577/// \brief A simplified classification of types used to determine whether two
578/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000579SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000580 switch (T->getTypeClass()) {
581 case Type::Builtin:
582 switch (cast<BuiltinType>(T)->getKind()) {
583 case BuiltinType::Void:
584 return STC_Void;
585
586 case BuiltinType::NullPtr:
587 return STC_Pointer;
588
589 case BuiltinType::Overload:
590 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000591 return STC_Other;
592
593 case BuiltinType::ObjCId:
594 case BuiltinType::ObjCClass:
595 case BuiltinType::ObjCSel:
596 return STC_ObjectiveC;
597
598 default:
599 return STC_Arithmetic;
600 }
David Blaikie7530c032012-01-17 06:56:22 +0000601
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000602 case Type::Complex:
603 return STC_Arithmetic;
604
605 case Type::Pointer:
606 return STC_Pointer;
607
608 case Type::BlockPointer:
609 return STC_Block;
610
611 case Type::LValueReference:
612 case Type::RValueReference:
613 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
614
615 case Type::ConstantArray:
616 case Type::IncompleteArray:
617 case Type::VariableArray:
618 case Type::DependentSizedArray:
619 return STC_Array;
620
621 case Type::DependentSizedExtVector:
622 case Type::Vector:
623 case Type::ExtVector:
624 return STC_Arithmetic;
625
626 case Type::FunctionProto:
627 case Type::FunctionNoProto:
628 return STC_Function;
629
630 case Type::Record:
631 return STC_Record;
632
633 case Type::Enum:
634 return STC_Arithmetic;
635
636 case Type::ObjCObject:
637 case Type::ObjCInterface:
638 case Type::ObjCObjectPointer:
639 return STC_ObjectiveC;
640
641 default:
642 return STC_Other;
643 }
644}
645
646/// \brief Get the type that a given expression will have if this declaration
647/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000648QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000649 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
650
651 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
652 return C.getTypeDeclType(Type);
653 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
654 return C.getObjCInterfaceType(Iface);
655
656 QualType T;
657 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000658 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000659 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000660 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000661 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000662 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000663 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
664 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
665 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
666 T = Property->getType();
667 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
668 T = Value->getType();
669 else
670 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000671
672 // Dig through references, function pointers, and block pointers to
673 // get down to the likely type of an expression when the entity is
674 // used.
675 do {
676 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
677 T = Ref->getPointeeType();
678 continue;
679 }
680
681 if (const PointerType *Pointer = T->getAs<PointerType>()) {
682 if (Pointer->getPointeeType()->isFunctionType()) {
683 T = Pointer->getPointeeType();
684 continue;
685 }
686
687 break;
688 }
689
690 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
691 T = Block->getPointeeType();
692 continue;
693 }
694
695 if (const FunctionType *Function = T->getAs<FunctionType>()) {
696 T = Function->getResultType();
697 continue;
698 }
699
700 break;
701 } while (true);
702
703 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000704}
705
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000706void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
707 // If this is an Objective-C method declaration whose selector matches our
708 // preferred selector, give it a priority boost.
709 if (!PreferredSelector.isNull())
710 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
711 if (PreferredSelector == Method->getSelector())
712 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000713
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000714 // If we have a preferred type, adjust the priority for results with exactly-
715 // matching or nearly-matching types.
716 if (!PreferredType.isNull()) {
717 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
718 if (!T.isNull()) {
719 CanQualType TC = SemaRef.Context.getCanonicalType(T);
720 // Check for exactly-matching types (modulo qualifiers).
721 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
722 R.Priority /= CCF_ExactTypeMatch;
723 // Check for nearly-matching types, based on classification of each.
724 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000725 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000726 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
727 R.Priority /= CCF_SimilarTypeMatch;
728 }
729 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000730}
731
Douglas Gregor6f942b22010-09-21 16:06:22 +0000732void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000733 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor6f942b22010-09-21 16:06:22 +0000734 !CompletionContext.wantConstructorResults())
735 return;
736
737 ASTContext &Context = SemaRef.Context;
738 NamedDecl *D = R.Declaration;
739 CXXRecordDecl *Record = 0;
740 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
741 Record = ClassTemplate->getTemplatedDecl();
742 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
743 // Skip specializations and partial specializations.
744 if (isa<ClassTemplateSpecializationDecl>(Record))
745 return;
746 } else {
747 // There are no constructors here.
748 return;
749 }
750
751 Record = Record->getDefinition();
752 if (!Record)
753 return;
754
755
756 QualType RecordTy = Context.getTypeDeclType(Record);
757 DeclarationName ConstructorName
758 = Context.DeclarationNames.getCXXConstructorName(
759 Context.getCanonicalType(RecordTy));
760 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
761 Ctors.first != Ctors.second; ++Ctors.first) {
762 R.Declaration = *Ctors.first;
763 R.CursorKind = getCursorKindForDecl(R.Declaration);
764 Results.push_back(R);
765 }
766}
767
Douglas Gregore495b7f2010-01-14 00:20:49 +0000768void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
769 assert(!ShadowMaps.empty() && "Must enter into a results scope");
770
771 if (R.Kind != Result::RK_Declaration) {
772 // For non-declaration results, just add the result.
773 Results.push_back(R);
774 return;
775 }
776
777 // Look through using declarations.
778 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
779 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
780 return;
781 }
782
783 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
784 unsigned IDNS = CanonDecl->getIdentifierNamespace();
785
Douglas Gregor45bcd432010-01-14 03:21:49 +0000786 bool AsNestedNameSpecifier = false;
787 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000788 return;
789
Douglas Gregor6f942b22010-09-21 16:06:22 +0000790 // C++ constructors are never found by name lookup.
791 if (isa<CXXConstructorDecl>(R.Declaration))
792 return;
793
Douglas Gregor86d9a522009-09-21 16:56:56 +0000794 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000795 ShadowMapEntry::iterator I, IEnd;
796 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
797 if (NamePos != SMap.end()) {
798 I = NamePos->second.begin();
799 IEnd = NamePos->second.end();
800 }
801
802 for (; I != IEnd; ++I) {
803 NamedDecl *ND = I->first;
804 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000805 if (ND->getCanonicalDecl() == CanonDecl) {
806 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000807 Results[Index].Declaration = R.Declaration;
808
Douglas Gregor86d9a522009-09-21 16:56:56 +0000809 // We're done.
810 return;
811 }
812 }
813
814 // This is a new declaration in this scope. However, check whether this
815 // declaration name is hidden by a similarly-named declaration in an outer
816 // scope.
817 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
818 --SMEnd;
819 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000820 ShadowMapEntry::iterator I, IEnd;
821 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
822 if (NamePos != SM->end()) {
823 I = NamePos->second.begin();
824 IEnd = NamePos->second.end();
825 }
826 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000827 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000828 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000829 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
830 Decl::IDNS_ObjCProtocol)))
831 continue;
832
833 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000834 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000835 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000836 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000837 continue;
838
839 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000840 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000842
843 break;
844 }
845 }
846
847 // Make sure that any given declaration only shows up in the result set once.
848 if (!AllDeclsFound.insert(CanonDecl))
849 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000850
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000851 // If the filter is for nested-name-specifiers, then this result starts a
852 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000853 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000854 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000855 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000856 } else
857 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000858
Douglas Gregor0563c262009-09-22 23:15:58 +0000859 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000860 if (R.QualifierIsInformative && !R.Qualifier &&
861 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000862 DeclContext *Ctx = R.Declaration->getDeclContext();
863 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
864 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
865 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
866 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
867 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
868 else
869 R.QualifierIsInformative = false;
870 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000871
Douglas Gregor86d9a522009-09-21 16:56:56 +0000872 // Insert this result into the set of results and into the current shadow
873 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000874 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000875 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000876
877 if (!AsNestedNameSpecifier)
878 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000879}
880
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000881void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000882 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000883 if (R.Kind != Result::RK_Declaration) {
884 // For non-declaration results, just add the result.
885 Results.push_back(R);
886 return;
887 }
888
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000889 // Look through using declarations.
890 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
891 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
892 return;
893 }
894
Douglas Gregor45bcd432010-01-14 03:21:49 +0000895 bool AsNestedNameSpecifier = false;
896 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000897 return;
898
Douglas Gregor6f942b22010-09-21 16:06:22 +0000899 // C++ constructors are never found by name lookup.
900 if (isa<CXXConstructorDecl>(R.Declaration))
901 return;
902
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000903 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
904 return;
Nick Lewycky173a37a2012-04-03 21:44:08 +0000905
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000906 // Make sure that any given declaration only shows up in the result set once.
907 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
908 return;
909
910 // If the filter is for nested-name-specifiers, then this result starts a
911 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000912 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000913 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000914 R.Priority = CCP_NestedNameSpecifier;
915 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000916 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
917 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000918 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000919 R.QualifierIsInformative = true;
920
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000921 // If this result is supposed to have an informative qualifier, add one.
922 if (R.QualifierIsInformative && !R.Qualifier &&
923 !R.StartsNestedNameSpecifier) {
924 DeclContext *Ctx = R.Declaration->getDeclContext();
925 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
926 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
927 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
928 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000929 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000930 else
931 R.QualifierIsInformative = false;
932 }
933
Douglas Gregor12e13132010-05-26 22:00:08 +0000934 // Adjust the priority if this result comes from a base class.
935 if (InBaseClass)
936 R.Priority += CCD_InBaseClass;
937
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000938 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000939
Douglas Gregor3cdee122010-08-26 16:36:48 +0000940 if (HasObjectTypeQualifiers)
941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
942 if (Method->isInstance()) {
943 Qualifiers MethodQuals
944 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
945 if (ObjectTypeQualifiers == MethodQuals)
946 R.Priority += CCD_ObjectQualifierMatch;
947 else if (ObjectTypeQualifiers - MethodQuals) {
948 // The method cannot be invoked, because doing so would drop
949 // qualifiers.
950 return;
951 }
952 }
953
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000954 // Insert this result into the set of results.
955 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000956
957 if (!AsNestedNameSpecifier)
958 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000959}
960
Douglas Gregora4477812010-01-14 16:01:26 +0000961void ResultBuilder::AddResult(Result R) {
962 assert(R.Kind != Result::RK_Declaration &&
963 "Declaration results need more context");
964 Results.push_back(R);
965}
966
Douglas Gregor86d9a522009-09-21 16:56:56 +0000967/// \brief Enter into a new scope.
968void ResultBuilder::EnterNewScope() {
969 ShadowMaps.push_back(ShadowMap());
970}
971
972/// \brief Exit from the current scope.
973void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000974 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
975 EEnd = ShadowMaps.back().end();
976 E != EEnd;
977 ++E)
978 E->second.Destroy();
979
Douglas Gregor86d9a522009-09-21 16:56:56 +0000980 ShadowMaps.pop_back();
981}
982
Douglas Gregor791215b2009-09-21 20:51:25 +0000983/// \brief Determines whether this given declaration will be found by
984/// ordinary name lookup.
985bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000986 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
987
Douglas Gregor791215b2009-09-21 20:51:25 +0000988 unsigned IDNS = Decl::IDNS_Ordinary;
David Blaikie4e4d0842012-03-11 07:00:24 +0000989 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000990 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikie4e4d0842012-03-11 07:00:24 +0000991 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregorca45da02010-11-02 20:36:02 +0000992 if (isa<ObjCIvarDecl>(ND))
993 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000994 }
995
Douglas Gregor791215b2009-09-21 20:51:25 +0000996 return ND->getIdentifierNamespace() & IDNS;
997}
998
Douglas Gregor01dfea02010-01-10 23:08:15 +0000999/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001000/// ordinary name lookup but is not a type name.
1001bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1002 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1003 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1004 return false;
1005
1006 unsigned IDNS = Decl::IDNS_Ordinary;
David Blaikie4e4d0842012-03-11 07:00:24 +00001007 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001008 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikie4e4d0842012-03-11 07:00:24 +00001009 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001010 if (isa<ObjCIvarDecl>(ND))
1011 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001012 }
1013
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001014 return ND->getIdentifierNamespace() & IDNS;
1015}
1016
Douglas Gregorf9578432010-07-28 21:50:18 +00001017bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1018 if (!IsOrdinaryNonTypeName(ND))
1019 return 0;
1020
1021 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1022 if (VD->getType()->isIntegralOrEnumerationType())
1023 return true;
1024
1025 return false;
1026}
1027
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001028/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001029/// ordinary name lookup.
1030bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001031 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1032
Douglas Gregor01dfea02010-01-10 23:08:15 +00001033 unsigned IDNS = Decl::IDNS_Ordinary;
David Blaikie4e4d0842012-03-11 07:00:24 +00001034 if (SemaRef.getLangOpts().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001035 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001036
1037 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001038 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1039 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001040}
1041
Douglas Gregor86d9a522009-09-21 16:56:56 +00001042/// \brief Determines whether the given declaration is suitable as the
1043/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1044bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1045 // Allow us to find class templates, too.
1046 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1047 ND = ClassTemplate->getTemplatedDecl();
1048
1049 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1050}
1051
1052/// \brief Determines whether the given declaration is an enumeration.
1053bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1054 return isa<EnumDecl>(ND);
1055}
1056
1057/// \brief Determines whether the given declaration is a class or struct.
1058bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1059 // Allow us to find class templates, too.
1060 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1061 ND = ClassTemplate->getTemplatedDecl();
Joao Matos6666ed42012-08-31 18:45:21 +00001062
1063 // For purposes of this check, interfaces match too.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001064 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001065 return RD->getTagKind() == TTK_Class ||
Joao Matos6666ed42012-08-31 18:45:21 +00001066 RD->getTagKind() == TTK_Struct ||
1067 RD->getTagKind() == TTK_Interface;
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
David Blaikie4e4d0842012-03-11 07:00:24 +00001138 if (!C.getLangOpts().CPlusPlus)
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001139 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 {
David Blaikie4e4d0842012-03-11 07:00:24 +00001168 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1169 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregorfb629412010-08-23 21:17:50 +00001170 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() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001179 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregorfb629412010-08-23 21:17:50 +00001180}
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
James Dennettde23c7e2012-06-17 05:33:25 +00001186/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001187/// 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
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00001242 CodeCompletionBuilder Builder(Results.getAllocator(),
1243 Results.getCodeCompletionTUInfo());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus) {
1245 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001246 Results.AddResult(Result("bool", CCP_Type +
1247 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001248 Results.AddResult(Result("class", CCP_Type));
1249 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001250
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001251 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001252 Builder.AddTypedTextChunk("typename");
1253 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1254 Builder.AddPlaceholderChunk("qualifier");
1255 Builder.AddTextChunk("::");
1256 Builder.AddPlaceholderChunk("name");
1257 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001258
Douglas Gregor86d9a522009-09-21 16:56:56 +00001259 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001260 Results.AddResult(Result("auto", CCP_Type));
1261 Results.AddResult(Result("char16_t", CCP_Type));
1262 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("decltype");
1265 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1266 Builder.AddPlaceholderChunk("expression");
1267 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1268 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001269 }
1270 }
1271
1272 // GNU extensions
1273 if (LangOpts.GNUMode) {
1274 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001275 // Results.AddResult(Result("_Decimal32"));
1276 // Results.AddResult(Result("_Decimal64"));
1277 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278
Douglas Gregor218937c2011-02-01 19:23:04 +00001279 Builder.AddTypedTextChunk("typeof");
1280 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1281 Builder.AddPlaceholderChunk("expression");
1282 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001283
Douglas Gregor218937c2011-02-01 19:23:04 +00001284 Builder.AddTypedTextChunk("typeof");
1285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1286 Builder.AddPlaceholderChunk("type");
1287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1288 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001289 }
1290}
1291
John McCallf312b1e2010-08-26 23:41:50 +00001292static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001293 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001294 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001295 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001296 // Note: we don't suggest either "auto" or "register", because both
1297 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1298 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001299 Results.AddResult(Result("extern"));
1300 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001301}
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001304 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001305 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001306 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001308 case Sema::PCC_Class:
1309 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001310 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001311 Results.AddResult(Result("explicit"));
1312 Results.AddResult(Result("friend"));
1313 Results.AddResult(Result("mutable"));
1314 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001315 }
1316 // Fall through
1317
John McCallf312b1e2010-08-26 23:41:50 +00001318 case Sema::PCC_ObjCInterface:
1319 case Sema::PCC_ObjCImplementation:
1320 case Sema::PCC_Namespace:
1321 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001322 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001323 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001324 break;
1325
John McCallf312b1e2010-08-26 23:41:50 +00001326 case Sema::PCC_ObjCInstanceVariableList:
1327 case Sema::PCC_Expression:
1328 case Sema::PCC_Statement:
1329 case Sema::PCC_ForInit:
1330 case Sema::PCC_Condition:
1331 case Sema::PCC_RecoveryInFunction:
1332 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001333 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001334 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001335 break;
1336 }
1337}
1338
Douglas Gregorbca403c2010-01-13 23:51:12 +00001339static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1340static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1341static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001342 ResultBuilder &Results,
1343 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001344static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001345 ResultBuilder &Results,
1346 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001347static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001348 ResultBuilder &Results,
1349 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001350static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001351
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001352static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00001353 CodeCompletionBuilder Builder(Results.getAllocator(),
1354 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00001355 Builder.AddTypedTextChunk("typedef");
1356 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1357 Builder.AddPlaceholderChunk("type");
1358 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1359 Builder.AddPlaceholderChunk("name");
1360 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001361}
1362
John McCallf312b1e2010-08-26 23:41:50 +00001363static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001364 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001365 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001366 case Sema::PCC_Namespace:
1367 case Sema::PCC_Class:
1368 case Sema::PCC_ObjCInstanceVariableList:
1369 case Sema::PCC_Template:
1370 case Sema::PCC_MemberTemplate:
1371 case Sema::PCC_Statement:
1372 case Sema::PCC_RecoveryInFunction:
1373 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001374 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001375 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001376 return true;
1377
John McCallf312b1e2010-08-26 23:41:50 +00001378 case Sema::PCC_Expression:
1379 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001380 return LangOpts.CPlusPlus;
1381
1382 case Sema::PCC_ObjCInterface:
1383 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001384 return false;
1385
John McCallf312b1e2010-08-26 23:41:50 +00001386 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001387 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001388 }
David Blaikie7530c032012-01-17 06:56:22 +00001389
1390 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001391}
1392
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001393static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1394 const Preprocessor &PP) {
1395 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregor8ca72082011-10-18 21:20:17 +00001396 Policy.AnonymousTagLocations = false;
1397 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001398 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001399 return Policy;
1400}
1401
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001402/// \brief Retrieve a printing policy suitable for code completion.
1403static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1404 return getCompletionPrintingPolicy(S.Context, S.PP);
1405}
1406
Douglas Gregor8ca72082011-10-18 21:20:17 +00001407/// \brief Retrieve the string representation of the given type as a string
1408/// that has the appropriate lifetime for code completion.
1409///
1410/// This routine provides a fast path where we provide constant strings for
1411/// common type names.
1412static const char *GetCompletionTypeString(QualType T,
1413 ASTContext &Context,
1414 const PrintingPolicy &Policy,
1415 CodeCompletionAllocator &Allocator) {
1416 if (!T.getLocalQualifiers()) {
1417 // Built-in type names are constant strings.
1418 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidis27a00972012-05-05 04:20:28 +00001419 return BT->getNameAsCString(Policy);
Douglas Gregor8ca72082011-10-18 21:20:17 +00001420
1421 // Anonymous tag types are constant strings.
1422 if (const TagType *TagT = dyn_cast<TagType>(T))
1423 if (TagDecl *Tag = TagT->getDecl())
1424 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1425 switch (Tag->getTagKind()) {
1426 case TTK_Struct: return "struct <anonymous>";
Joao Matos6666ed42012-08-31 18:45:21 +00001427 case TTK_Interface: return "__interface <anonymous>";
1428 case TTK_Class: return "class <anonymous>";
Douglas Gregor8ca72082011-10-18 21:20:17 +00001429 case TTK_Union: return "union <anonymous>";
1430 case TTK_Enum: return "enum <anonymous>";
1431 }
1432 }
1433 }
1434
1435 // Slow path: format the type as a string.
1436 std::string Result;
1437 T.getAsStringInternal(Result, Policy);
1438 return Allocator.CopyString(Result);
1439}
1440
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001441/// \brief Add a completion for "this", if we're in a member function.
1442static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1443 QualType ThisTy = S.getCurrentThisType();
1444 if (ThisTy.isNull())
1445 return;
1446
1447 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00001448 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001449 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1450 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1451 S.Context,
1452 Policy,
1453 Allocator));
1454 Builder.AddTypedTextChunk("this");
Joao Matos6666ed42012-08-31 18:45:21 +00001455 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001456}
1457
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001459static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460 Scope *S,
1461 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001462 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001463 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00001464 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor8ca72082011-10-18 21:20:17 +00001465 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001466
John McCall0a2c5e22010-08-25 06:19:51 +00001467 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001468 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001469 case Sema::PCC_Namespace:
David Blaikie4e4d0842012-03-11 07:00:24 +00001470 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001471 if (Results.includeCodePatterns()) {
1472 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001473 Builder.AddTypedTextChunk("namespace");
1474 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1475 Builder.AddPlaceholderChunk("identifier");
1476 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1477 Builder.AddPlaceholderChunk("declarations");
1478 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1479 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1480 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001481 }
1482
Douglas Gregor01dfea02010-01-10 23:08:15 +00001483 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001484 Builder.AddTypedTextChunk("namespace");
1485 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1486 Builder.AddPlaceholderChunk("name");
1487 Builder.AddChunk(CodeCompletionString::CK_Equal);
1488 Builder.AddPlaceholderChunk("namespace");
1489 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001490
1491 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001492 Builder.AddTypedTextChunk("using");
1493 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1494 Builder.AddTextChunk("namespace");
1495 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1496 Builder.AddPlaceholderChunk("identifier");
1497 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001498
1499 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001500 Builder.AddTypedTextChunk("asm");
1501 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1502 Builder.AddPlaceholderChunk("string-literal");
1503 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1504 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001505
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001506 if (Results.includeCodePatterns()) {
1507 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001508 Builder.AddTypedTextChunk("template");
1509 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1510 Builder.AddPlaceholderChunk("declaration");
1511 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001512 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001513 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001514
David Blaikie4e4d0842012-03-11 07:00:24 +00001515 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001516 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001517
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001518 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001519 // Fall through
1520
John McCallf312b1e2010-08-26 23:41:50 +00001521 case Sema::PCC_Class:
David Blaikie4e4d0842012-03-11 07:00:24 +00001522 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001523 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001524 Builder.AddTypedTextChunk("using");
1525 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1526 Builder.AddPlaceholderChunk("qualifier");
1527 Builder.AddTextChunk("::");
1528 Builder.AddPlaceholderChunk("name");
1529 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001530
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001531 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001533 Builder.AddTypedTextChunk("using");
1534 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1535 Builder.AddTextChunk("typename");
1536 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1537 Builder.AddPlaceholderChunk("qualifier");
1538 Builder.AddTextChunk("::");
1539 Builder.AddPlaceholderChunk("name");
1540 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001541 }
1542
John McCallf312b1e2010-08-26 23:41:50 +00001543 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001544 AddTypedefResult(Results);
1545
Douglas Gregor01dfea02010-01-10 23:08:15 +00001546 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001547 Builder.AddTypedTextChunk("public");
Douglas Gregor10ccf122012-04-10 17:56:28 +00001548 if (Results.includeCodePatterns())
1549 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor218937c2011-02-01 19:23:04 +00001550 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001551
1552 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001553 Builder.AddTypedTextChunk("protected");
Douglas Gregor10ccf122012-04-10 17:56:28 +00001554 if (Results.includeCodePatterns())
1555 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor218937c2011-02-01 19:23:04 +00001556 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001557
1558 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001559 Builder.AddTypedTextChunk("private");
Douglas Gregor10ccf122012-04-10 17:56:28 +00001560 if (Results.includeCodePatterns())
1561 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor218937c2011-02-01 19:23:04 +00001562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001563 }
1564 }
1565 // Fall through
1566
John McCallf312b1e2010-08-26 23:41:50 +00001567 case Sema::PCC_Template:
1568 case Sema::PCC_MemberTemplate:
David Blaikie4e4d0842012-03-11 07:00:24 +00001569 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001570 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001571 Builder.AddTypedTextChunk("template");
1572 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1573 Builder.AddPlaceholderChunk("parameters");
1574 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1575 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001576 }
1577
David Blaikie4e4d0842012-03-11 07:00:24 +00001578 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1579 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001580 break;
1581
John McCallf312b1e2010-08-26 23:41:50 +00001582 case Sema::PCC_ObjCInterface:
David Blaikie4e4d0842012-03-11 07:00:24 +00001583 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1584 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1585 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001586 break;
1587
John McCallf312b1e2010-08-26 23:41:50 +00001588 case Sema::PCC_ObjCImplementation:
David Blaikie4e4d0842012-03-11 07:00:24 +00001589 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1590 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1591 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001592 break;
1593
John McCallf312b1e2010-08-26 23:41:50 +00001594 case Sema::PCC_ObjCInstanceVariableList:
David Blaikie4e4d0842012-03-11 07:00:24 +00001595 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001596 break;
1597
John McCallf312b1e2010-08-26 23:41:50 +00001598 case Sema::PCC_RecoveryInFunction:
1599 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001600 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001601
David Blaikie4e4d0842012-03-11 07:00:24 +00001602 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1603 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001604 Builder.AddTypedTextChunk("try");
1605 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1606 Builder.AddPlaceholderChunk("statements");
1607 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1608 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1609 Builder.AddTextChunk("catch");
1610 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1611 Builder.AddPlaceholderChunk("declaration");
1612 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1613 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1614 Builder.AddPlaceholderChunk("statements");
1615 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1616 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1617 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001618 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001619 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001620 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001621
Douglas Gregord8e8a582010-05-25 21:41:55 +00001622 if (Results.includeCodePatterns()) {
1623 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001624 Builder.AddTypedTextChunk("if");
1625 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00001626 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001627 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001628 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddPlaceholderChunk("expression");
1630 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1631 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1632 Builder.AddPlaceholderChunk("statements");
1633 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1634 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1635 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001636
Douglas Gregord8e8a582010-05-25 21:41:55 +00001637 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001638 Builder.AddTypedTextChunk("switch");
1639 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00001640 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001641 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001642 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001643 Builder.AddPlaceholderChunk("expression");
1644 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1645 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1646 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1647 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1648 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001649 }
1650
Douglas Gregor01dfea02010-01-10 23:08:15 +00001651 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001652 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001653 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001654 Builder.AddTypedTextChunk("case");
1655 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1656 Builder.AddPlaceholderChunk("expression");
1657 Builder.AddChunk(CodeCompletionString::CK_Colon);
1658 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001659
1660 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001661 Builder.AddTypedTextChunk("default");
1662 Builder.AddChunk(CodeCompletionString::CK_Colon);
1663 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001664 }
1665
Douglas Gregord8e8a582010-05-25 21:41:55 +00001666 if (Results.includeCodePatterns()) {
1667 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001668 Builder.AddTypedTextChunk("while");
1669 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00001670 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001671 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001672 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001673 Builder.AddPlaceholderChunk("expression");
1674 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1675 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1676 Builder.AddPlaceholderChunk("statements");
1677 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1678 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1679 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001680
1681 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001682 Builder.AddTypedTextChunk("do");
1683 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1684 Builder.AddPlaceholderChunk("statements");
1685 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1686 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1687 Builder.AddTextChunk("while");
1688 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1689 Builder.AddPlaceholderChunk("expression");
1690 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1691 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001692
Douglas Gregord8e8a582010-05-25 21:41:55 +00001693 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("for");
1695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00001696 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001697 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001698 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001699 Builder.AddPlaceholderChunk("init-expression");
1700 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1701 Builder.AddPlaceholderChunk("condition");
1702 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1703 Builder.AddPlaceholderChunk("inc-expression");
1704 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1705 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1706 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1707 Builder.AddPlaceholderChunk("statements");
1708 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1709 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1710 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001711 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001712
1713 if (S->getContinueParent()) {
1714 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001715 Builder.AddTypedTextChunk("continue");
1716 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717 }
1718
1719 if (S->getBreakParent()) {
1720 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001721 Builder.AddTypedTextChunk("break");
1722 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001723 }
1724
1725 // "return expression ;" or "return ;", depending on whether we
1726 // know the function is void or not.
1727 bool isVoid = false;
1728 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1729 isVoid = Function->getResultType()->isVoidType();
1730 else if (ObjCMethodDecl *Method
1731 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1732 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001733 else if (SemaRef.getCurBlock() &&
1734 !SemaRef.getCurBlock()->ReturnType.isNull())
1735 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001736 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001737 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001738 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1739 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001740 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001741 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001742
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001743 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001744 Builder.AddTypedTextChunk("goto");
1745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1746 Builder.AddPlaceholderChunk("label");
1747 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001748
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001749 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001750 Builder.AddTypedTextChunk("using");
1751 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1752 Builder.AddTextChunk("namespace");
1753 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1754 Builder.AddPlaceholderChunk("identifier");
1755 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001756 }
1757
1758 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001759 case Sema::PCC_ForInit:
1760 case Sema::PCC_Condition:
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001762 // Fall through: conditions and statements can have expressions.
1763
Douglas Gregor02688102010-09-14 23:59:36 +00001764 case Sema::PCC_ParenthesizedExpression:
David Blaikie4e4d0842012-03-11 07:00:24 +00001765 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001766 CCC == Sema::PCC_ParenthesizedExpression) {
1767 // (__bridge <type>)<expression>
1768 Builder.AddTypedTextChunk("__bridge");
1769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1770 Builder.AddPlaceholderChunk("type");
1771 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1772 Builder.AddPlaceholderChunk("expression");
1773 Results.AddResult(Result(Builder.TakeString()));
1774
1775 // (__bridge_transfer <Objective-C type>)<expression>
1776 Builder.AddTypedTextChunk("__bridge_transfer");
1777 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1778 Builder.AddPlaceholderChunk("Objective-C type");
1779 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1780 Builder.AddPlaceholderChunk("expression");
1781 Results.AddResult(Result(Builder.TakeString()));
1782
1783 // (__bridge_retained <CF type>)<expression>
1784 Builder.AddTypedTextChunk("__bridge_retained");
1785 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1786 Builder.AddPlaceholderChunk("CF type");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Builder.AddPlaceholderChunk("expression");
1789 Results.AddResult(Result(Builder.TakeString()));
1790 }
1791 // Fall through
1792
John McCallf312b1e2010-08-26 23:41:50 +00001793 case Sema::PCC_Expression: {
David Blaikie4e4d0842012-03-11 07:00:24 +00001794 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795 // 'this', if we're in a non-static member function.
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001796 addThisCompletion(SemaRef, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001797
Douglas Gregor8ca72082011-10-18 21:20:17 +00001798 // true
1799 Builder.AddResultTypeChunk("bool");
1800 Builder.AddTypedTextChunk("true");
1801 Results.AddResult(Result(Builder.TakeString()));
1802
1803 // false
1804 Builder.AddResultTypeChunk("bool");
1805 Builder.AddTypedTextChunk("false");
1806 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001807
David Blaikie4e4d0842012-03-11 07:00:24 +00001808 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorec3310a2011-04-12 02:47:21 +00001809 // dynamic_cast < type-id > ( expression )
1810 Builder.AddTypedTextChunk("dynamic_cast");
1811 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1812 Builder.AddPlaceholderChunk("type");
1813 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1814 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1815 Builder.AddPlaceholderChunk("expression");
1816 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1817 Results.AddResult(Result(Builder.TakeString()));
1818 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001819
1820 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001821 Builder.AddTypedTextChunk("static_cast");
1822 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1823 Builder.AddPlaceholderChunk("type");
1824 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1825 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1826 Builder.AddPlaceholderChunk("expression");
1827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1828 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001829
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001830 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001831 Builder.AddTypedTextChunk("reinterpret_cast");
1832 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1833 Builder.AddPlaceholderChunk("type");
1834 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1836 Builder.AddPlaceholderChunk("expression");
1837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1838 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001839
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001840 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001841 Builder.AddTypedTextChunk("const_cast");
1842 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1843 Builder.AddPlaceholderChunk("type");
1844 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1845 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1846 Builder.AddPlaceholderChunk("expression");
1847 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1848 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001849
David Blaikie4e4d0842012-03-11 07:00:24 +00001850 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorec3310a2011-04-12 02:47:21 +00001851 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001852 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001853 Builder.AddTypedTextChunk("typeid");
1854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1855 Builder.AddPlaceholderChunk("expression-or-type");
1856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1857 Results.AddResult(Result(Builder.TakeString()));
1858 }
1859
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001860 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001861 Builder.AddTypedTextChunk("new");
1862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1863 Builder.AddPlaceholderChunk("type");
1864 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1865 Builder.AddPlaceholderChunk("expressions");
1866 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1867 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001868
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001869 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001870 Builder.AddTypedTextChunk("new");
1871 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1872 Builder.AddPlaceholderChunk("type");
1873 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1874 Builder.AddPlaceholderChunk("size");
1875 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1876 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1877 Builder.AddPlaceholderChunk("expressions");
1878 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1879 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001880
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001881 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001882 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001883 Builder.AddTypedTextChunk("delete");
1884 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1885 Builder.AddPlaceholderChunk("expression");
1886 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001887
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001888 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001889 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001890 Builder.AddTypedTextChunk("delete");
1891 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1892 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1893 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1894 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1895 Builder.AddPlaceholderChunk("expression");
1896 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001897
David Blaikie4e4d0842012-03-11 07:00:24 +00001898 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorec3310a2011-04-12 02:47:21 +00001899 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001900 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001901 Builder.AddTypedTextChunk("throw");
1902 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1903 Builder.AddPlaceholderChunk("expression");
1904 Results.AddResult(Result(Builder.TakeString()));
1905 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001906
Douglas Gregor12e13132010-05-26 22:00:08 +00001907 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001908
David Blaikie4e4d0842012-03-11 07:00:24 +00001909 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregora50216c2011-10-18 16:29:03 +00001910 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001911 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001912 Builder.AddTypedTextChunk("nullptr");
1913 Results.AddResult(Result(Builder.TakeString()));
1914
1915 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001916 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001917 Builder.AddTypedTextChunk("alignof");
1918 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1919 Builder.AddPlaceholderChunk("type");
1920 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1921 Results.AddResult(Result(Builder.TakeString()));
1922
1923 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001924 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001925 Builder.AddTypedTextChunk("noexcept");
1926 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1927 Builder.AddPlaceholderChunk("expression");
1928 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1929 Results.AddResult(Result(Builder.TakeString()));
1930
1931 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001932 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001933 Builder.AddTypedTextChunk("sizeof...");
1934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935 Builder.AddPlaceholderChunk("parameter-pack");
1936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937 Results.AddResult(Result(Builder.TakeString()));
1938 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001939 }
1940
David Blaikie4e4d0842012-03-11 07:00:24 +00001941 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001942 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001943 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1944 // The interface can be NULL.
1945 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001946 if (ID->getSuperClass()) {
1947 std::string SuperType;
1948 SuperType = ID->getSuperClass()->getNameAsString();
1949 if (Method->isInstanceMethod())
1950 SuperType += " *";
1951
1952 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1953 Builder.AddTypedTextChunk("super");
1954 Results.AddResult(Result(Builder.TakeString()));
1955 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001956 }
1957
Douglas Gregorbca403c2010-01-13 23:51:12 +00001958 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001959 }
1960
Jordan Rosef70a8862012-06-30 21:33:57 +00001961 if (SemaRef.getLangOpts().C11) {
1962 // _Alignof
1963 Builder.AddResultTypeChunk("size_t");
1964 if (SemaRef.getASTContext().Idents.get("alignof").hasMacroDefinition())
1965 Builder.AddTypedTextChunk("alignof");
1966 else
1967 Builder.AddTypedTextChunk("_Alignof");
1968 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1969 Builder.AddPlaceholderChunk("type");
1970 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1971 Results.AddResult(Result(Builder.TakeString()));
1972 }
1973
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001974 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001975 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001976 Builder.AddTypedTextChunk("sizeof");
1977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1978 Builder.AddPlaceholderChunk("expression-or-type");
1979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1980 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001981 break;
1982 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001983
John McCallf312b1e2010-08-26 23:41:50 +00001984 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001985 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001986 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001987 }
1988
David Blaikie4e4d0842012-03-11 07:00:24 +00001989 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
1990 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001991
David Blaikie4e4d0842012-03-11 07:00:24 +00001992 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001993 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001994}
1995
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001996/// \brief If the given declaration has an associated type, add it as a result
1997/// type chunk.
1998static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001999 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002000 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002001 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002002 if (!ND)
2003 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00002004
2005 // Skip constructors and conversion functions, which have their return types
2006 // built into their names.
2007 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2008 return;
2009
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002010 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00002011 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002012 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
2013 T = Function->getResultType();
2014 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
2015 T = Method->getResultType();
2016 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
2017 T = FunTmpl->getTemplatedDecl()->getResultType();
2018 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2019 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2020 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2021 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00002022 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002023 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002024 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002025 T = Property->getType();
2026
2027 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2028 return;
2029
Douglas Gregor8987b232011-09-27 23:30:47 +00002030 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002031 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002032}
2033
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002034static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00002035 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002036 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2037 if (Sentinel->getSentinel() == 0) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002038 if (Context.getLangOpts().ObjC1 &&
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002039 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00002040 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002041 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00002042 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002043 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002044 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002045 }
2046}
2047
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002048static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2049 std::string Result;
2050 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002051 Result += "in ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002052 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002053 Result += "inout ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002054 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002055 Result += "out ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002056 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002057 Result += "bycopy ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002058 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002059 Result += "byref ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002060 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002061 Result += "oneway ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002062 return Result;
2063}
2064
Douglas Gregor83482d12010-08-24 16:15:59 +00002065static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002066 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002067 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002068 bool SuppressName = false,
2069 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002070 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2071 if (Param->getType()->isDependentType() ||
2072 !Param->getType()->isBlockPointerType()) {
2073 // The argument for a dependent or non-block parameter is a placeholder
2074 // containing that parameter's type.
2075 std::string Result;
2076
Douglas Gregoraba48082010-08-29 19:47:46 +00002077 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002078 Result = Param->getIdentifier()->getName();
2079
John McCallf85e1932011-06-15 23:02:42 +00002080 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002081
2082 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002083 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2084 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002085 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002086 Result += Param->getIdentifier()->getName();
2087 }
2088 return Result;
2089 }
2090
2091 // The argument for a block pointer parameter is a block literal with
2092 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002093 FunctionTypeLoc *Block = 0;
2094 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002095 TypeLoc TL;
2096 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2097 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2098 while (true) {
2099 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002100 if (!SuppressBlock) {
2101 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2102 if (TypeSourceInfo *InnerTSInfo
2103 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2104 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2105 continue;
2106 }
2107 }
2108
2109 // Look through qualified types
2110 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2111 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002112 continue;
2113 }
2114 }
2115
Douglas Gregor83482d12010-08-24 16:15:59 +00002116 // Try to get the function prototype behind the block pointer type,
2117 // then we're done.
2118 if (BlockPointerTypeLoc *BlockPtr
2119 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002120 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002121 Block = dyn_cast<FunctionTypeLoc>(&TL);
2122 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002123 }
2124 break;
2125 }
2126 }
2127
2128 if (!Block) {
2129 // We were unable to find a FunctionProtoTypeLoc with parameter names
2130 // for the block; just use the parameter type as a placeholder.
2131 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002132 if (!ObjCMethodParam && Param->getIdentifier())
2133 Result = Param->getIdentifier()->getName();
2134
John McCallf85e1932011-06-15 23:02:42 +00002135 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002136
2137 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002138 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2139 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002140 if (Param->getIdentifier())
2141 Result += Param->getIdentifier()->getName();
2142 }
2143
2144 return Result;
2145 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002146
Douglas Gregor83482d12010-08-24 16:15:59 +00002147 // We have the function prototype behind the block pointer type, as it was
2148 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002149 std::string Result;
2150 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002151 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002152 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002153
2154 // Format the parameter list.
2155 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002156 if (!BlockProto || Block->getNumArgs() == 0) {
2157 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002158 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002159 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002160 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002161 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002162 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002163 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2164 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002165 Params += ", ";
2166 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2167 /*SuppressName=*/false,
2168 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002169
Douglas Gregor830072c2011-02-15 22:37:09 +00002170 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002171 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002172 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002173 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002174 }
Douglas Gregor38276252010-09-08 22:47:51 +00002175
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002176 if (SuppressBlock) {
2177 // Format as a parameter.
2178 Result = Result + " (^";
2179 if (Param->getIdentifier())
2180 Result += Param->getIdentifier()->getName();
2181 Result += ")";
2182 Result += Params;
2183 } else {
2184 // Format as a block literal argument.
2185 Result = '^' + Result;
2186 Result += Params;
2187
2188 if (Param->getIdentifier())
2189 Result += Param->getIdentifier()->getName();
2190 }
2191
Douglas Gregor83482d12010-08-24 16:15:59 +00002192 return Result;
2193}
2194
Douglas Gregor86d9a522009-09-21 16:56:56 +00002195/// \brief Add function parameter chunks to the given code completion string.
2196static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002197 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002198 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002199 CodeCompletionBuilder &Result,
2200 unsigned Start = 0,
2201 bool InOptional = false) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002202 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002203
Douglas Gregor218937c2011-02-01 19:23:04 +00002204 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002205 ParmVarDecl *Param = Function->getParamDecl(P);
2206
Douglas Gregor218937c2011-02-01 19:23:04 +00002207 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002208 // When we see an optional default argument, put that argument and
2209 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002210 CodeCompletionBuilder Opt(Result.getAllocator(),
2211 Result.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00002212 if (!FirstParameter)
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002213 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor8987b232011-09-27 23:30:47 +00002214 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002215 Result.AddOptionalChunk(Opt.TakeString());
2216 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002217 }
2218
Douglas Gregor218937c2011-02-01 19:23:04 +00002219 if (FirstParameter)
2220 FirstParameter = false;
2221 else
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002222 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor218937c2011-02-01 19:23:04 +00002223
2224 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002225
2226 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002227 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2228 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002229
Douglas Gregore17794f2010-08-31 05:13:43 +00002230 if (Function->isVariadic() && P == N - 1)
2231 PlaceholderStr += ", ...";
2232
Douglas Gregor86d9a522009-09-21 16:56:56 +00002233 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002234 Result.AddPlaceholderChunk(
2235 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002236 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002237
2238 if (const FunctionProtoType *Proto
2239 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002240 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002241 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002242 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002243
Douglas Gregor218937c2011-02-01 19:23:04 +00002244 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002245 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002246}
2247
2248/// \brief Add template parameter chunks to the given code completion string.
2249static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002250 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002251 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002252 CodeCompletionBuilder &Result,
2253 unsigned MaxParameters = 0,
2254 unsigned Start = 0,
2255 bool InDefaultArg = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002256 bool FirstParameter = true;
2257
2258 TemplateParameterList *Params = Template->getTemplateParameters();
2259 TemplateParameterList::iterator PEnd = Params->end();
2260 if (MaxParameters)
2261 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002262 for (TemplateParameterList::iterator P = Params->begin() + Start;
2263 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002264 bool HasDefaultArg = false;
2265 std::string PlaceholderStr;
2266 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2267 if (TTP->wasDeclaredWithTypename())
2268 PlaceholderStr = "typename";
2269 else
2270 PlaceholderStr = "class";
2271
2272 if (TTP->getIdentifier()) {
2273 PlaceholderStr += ' ';
2274 PlaceholderStr += TTP->getIdentifier()->getName();
2275 }
2276
2277 HasDefaultArg = TTP->hasDefaultArgument();
2278 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002279 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002280 if (NTTP->getIdentifier())
2281 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002282 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002283 HasDefaultArg = NTTP->hasDefaultArgument();
2284 } else {
2285 assert(isa<TemplateTemplateParmDecl>(*P));
2286 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2287
2288 // Since putting the template argument list into the placeholder would
2289 // be very, very long, we just use an abbreviation.
2290 PlaceholderStr = "template<...> class";
2291 if (TTP->getIdentifier()) {
2292 PlaceholderStr += ' ';
2293 PlaceholderStr += TTP->getIdentifier()->getName();
2294 }
2295
2296 HasDefaultArg = TTP->hasDefaultArgument();
2297 }
2298
Douglas Gregor218937c2011-02-01 19:23:04 +00002299 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002300 // When we see an optional default argument, put that argument and
2301 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002302 CodeCompletionBuilder Opt(Result.getAllocator(),
2303 Result.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00002304 if (!FirstParameter)
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002305 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor8987b232011-09-27 23:30:47 +00002306 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002307 P - Params->begin(), true);
2308 Result.AddOptionalChunk(Opt.TakeString());
2309 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002310 }
2311
Douglas Gregor218937c2011-02-01 19:23:04 +00002312 InDefaultArg = false;
2313
Douglas Gregor86d9a522009-09-21 16:56:56 +00002314 if (FirstParameter)
2315 FirstParameter = false;
2316 else
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002317 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002318
2319 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002320 Result.AddPlaceholderChunk(
2321 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002322 }
2323}
2324
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002325/// \brief Add a qualifier to the given code-completion string, if the
2326/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002327static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002328AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002329 NestedNameSpecifier *Qualifier,
2330 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002331 ASTContext &Context,
2332 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002333 if (!Qualifier)
2334 return;
2335
2336 std::string PrintedNNS;
2337 {
2338 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002339 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002340 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002341 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002342 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002343 else
Douglas Gregordae68752011-02-01 22:57:45 +00002344 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002345}
2346
Douglas Gregor218937c2011-02-01 19:23:04 +00002347static void
2348AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2349 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002350 const FunctionProtoType *Proto
2351 = Function->getType()->getAs<FunctionProtoType>();
2352 if (!Proto || !Proto->getTypeQuals())
2353 return;
2354
Douglas Gregora63f6de2011-02-01 21:15:40 +00002355 // FIXME: Add ref-qualifier!
2356
2357 // Handle single qualifiers without copying
2358 if (Proto->getTypeQuals() == Qualifiers::Const) {
2359 Result.AddInformativeChunk(" const");
2360 return;
2361 }
2362
2363 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2364 Result.AddInformativeChunk(" volatile");
2365 return;
2366 }
2367
2368 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2369 Result.AddInformativeChunk(" restrict");
2370 return;
2371 }
2372
2373 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002374 std::string QualsStr;
David Blaikie4ef832f2012-08-10 00:55:35 +00002375 if (Proto->isConst())
Douglas Gregora61a8792009-12-11 18:44:16 +00002376 QualsStr += " const";
David Blaikie4ef832f2012-08-10 00:55:35 +00002377 if (Proto->isVolatile())
Douglas Gregora61a8792009-12-11 18:44:16 +00002378 QualsStr += " volatile";
David Blaikie4ef832f2012-08-10 00:55:35 +00002379 if (Proto->isRestrict())
Douglas Gregora61a8792009-12-11 18:44:16 +00002380 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002381 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002382}
2383
Douglas Gregor6f942b22010-09-21 16:06:22 +00002384/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002385static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2386 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002387 DeclarationName Name = ND->getDeclName();
2388 if (!Name)
2389 return;
2390
2391 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002392 case DeclarationName::CXXOperatorName: {
2393 const char *OperatorName = 0;
2394 switch (Name.getCXXOverloadedOperator()) {
2395 case OO_None:
2396 case OO_Conditional:
2397 case NUM_OVERLOADED_OPERATORS:
2398 OperatorName = "operator";
2399 break;
2400
2401#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2402 case OO_##Name: OperatorName = "operator" Spelling; break;
2403#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2404#include "clang/Basic/OperatorKinds.def"
2405
2406 case OO_New: OperatorName = "operator new"; break;
2407 case OO_Delete: OperatorName = "operator delete"; break;
2408 case OO_Array_New: OperatorName = "operator new[]"; break;
2409 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2410 case OO_Call: OperatorName = "operator()"; break;
2411 case OO_Subscript: OperatorName = "operator[]"; break;
2412 }
2413 Result.AddTypedTextChunk(OperatorName);
2414 break;
2415 }
2416
Douglas Gregor6f942b22010-09-21 16:06:22 +00002417 case DeclarationName::Identifier:
2418 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002419 case DeclarationName::CXXDestructorName:
2420 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002421 Result.AddTypedTextChunk(
2422 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002423 break;
2424
2425 case DeclarationName::CXXUsingDirective:
2426 case DeclarationName::ObjCZeroArgSelector:
2427 case DeclarationName::ObjCOneArgSelector:
2428 case DeclarationName::ObjCMultiArgSelector:
2429 break;
2430
2431 case DeclarationName::CXXConstructorName: {
2432 CXXRecordDecl *Record = 0;
2433 QualType Ty = Name.getCXXNameType();
2434 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2435 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2436 else if (const InjectedClassNameType *InjectedTy
2437 = Ty->getAs<InjectedClassNameType>())
2438 Record = InjectedTy->getDecl();
2439 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002440 Result.AddTypedTextChunk(
2441 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002442 break;
2443 }
2444
Douglas Gregordae68752011-02-01 22:57:45 +00002445 Result.AddTypedTextChunk(
2446 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002447 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002448 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor8987b232011-09-27 23:30:47 +00002449 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002450 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002451 }
2452 break;
2453 }
2454 }
2455}
2456
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002457CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002458 CodeCompletionAllocator &Allocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002459 CodeCompletionTUInfo &CCTUInfo,
2460 bool IncludeBriefComments) {
2461 return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo,
2462 IncludeBriefComments);
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002463}
2464
Douglas Gregor86d9a522009-09-21 16:56:56 +00002465/// \brief If possible, create a new code completion string for the given
2466/// result.
2467///
2468/// \returns Either a new, heap-allocated code completion string describing
2469/// how to use this result, or NULL to indicate that the string or name of the
2470/// result is all that is needed.
2471CodeCompletionString *
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002472CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2473 Preprocessor &PP,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002474 CodeCompletionAllocator &Allocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002475 CodeCompletionTUInfo &CCTUInfo,
2476 bool IncludeBriefComments) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002477 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002478
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002479 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregor218937c2011-02-01 19:23:04 +00002480 if (Kind == RK_Pattern) {
2481 Pattern->Priority = Priority;
2482 Pattern->Availability = Availability;
Douglas Gregorba103062012-03-27 23:34:16 +00002483
2484 if (Declaration) {
2485 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregorba103062012-03-27 23:34:16 +00002486 Pattern->ParentName = Result.getParentName();
2487 }
2488
Douglas Gregor218937c2011-02-01 19:23:04 +00002489 return Pattern;
2490 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002491
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002492 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002493 Result.AddTypedTextChunk(Keyword);
2494 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002495 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002496
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002497 if (Kind == RK_Macro) {
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002498 MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002499 assert(MI && "Not a macro?");
2500
Douglas Gregordae68752011-02-01 22:57:45 +00002501 Result.AddTypedTextChunk(
2502 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002503
2504 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002505 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002506
2507 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002508 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregore4244702011-07-30 08:17:44 +00002509 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002510
2511 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2512 if (MI->isC99Varargs()) {
2513 --AEnd;
2514
2515 if (A == AEnd) {
2516 Result.AddPlaceholderChunk("...");
2517 }
Douglas Gregore4244702011-07-30 08:17:44 +00002518 }
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002519
Douglas Gregore4244702011-07-30 08:17:44 +00002520 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002521 if (A != MI->arg_begin())
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002522 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002523
2524 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002525 SmallString<32> Arg = (*A)->getName();
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002526 if (MI->isC99Varargs())
2527 Arg += ", ...";
2528 else
2529 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002530 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002531 break;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002532 }
Douglas Gregorc8dc1352012-01-21 00:43:38 +00002533
2534 // Non-variadic macros are simple.
2535 Result.AddPlaceholderChunk(
2536 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregore4244702011-07-30 08:17:44 +00002537 }
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002538 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002540 }
2541
Douglas Gregord8e8a582010-05-25 21:41:55 +00002542 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002543 NamedDecl *ND = Declaration;
Douglas Gregorba103062012-03-27 23:34:16 +00002544 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002545
2546 if (IncludeBriefComments) {
2547 // Add documentation comment, if it exists.
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00002548 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002549 Result.addBriefComment(RC->getBriefText(Ctx));
2550 }
2551 }
2552
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002553 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002554 Result.AddTypedTextChunk(
2555 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002556 Result.AddTextChunk("::");
2557 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002558 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002559
2560 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2561 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2562 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2563 }
2564 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002565
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002566 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002567
Douglas Gregor86d9a522009-09-21 16:56:56 +00002568 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002569 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002570 Ctx, Policy);
2571 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002572 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002573 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002574 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora61a8792009-12-11 18:44:16 +00002575 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002577 }
2578
2579 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002580 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002581 Ctx, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002582 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002583 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002584
Douglas Gregor86d9a522009-09-21 16:56:56 +00002585 // Figure out which template parameters are deduced (or have default
2586 // arguments).
Benjamin Kramer013b3662012-01-30 16:17:39 +00002587 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002588 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002589 unsigned LastDeducibleArgument;
2590 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2591 --LastDeducibleArgument) {
2592 if (!Deduced[LastDeducibleArgument - 1]) {
2593 // C++0x: Figure out if the template argument has a default. If so,
2594 // the user doesn't need to type this argument.
2595 // FIXME: We need to abstract template parameters better!
2596 bool HasDefaultArg = false;
2597 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002598 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002599 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2600 HasDefaultArg = TTP->hasDefaultArgument();
2601 else if (NonTypeTemplateParmDecl *NTTP
2602 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2603 HasDefaultArg = NTTP->hasDefaultArgument();
2604 else {
2605 assert(isa<TemplateTemplateParmDecl>(Param));
2606 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002607 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002608 }
2609
2610 if (!HasDefaultArg)
2611 break;
2612 }
2613 }
2614
2615 if (LastDeducibleArgument) {
2616 // Some of the function template arguments cannot be deduced from a
2617 // function call, so we introduce an explicit template argument list
2618 // containing all of the arguments up to the first deducible argument.
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002619 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002620 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002621 LastDeducibleArgument);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002622 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002623 }
2624
2625 // Add the function parameters
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002626 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002627 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002628 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora61a8792009-12-11 18:44:16 +00002629 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002630 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002631 }
2632
2633 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002634 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002635 Ctx, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002636 Result.AddTypedTextChunk(
2637 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002638 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002639 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002640 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor218937c2011-02-01 19:23:04 +00002641 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002642 }
2643
Douglas Gregor9630eb62009-11-17 16:44:22 +00002644 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002645 Selector Sel = Method->getSelector();
2646 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002647 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002648 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002649 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002650 }
2651
Douglas Gregor813d8342011-02-18 22:29:55 +00002652 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002653 SelName += ':';
2654 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002655 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002656 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002657 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002658
2659 // If there is only one parameter, and we're past it, add an empty
2660 // typed-text chunk since there is nothing to type.
2661 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002662 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002663 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002664 unsigned Idx = 0;
2665 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2666 PEnd = Method->param_end();
2667 P != PEnd; (void)++P, ++Idx) {
2668 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002669 std::string Keyword;
2670 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002671 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002672 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002673 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002674 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002675 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002676 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002677 else
Douglas Gregordae68752011-02-01 22:57:45 +00002678 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002679 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002680
2681 // If we're before the starting parameter, skip the placeholder.
2682 if (Idx < StartParameter)
2683 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002684
2685 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002686
2687 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002688 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002689 else {
John McCallf85e1932011-06-15 23:02:42 +00002690 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002691 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2692 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002693 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002694 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002695 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002696 }
2697
Douglas Gregore17794f2010-08-31 05:13:43 +00002698 if (Method->isVariadic() && (P + 1) == PEnd)
2699 Arg += ", ...";
2700
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002701 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002702 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002703 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002704 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002705 else
Douglas Gregordae68752011-02-01 22:57:45 +00002706 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002707 }
2708
Douglas Gregor2a17af02009-12-23 00:21:46 +00002709 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002710 if (Method->param_size() == 0) {
2711 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002712 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002713 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002714 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002715 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002716 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002717 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002718
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002719 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002720 }
2721
Douglas Gregor218937c2011-02-01 19:23:04 +00002722 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002723 }
2724
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002725 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002726 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002727 Ctx, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002728
Douglas Gregordae68752011-02-01 22:57:45 +00002729 Result.AddTypedTextChunk(
2730 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002731 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002732}
2733
Douglas Gregor86d802e2009-09-23 00:34:09 +00002734CodeCompletionString *
2735CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2736 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002737 Sema &S,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002738 CodeCompletionAllocator &Allocator,
2739 CodeCompletionTUInfo &CCTUInfo) const {
Douglas Gregor8987b232011-09-27 23:30:47 +00002740 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002741
Douglas Gregor218937c2011-02-01 19:23:04 +00002742 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002743 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002744 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002745 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002746 const FunctionProtoType *Proto
2747 = dyn_cast<FunctionProtoType>(getFunctionType());
2748 if (!FDecl && !Proto) {
2749 // Function without a prototype. Just give the return type and a
2750 // highlighted ellipsis.
2751 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002752 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002753 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002754 Result.getAllocator()));
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002755 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2756 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2757 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor218937c2011-02-01 19:23:04 +00002758 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002759 }
2760
2761 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002762 Result.AddTextChunk(
2763 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002764 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002765 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002766 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002767 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002768
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002769 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002770 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2771 for (unsigned I = 0; I != NumParams; ++I) {
2772 if (I)
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002773 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002774
2775 std::string ArgString;
2776 QualType ArgType;
2777
2778 if (FDecl) {
2779 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2780 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2781 } else {
2782 ArgType = Proto->getArgType(I);
2783 }
2784
John McCallf85e1932011-06-15 23:02:42 +00002785 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002786
2787 if (I == CurrentArg)
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002788 Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
2789 Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002790 else
Douglas Gregordae68752011-02-01 22:57:45 +00002791 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002792 }
2793
2794 if (Proto && Proto->isVariadic()) {
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002795 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002796 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002797 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002798 else
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002799 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002800 }
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00002801 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002802
Douglas Gregor218937c2011-02-01 19:23:04 +00002803 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002804}
2805
Chris Lattner5f9e2722011-07-23 10:55:15 +00002806unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002807 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002808 bool PreferredTypeIsPointer) {
2809 unsigned Priority = CCP_Macro;
2810
Douglas Gregorb05496d2010-09-20 21:11:48 +00002811 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2812 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2813 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002814 Priority = CCP_Constant;
2815 if (PreferredTypeIsPointer)
2816 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002817 }
2818 // Treat "YES", "NO", "true", and "false" as constants.
2819 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2820 MacroName.equals("true") || MacroName.equals("false"))
2821 Priority = CCP_Constant;
2822 // Treat "bool" as a type.
2823 else if (MacroName.equals("bool"))
2824 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2825
Douglas Gregor1827e102010-08-16 16:18:59 +00002826
2827 return Priority;
2828}
2829
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002830CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2831 if (!D)
2832 return CXCursor_UnexposedDecl;
2833
2834 switch (D->getKind()) {
2835 case Decl::Enum: return CXCursor_EnumDecl;
2836 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2837 case Decl::Field: return CXCursor_FieldDecl;
2838 case Decl::Function:
2839 return CXCursor_FunctionDecl;
2840 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2841 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002842 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregor375bb142011-12-27 22:43:10 +00002843
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00002844 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002845 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2846 case Decl::ObjCMethod:
2847 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2848 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2849 case Decl::CXXMethod: return CXCursor_CXXMethod;
2850 case Decl::CXXConstructor: return CXCursor_Constructor;
2851 case Decl::CXXDestructor: return CXCursor_Destructor;
2852 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2853 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00002854 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002855 case Decl::ParmVar: return CXCursor_ParmDecl;
2856 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002857 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002858 case Decl::Var: return CXCursor_VarDecl;
2859 case Decl::Namespace: return CXCursor_Namespace;
2860 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2861 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2862 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2863 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2864 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2865 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002866 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002867 case Decl::ClassTemplatePartialSpecialization:
2868 return CXCursor_ClassTemplatePartialSpecialization;
2869 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002870 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002871
2872 case Decl::Using:
2873 case Decl::UnresolvedUsingValue:
2874 case Decl::UnresolvedUsingTypename:
2875 return CXCursor_UsingDeclaration;
2876
Douglas Gregor352697a2011-06-03 23:08:58 +00002877 case Decl::ObjCPropertyImpl:
2878 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2879 case ObjCPropertyImplDecl::Dynamic:
2880 return CXCursor_ObjCDynamicDecl;
2881
2882 case ObjCPropertyImplDecl::Synthesize:
2883 return CXCursor_ObjCSynthesizeDecl;
2884 }
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00002885
2886 case Decl::Import:
2887 return CXCursor_ModuleImportDecl;
Douglas Gregor352697a2011-06-03 23:08:58 +00002888
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002889 default:
2890 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2891 switch (TD->getTagKind()) {
Joao Matos6666ed42012-08-31 18:45:21 +00002892 case TTK_Interface: // fall through
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002893 case TTK_Struct: return CXCursor_StructDecl;
2894 case TTK_Class: return CXCursor_ClassDecl;
2895 case TTK_Union: return CXCursor_UnionDecl;
2896 case TTK_Enum: return CXCursor_EnumDecl;
2897 }
2898 }
2899 }
2900
2901 return CXCursor_UnexposedDecl;
2902}
2903
Douglas Gregor590c7d52010-07-08 20:55:51 +00002904static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2905 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002906 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002907
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002908 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002909
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002910 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2911 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002912 M != MEnd; ++M) {
Alexander Kornienko8a64bb52012-08-29 00:20:03 +00002913 // FIXME: Eventually, we'd want to be able to look back to the macro
2914 // definition that was actually active at the point of code completion (even
2915 // if that macro has since been #undef'd).
2916 if (M->first->hasMacroDefinition())
2917 Results.AddResult(Result(M->first,
Douglas Gregor1827e102010-08-16 16:18:59 +00002918 getMacroUsagePriority(M->first->getName(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002919 PP.getLangOpts(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002920 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002921 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002922
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002923 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002924
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002925}
2926
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002927static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2928 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002929 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002930
2931 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002932
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002933 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2934 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2935 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2936 Results.AddResult(Result("__func__", CCP_Constant));
2937 Results.ExitScope();
2938}
2939
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002940static void HandleCodeCompleteResults(Sema *S,
2941 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002942 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002943 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002944 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002945 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002946 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002947}
2948
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002949static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2950 Sema::ParserCompletionContext PCC) {
2951 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002952 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002953 return CodeCompletionContext::CCC_TopLevel;
2954
John McCallf312b1e2010-08-26 23:41:50 +00002955 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002956 return CodeCompletionContext::CCC_ClassStructUnion;
2957
John McCallf312b1e2010-08-26 23:41:50 +00002958 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002959 return CodeCompletionContext::CCC_ObjCInterface;
2960
John McCallf312b1e2010-08-26 23:41:50 +00002961 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002962 return CodeCompletionContext::CCC_ObjCImplementation;
2963
John McCallf312b1e2010-08-26 23:41:50 +00002964 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002965 return CodeCompletionContext::CCC_ObjCIvarList;
2966
John McCallf312b1e2010-08-26 23:41:50 +00002967 case Sema::PCC_Template:
2968 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002969 if (S.CurContext->isFileContext())
2970 return CodeCompletionContext::CCC_TopLevel;
David Blaikie7530c032012-01-17 06:56:22 +00002971 if (S.CurContext->isRecord())
Douglas Gregor52779fb2010-09-23 23:01:17 +00002972 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie7530c032012-01-17 06:56:22 +00002973 return CodeCompletionContext::CCC_Other;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002974
John McCallf312b1e2010-08-26 23:41:50 +00002975 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002976 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002977
John McCallf312b1e2010-08-26 23:41:50 +00002978 case Sema::PCC_ForInit:
David Blaikie4e4d0842012-03-11 07:00:24 +00002979 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
2980 S.getLangOpts().ObjC1)
Douglas Gregora5450a02010-10-18 22:01:46 +00002981 return CodeCompletionContext::CCC_ParenthesizedExpression;
2982 else
2983 return CodeCompletionContext::CCC_Expression;
2984
2985 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002986 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002987 return CodeCompletionContext::CCC_Expression;
2988
John McCallf312b1e2010-08-26 23:41:50 +00002989 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002990 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002991
John McCallf312b1e2010-08-26 23:41:50 +00002992 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002993 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002994
2995 case Sema::PCC_ParenthesizedExpression:
2996 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002997
2998 case Sema::PCC_LocalDeclarationSpecifiers:
2999 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003000 }
David Blaikie7530c032012-01-17 06:56:22 +00003001
3002 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003003}
3004
Douglas Gregorf6961522010-08-27 21:18:54 +00003005/// \brief If we're in a C++ virtual member function, add completion results
3006/// that invoke the functions we override, since it's common to invoke the
3007/// overridden function as well as adding new functionality.
3008///
3009/// \param S The semantic analysis object for which we are generating results.
3010///
3011/// \param InContext This context in which the nested-name-specifier preceding
3012/// the code-completion point
3013static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3014 ResultBuilder &Results) {
3015 // Look through blocks.
3016 DeclContext *CurContext = S.CurContext;
3017 while (isa<BlockDecl>(CurContext))
3018 CurContext = CurContext->getParent();
3019
3020
3021 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3022 if (!Method || !Method->isVirtual())
3023 return;
3024
3025 // We need to have names for all of the parameters, if we're going to
3026 // generate a forwarding call.
3027 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3028 PEnd = Method->param_end();
3029 P != PEnd;
3030 ++P) {
3031 if (!(*P)->getDeclName())
3032 return;
3033 }
3034
Douglas Gregor8987b232011-09-27 23:30:47 +00003035 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00003036 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3037 MEnd = Method->end_overridden_methods();
3038 M != MEnd; ++M) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003039 CodeCompletionBuilder Builder(Results.getAllocator(),
3040 Results.getCodeCompletionTUInfo());
Douglas Gregorf6961522010-08-27 21:18:54 +00003041 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
3042 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3043 continue;
3044
3045 // If we need a nested-name-specifier, add one now.
3046 if (!InContext) {
3047 NestedNameSpecifier *NNS
3048 = getRequiredQualification(S.Context, CurContext,
3049 Overridden->getDeclContext());
3050 if (NNS) {
3051 std::string Str;
3052 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00003053 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003054 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003055 }
3056 } else if (!InContext->Equals(Overridden->getDeclContext()))
3057 continue;
3058
Douglas Gregordae68752011-02-01 22:57:45 +00003059 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003060 Overridden->getNameAsString()));
3061 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003062 bool FirstParam = true;
3063 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3064 PEnd = Method->param_end();
3065 P != PEnd; ++P) {
3066 if (FirstParam)
3067 FirstParam = false;
3068 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003069 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003070
Douglas Gregordae68752011-02-01 22:57:45 +00003071 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003072 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003073 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3075 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003076 CCP_SuperCompletion,
Douglas Gregorba103062012-03-27 23:34:16 +00003077 CXCursor_CXXMethod,
3078 CXAvailability_Available,
3079 Overridden));
Douglas Gregorf6961522010-08-27 21:18:54 +00003080 Results.Ignore(Overridden);
3081 }
3082}
3083
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003084void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3085 ModuleIdPath Path) {
3086 typedef CodeCompletionResult Result;
3087 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003088 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003089 CodeCompletionContext::CCC_Other);
3090 Results.EnterNewScope();
3091
3092 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003093 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003094 typedef CodeCompletionResult Result;
3095 if (Path.empty()) {
3096 // Enumerate all top-level modules.
3097 llvm::SmallVector<Module *, 8> Modules;
3098 PP.getHeaderSearchInfo().collectAllModules(Modules);
3099 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3100 Builder.AddTypedTextChunk(
3101 Builder.getAllocator().CopyString(Modules[I]->Name));
3102 Results.AddResult(Result(Builder.TakeString(),
3103 CCP_Declaration,
3104 CXCursor_NotImplemented,
3105 Modules[I]->isAvailable()
3106 ? CXAvailability_Available
3107 : CXAvailability_NotAvailable));
3108 }
3109 } else {
3110 // Load the named module.
3111 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3112 Module::AllVisible,
3113 /*IsInclusionDirective=*/false);
3114 // Enumerate submodules.
3115 if (Mod) {
3116 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3117 SubEnd = Mod->submodule_end();
3118 Sub != SubEnd; ++Sub) {
3119
3120 Builder.AddTypedTextChunk(
3121 Builder.getAllocator().CopyString((*Sub)->Name));
3122 Results.AddResult(Result(Builder.TakeString(),
3123 CCP_Declaration,
3124 CXCursor_NotImplemented,
3125 (*Sub)->isAvailable()
3126 ? CXAvailability_Available
3127 : CXAvailability_NotAvailable));
3128 }
3129 }
3130 }
3131 Results.ExitScope();
3132 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3133 Results.data(),Results.size());
3134}
3135
Douglas Gregor01dfea02010-01-10 23:08:15 +00003136void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003137 ParserCompletionContext CompletionContext) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003138 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003139 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003140 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003141 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003142
Douglas Gregor01dfea02010-01-10 23:08:15 +00003143 // Determine how to filter results, e.g., so that the names of
3144 // values (functions, enumerators, function templates, etc.) are
3145 // only allowed where we can have an expression.
3146 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003147 case PCC_Namespace:
3148 case PCC_Class:
3149 case PCC_ObjCInterface:
3150 case PCC_ObjCImplementation:
3151 case PCC_ObjCInstanceVariableList:
3152 case PCC_Template:
3153 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003154 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003155 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003156 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3157 break;
3158
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003159 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003160 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003161 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003162 case PCC_ForInit:
3163 case PCC_Condition:
David Blaikie4e4d0842012-03-11 07:00:24 +00003164 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003165 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3166 else
3167 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003168
David Blaikie4e4d0842012-03-11 07:00:24 +00003169 if (getLangOpts().CPlusPlus)
Douglas Gregorf6961522010-08-27 21:18:54 +00003170 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003171 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003172
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003173 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003174 // Unfiltered
3175 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003176 }
3177
Douglas Gregor3cdee122010-08-26 16:36:48 +00003178 // If we are in a C++ non-static member function, check the qualifiers on
3179 // the member function to filter/prioritize the results list.
3180 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3181 if (CurMethod->isInstance())
3182 Results.setObjectTypeQualifiers(
3183 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3184
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003185 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003186 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3187 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003188
Douglas Gregorbca403c2010-01-13 23:51:12 +00003189 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003190 Results.ExitScope();
3191
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003192 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003193 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003194 case PCC_Expression:
3195 case PCC_Statement:
3196 case PCC_RecoveryInFunction:
3197 if (S->getFnParent())
David Blaikie4e4d0842012-03-11 07:00:24 +00003198 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor72db1082010-08-24 01:11:00 +00003199 break;
3200
3201 case PCC_Namespace:
3202 case PCC_Class:
3203 case PCC_ObjCInterface:
3204 case PCC_ObjCImplementation:
3205 case PCC_ObjCInstanceVariableList:
3206 case PCC_Template:
3207 case PCC_MemberTemplate:
3208 case PCC_ForInit:
3209 case PCC_Condition:
3210 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003211 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003212 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003213 }
3214
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003215 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003216 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003217
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003218 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003219 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003220}
3221
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003222static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3223 ParsedType Receiver,
3224 IdentifierInfo **SelIdents,
3225 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003226 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003227 bool IsSuper,
3228 ResultBuilder &Results);
3229
3230void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3231 bool AllowNonIdentifiers,
3232 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003233 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003234 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003235 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003236 AllowNestedNameSpecifiers
3237 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3238 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003239 Results.EnterNewScope();
3240
3241 // Type qualifiers can come after names.
3242 Results.AddResult(Result("const"));
3243 Results.AddResult(Result("volatile"));
David Blaikie4e4d0842012-03-11 07:00:24 +00003244 if (getLangOpts().C99)
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003245 Results.AddResult(Result("restrict"));
3246
David Blaikie4e4d0842012-03-11 07:00:24 +00003247 if (getLangOpts().CPlusPlus) {
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003248 if (AllowNonIdentifiers) {
3249 Results.AddResult(Result("operator"));
3250 }
3251
3252 // Add nested-name-specifiers.
3253 if (AllowNestedNameSpecifiers) {
3254 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003255 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003256 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3257 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3258 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003259 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003260 }
3261 }
3262 Results.ExitScope();
3263
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003264 // If we're in a context where we might have an expression (rather than a
3265 // declaration), and what we've seen so far is an Objective-C type that could
3266 // be a receiver of a class message, this may be a class message send with
3267 // the initial opening bracket '[' missing. Add appropriate completions.
3268 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3269 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3270 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3271 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3272 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3273 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3274 DS.getTypeQualifiers() == 0 &&
3275 S &&
3276 (S->getFlags() & Scope::DeclScope) != 0 &&
3277 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3278 Scope::FunctionPrototypeScope |
3279 Scope::AtCatchScope)) == 0) {
3280 ParsedType T = DS.getRepAsType();
3281 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003282 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003283 }
3284
Douglas Gregor4497dd42010-08-24 04:59:56 +00003285 // Note that we intentionally suppress macro results here, since we do not
3286 // encourage using macros to produce the names of entities.
3287
Douglas Gregor52779fb2010-09-23 23:01:17 +00003288 HandleCodeCompleteResults(this, CodeCompleter,
3289 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003290 Results.data(), Results.size());
3291}
3292
Douglas Gregorfb629412010-08-23 21:17:50 +00003293struct Sema::CodeCompleteExpressionData {
3294 CodeCompleteExpressionData(QualType PreferredType = QualType())
3295 : PreferredType(PreferredType), IntegralConstantExpression(false),
3296 ObjCCollection(false) { }
3297
3298 QualType PreferredType;
3299 bool IntegralConstantExpression;
3300 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003301 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003302};
3303
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003304/// \brief Perform code-completion in an expression context when we know what
3305/// type we're looking for.
Douglas Gregorfb629412010-08-23 21:17:50 +00003306void Sema::CodeCompleteExpression(Scope *S,
3307 const CodeCompleteExpressionData &Data) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003308 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003309 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003310 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003311 if (Data.ObjCCollection)
3312 Results.setFilter(&ResultBuilder::IsObjCCollection);
3313 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003314 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikie4e4d0842012-03-11 07:00:24 +00003315 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003316 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3317 else
3318 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003319
3320 if (!Data.PreferredType.isNull())
3321 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3322
3323 // Ignore any declarations that we were told that we don't care about.
3324 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3325 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003326
3327 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003328 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3329 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003330
3331 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003332 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003333 Results.ExitScope();
3334
Douglas Gregor590c7d52010-07-08 20:55:51 +00003335 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003336 if (!Data.PreferredType.isNull())
3337 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3338 || Data.PreferredType->isMemberPointerType()
3339 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003340
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003341 if (S->getFnParent() &&
3342 !Data.ObjCCollection &&
3343 !Data.IntegralConstantExpression)
David Blaikie4e4d0842012-03-11 07:00:24 +00003344 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003345
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003346 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003347 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003348 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003349 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3350 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003351 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003352}
3353
Douglas Gregorac5fd842010-09-18 01:28:11 +00003354void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3355 if (E.isInvalid())
3356 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikie4e4d0842012-03-11 07:00:24 +00003357 else if (getLangOpts().ObjC1)
Douglas Gregorac5fd842010-09-18 01:28:11 +00003358 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003359}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003360
Douglas Gregor73449212010-12-09 23:01:55 +00003361/// \brief The set of properties that have already been added, referenced by
3362/// property name.
3363typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3364
Douglas Gregorb92a4082012-06-12 13:44:08 +00003365/// \brief Retrieve the container definition, if any?
3366static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3367 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3368 if (Interface->hasDefinition())
3369 return Interface->getDefinition();
3370
3371 return Interface;
3372 }
3373
3374 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3375 if (Protocol->hasDefinition())
3376 return Protocol->getDefinition();
3377
3378 return Protocol;
3379 }
3380 return Container;
3381}
3382
3383static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003384 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003385 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003386 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003387 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003388 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003389 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003390
Douglas Gregorb92a4082012-06-12 13:44:08 +00003391 // Retrieve the definition.
3392 Container = getContainerDef(Container);
3393
Douglas Gregor95ac6552009-11-18 01:29:26 +00003394 // Add properties in this container.
3395 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3396 PEnd = Container->prop_end();
3397 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003398 ++P) {
3399 if (AddedProperties.insert(P->getIdentifier()))
David Blaikie581deb32012-06-06 20:45:41 +00003400 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor73449212010-12-09 23:01:55 +00003401 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003402
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003403 // Add nullary methods
3404 if (AllowNullaryMethods) {
3405 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003406 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003407 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3408 MEnd = Container->meth_end();
3409 M != MEnd; ++M) {
3410 if (M->getSelector().isUnarySelector())
3411 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3412 if (AddedProperties.insert(Name)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003413 CodeCompletionBuilder Builder(Results.getAllocator(),
3414 Results.getCodeCompletionTUInfo());
David Blaikie581deb32012-06-06 20:45:41 +00003415 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003416 Builder.AddTypedTextChunk(
3417 Results.getAllocator().CopyString(Name->getName()));
3418
David Blaikie581deb32012-06-06 20:45:41 +00003419 Results.MaybeAddResult(Result(Builder.TakeString(), *M,
Douglas Gregorba103062012-03-27 23:34:16 +00003420 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003421 CurContext);
3422 }
3423 }
3424 }
3425
3426
Douglas Gregor95ac6552009-11-18 01:29:26 +00003427 // Add properties in referenced protocols.
3428 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3429 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3430 PEnd = Protocol->protocol_end();
3431 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003432 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3433 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003434 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003435 if (AllowCategories) {
3436 // Look through categories.
3437 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3438 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003439 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3440 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003441 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003442
3443 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003444 for (ObjCInterfaceDecl::all_protocol_iterator
3445 I = IFace->all_referenced_protocol_begin(),
3446 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003447 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3448 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003449
3450 // Look in the superclass.
3451 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003452 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3453 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003454 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003455 } else if (const ObjCCategoryDecl *Category
3456 = dyn_cast<ObjCCategoryDecl>(Container)) {
3457 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003458 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3459 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003460 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003461 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3462 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003463 }
3464}
3465
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003466void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003467 SourceLocation OpLoc,
3468 bool IsArrow) {
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003469 if (!Base || !CodeCompleter)
Douglas Gregor81b747b2009-09-17 21:32:03 +00003470 return;
3471
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003472 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3473 if (ConvertedBase.isInvalid())
3474 return;
3475 Base = ConvertedBase.get();
3476
John McCall0a2c5e22010-08-25 06:19:51 +00003477 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003478
Douglas Gregor81b747b2009-09-17 21:32:03 +00003479 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003480
3481 if (IsArrow) {
3482 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3483 BaseType = Ptr->getPointeeType();
3484 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003485 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003486 else
3487 return;
3488 }
3489
Douglas Gregor3da626b2011-07-07 16:03:39 +00003490 enum CodeCompletionContext::Kind contextKind;
3491
3492 if (IsArrow) {
3493 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3494 }
3495 else {
3496 if (BaseType->isObjCObjectPointerType() ||
3497 BaseType->isObjCObjectOrInterfaceType()) {
3498 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3499 }
3500 else {
3501 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3502 }
3503 }
3504
Douglas Gregor218937c2011-02-01 19:23:04 +00003505 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003506 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003507 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003508 BaseType),
3509 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003510 Results.EnterNewScope();
3511 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003512 // Indicate that we are performing a member access, and the cv-qualifiers
3513 // for the base object type.
3514 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3515
Douglas Gregor95ac6552009-11-18 01:29:26 +00003516 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003517 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003518 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003519 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3520 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003521
David Blaikie4e4d0842012-03-11 07:00:24 +00003522 if (getLangOpts().CPlusPlus) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003523 if (!Results.empty()) {
3524 // The "template" keyword can follow "->" or "." in the grammar.
3525 // However, we only want to suggest the template keyword if something
3526 // is dependent.
3527 bool IsDependent = BaseType->isDependentType();
3528 if (!IsDependent) {
3529 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3530 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3531 IsDependent = Ctx->isDependentContext();
3532 break;
3533 }
3534 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003535
Douglas Gregor95ac6552009-11-18 01:29:26 +00003536 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003537 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003538 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003539 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003540 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3541 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003542 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003543
3544 // Add property results based on our interface.
3545 const ObjCObjectPointerType *ObjCPtr
3546 = BaseType->getAsObjCInterfacePointerType();
3547 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003548 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3549 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003550 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003551
3552 // Add properties from the protocols in a qualified interface.
3553 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3554 E = ObjCPtr->qual_end();
3555 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003556 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3557 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003558 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003559 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003560 // Objective-C instance variable access.
3561 ObjCInterfaceDecl *Class = 0;
3562 if (const ObjCObjectPointerType *ObjCPtr
3563 = BaseType->getAs<ObjCObjectPointerType>())
3564 Class = ObjCPtr->getInterfaceDecl();
3565 else
John McCallc12c5bb2010-05-15 11:32:37 +00003566 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003567
3568 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003569 if (Class) {
3570 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3571 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003572 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3573 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003574 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003575 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003576
3577 // FIXME: How do we cope with isa?
3578
3579 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003580
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003581 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003582 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003583 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003584 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003585}
3586
Douglas Gregor374929f2009-09-18 15:37:17 +00003587void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3588 if (!CodeCompleter)
3589 return;
3590
Douglas Gregor86d9a522009-09-21 16:56:56 +00003591 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003592 enum CodeCompletionContext::Kind ContextKind
3593 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003594 switch ((DeclSpec::TST)TagSpec) {
3595 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003596 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003597 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003598 break;
3599
3600 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003601 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003602 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003603 break;
3604
3605 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003606 case DeclSpec::TST_class:
Joao Matos6666ed42012-08-31 18:45:21 +00003607 case DeclSpec::TST_interface:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003608 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003609 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003610 break;
3611
3612 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003613 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003614 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003615
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003616 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3617 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003618 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003619
3620 // First pass: look for tags.
3621 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003622 LookupVisibleDecls(S, LookupTagName, Consumer,
3623 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003624
Douglas Gregor8071e422010-08-15 06:18:01 +00003625 if (CodeCompleter->includeGlobals()) {
3626 // Second pass: look for nested name specifiers.
3627 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3628 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3629 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003630
Douglas Gregor52779fb2010-09-23 23:01:17 +00003631 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003632 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003633}
3634
Douglas Gregor1a480c42010-08-27 17:35:51 +00003635void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003636 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003637 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003638 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003639 Results.EnterNewScope();
3640 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3641 Results.AddResult("const");
3642 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3643 Results.AddResult("volatile");
David Blaikie4e4d0842012-03-11 07:00:24 +00003644 if (getLangOpts().C99 &&
Douglas Gregor1a480c42010-08-27 17:35:51 +00003645 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3646 Results.AddResult("restrict");
3647 Results.ExitScope();
3648 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003649 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003650 Results.data(), Results.size());
3651}
3652
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003653void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003654 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003655 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003656
John McCall781472f2010-08-25 08:40:02 +00003657 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003658 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3659 if (!type->isEnumeralType()) {
3660 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003661 Data.IntegralConstantExpression = true;
3662 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003663 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003664 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003665
3666 // Code-complete the cases of a switch statement over an enumeration type
3667 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003668 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregorb92a4082012-06-12 13:44:08 +00003669 if (EnumDecl *Def = Enum->getDefinition())
3670 Enum = Def;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003671
3672 // Determine which enumerators we have already seen in the switch statement.
3673 // FIXME: Ideally, we would also be able to look *past* the code-completion
3674 // token, in case we are code-completing in the middle of the switch and not
3675 // at the end. However, we aren't able to do so at the moment.
3676 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003677 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003678 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3679 SC = SC->getNextSwitchCase()) {
3680 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3681 if (!Case)
3682 continue;
3683
3684 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3685 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3686 if (EnumConstantDecl *Enumerator
3687 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3688 // We look into the AST of the case statement to determine which
3689 // enumerator was named. Alternatively, we could compute the value of
3690 // the integral constant expression, then compare it against the
3691 // values of each enumerator. However, value-based approach would not
3692 // work as well with C++ templates where enumerators declared within a
3693 // template are type- and value-dependent.
3694 EnumeratorsSeen.insert(Enumerator);
3695
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003696 // If this is a qualified-id, keep track of the nested-name-specifier
3697 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003698 //
3699 // switch (TagD.getKind()) {
3700 // case TagDecl::TK_enum:
3701 // break;
3702 // case XXX
3703 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003704 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003705 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3706 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003707 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003708 }
3709 }
3710
David Blaikie4e4d0842012-03-11 07:00:24 +00003711 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003712 // If there are no prior enumerators in C++, check whether we have to
3713 // qualify the names of the enumerators that we suggest, because they
3714 // may not be visible in this scope.
Douglas Gregorb223d8c2012-02-01 05:02:47 +00003715 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003716 }
3717
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003718 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003719 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003720 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003721 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003722 Results.EnterNewScope();
3723 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3724 EEnd = Enum->enumerator_end();
3725 E != EEnd; ++E) {
David Blaikie581deb32012-06-06 20:45:41 +00003726 if (EnumeratorsSeen.count(*E))
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003727 continue;
3728
David Blaikie581deb32012-06-06 20:45:41 +00003729 CodeCompletionResult R(*E, Qualifier);
Douglas Gregor5c722c702011-02-18 23:30:37 +00003730 R.Priority = CCP_EnumInCase;
3731 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003732 }
3733 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003734
Douglas Gregor3da626b2011-07-07 16:03:39 +00003735 //We need to make sure we're setting the right context,
3736 //so only say we include macros if the code completer says we do
3737 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3738 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003739 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003740 kind = CodeCompletionContext::CCC_OtherWithMacros;
3741 }
3742
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003743 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003744 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003745 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003746}
3747
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003748namespace {
3749 struct IsBetterOverloadCandidate {
3750 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003751 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003752
3753 public:
John McCall5769d612010-02-08 23:07:23 +00003754 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3755 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003756
3757 bool
3758 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003759 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003760 }
3761 };
3762}
3763
Ahmed Charles13a140c2012-02-25 11:00:22 +00003764static bool anyNullArguments(llvm::ArrayRef<Expr*> Args) {
3765 if (Args.size() && !Args.data())
Douglas Gregord28dcd72010-05-30 06:10:08 +00003766 return true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003767
3768 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregord28dcd72010-05-30 06:10:08 +00003769 if (!Args[I])
3770 return true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003771
Douglas Gregord28dcd72010-05-30 06:10:08 +00003772 return false;
3773}
3774
Richard Trieuf81e5a92011-09-09 02:00:50 +00003775void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003776 llvm::ArrayRef<Expr *> Args) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003777 if (!CodeCompleter)
3778 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003779
3780 // When we're code-completing for a call, we fall back to ordinary
3781 // name code-completion whenever we can't produce specific
3782 // results. We may want to revisit this strategy in the future,
3783 // e.g., by merging the two kinds of results.
3784
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003785 Expr *Fn = (Expr *)FnIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003786
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003787 // Ignore type-dependent call expressions entirely.
Ahmed Charles13a140c2012-02-25 11:00:22 +00003788 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3789 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003790 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003791 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003792 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003793
John McCall3b4294e2009-12-16 12:17:52 +00003794 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003795 SourceLocation Loc = Fn->getExprLoc();
3796 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003797
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003798 // FIXME: What if we're calling something that isn't a function declaration?
3799 // FIXME: What if we're calling a pseudo-destructor?
3800 // FIXME: What if we're calling a member function?
3801
Douglas Gregorc0265402010-01-21 15:46:19 +00003802 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003803 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003804
John McCall3b4294e2009-12-16 12:17:52 +00003805 Expr *NakedFn = Fn->IgnoreParenCasts();
3806 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charles13a140c2012-02-25 11:00:22 +00003807 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
John McCall3b4294e2009-12-16 12:17:52 +00003808 /*PartialOverloading=*/ true);
3809 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3810 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003811 if (FDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003812 if (!getLangOpts().CPlusPlus ||
Douglas Gregord28dcd72010-05-30 06:10:08 +00003813 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003814 Results.push_back(ResultCandidate(FDecl));
3815 else
John McCall86820f52010-01-26 01:37:31 +00003816 // FIXME: access?
Ahmed Charles13a140c2012-02-25 11:00:22 +00003817 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
3818 CandidateSet, false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003819 }
John McCall3b4294e2009-12-16 12:17:52 +00003820 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003821
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003822 QualType ParamType;
3823
Douglas Gregorc0265402010-01-21 15:46:19 +00003824 if (!CandidateSet.empty()) {
3825 // Sort the overload candidate set by placing the best overloads first.
3826 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003827 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003828
Douglas Gregorc0265402010-01-21 15:46:19 +00003829 // Add the remaining viable overload candidates as code-completion reslults.
3830 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3831 CandEnd = CandidateSet.end();
3832 Cand != CandEnd; ++Cand) {
3833 if (Cand->Viable)
3834 Results.push_back(ResultCandidate(Cand->Function));
3835 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003836
3837 // From the viable candidates, try to determine the type of this parameter.
3838 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3839 if (const FunctionType *FType = Results[I].getFunctionType())
3840 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
Ahmed Charles13a140c2012-02-25 11:00:22 +00003841 if (Args.size() < Proto->getNumArgs()) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003842 if (ParamType.isNull())
Ahmed Charles13a140c2012-02-25 11:00:22 +00003843 ParamType = Proto->getArgType(Args.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003844 else if (!Context.hasSameUnqualifiedType(
3845 ParamType.getNonReferenceType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00003846 Proto->getArgType(Args.size()).getNonReferenceType())) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003847 ParamType = QualType();
3848 break;
3849 }
3850 }
3851 }
3852 } else {
3853 // Try to determine the parameter type from the type of the expression
3854 // being called.
3855 QualType FunctionType = Fn->getType();
3856 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3857 FunctionType = Ptr->getPointeeType();
3858 else if (const BlockPointerType *BlockPtr
3859 = FunctionType->getAs<BlockPointerType>())
3860 FunctionType = BlockPtr->getPointeeType();
3861 else if (const MemberPointerType *MemPtr
3862 = FunctionType->getAs<MemberPointerType>())
3863 FunctionType = MemPtr->getPointeeType();
3864
3865 if (const FunctionProtoType *Proto
3866 = FunctionType->getAs<FunctionProtoType>()) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00003867 if (Args.size() < Proto->getNumArgs())
3868 ParamType = Proto->getArgType(Args.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003869 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003870 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003871
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003872 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003873 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003874 else
3875 CodeCompleteExpression(S, ParamType);
3876
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003877 if (!Results.empty())
Ahmed Charles13a140c2012-02-25 11:00:22 +00003878 CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
Douglas Gregoref96eac2009-12-11 19:06:04 +00003879 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003880}
3881
John McCalld226f652010-08-21 09:40:31 +00003882void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3883 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003884 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003885 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003886 return;
3887 }
3888
3889 CodeCompleteExpression(S, VD->getType());
3890}
3891
3892void Sema::CodeCompleteReturn(Scope *S) {
3893 QualType ResultType;
3894 if (isa<BlockDecl>(CurContext)) {
3895 if (BlockScopeInfo *BSI = getCurBlock())
3896 ResultType = BSI->ReturnType;
3897 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3898 ResultType = Function->getResultType();
3899 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3900 ResultType = Method->getResultType();
3901
3902 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003903 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003904 else
3905 CodeCompleteExpression(S, ResultType);
3906}
3907
Douglas Gregord2d8be62011-07-30 08:36:53 +00003908void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregord2d8be62011-07-30 08:36:53 +00003909 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003910 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord2d8be62011-07-30 08:36:53 +00003911 mapCodeCompletionContext(*this, PCC_Statement));
3912 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3913 Results.EnterNewScope();
3914
3915 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3916 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3917 CodeCompleter->includeGlobals());
3918
3919 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3920
3921 // "else" block
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003922 CodeCompletionBuilder Builder(Results.getAllocator(),
3923 Results.getCodeCompletionTUInfo());
Douglas Gregord2d8be62011-07-30 08:36:53 +00003924 Builder.AddTypedTextChunk("else");
Douglas Gregorf11641a2012-02-16 17:49:04 +00003925 if (Results.includeCodePatterns()) {
3926 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3927 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3928 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3929 Builder.AddPlaceholderChunk("statements");
3930 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3931 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3932 }
Douglas Gregord2d8be62011-07-30 08:36:53 +00003933 Results.AddResult(Builder.TakeString());
3934
3935 // "else if" block
3936 Builder.AddTypedTextChunk("else");
3937 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3938 Builder.AddTextChunk("if");
3939 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3940 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00003941 if (getLangOpts().CPlusPlus)
Douglas Gregord2d8be62011-07-30 08:36:53 +00003942 Builder.AddPlaceholderChunk("condition");
3943 else
3944 Builder.AddPlaceholderChunk("expression");
3945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf11641a2012-02-16 17:49:04 +00003946 if (Results.includeCodePatterns()) {
3947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3948 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3949 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3950 Builder.AddPlaceholderChunk("statements");
3951 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3952 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3953 }
Douglas Gregord2d8be62011-07-30 08:36:53 +00003954 Results.AddResult(Builder.TakeString());
3955
3956 Results.ExitScope();
3957
3958 if (S->getFnParent())
David Blaikie4e4d0842012-03-11 07:00:24 +00003959 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregord2d8be62011-07-30 08:36:53 +00003960
3961 if (CodeCompleter->includeMacros())
3962 AddMacroResults(PP, Results);
3963
3964 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3965 Results.data(),Results.size());
3966}
3967
Richard Trieuf81e5a92011-09-09 02:00:50 +00003968void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003969 if (LHS)
3970 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3971 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003972 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003973}
3974
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003975void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003976 bool EnteringContext) {
3977 if (!SS.getScopeRep() || !CodeCompleter)
3978 return;
3979
Douglas Gregor86d9a522009-09-21 16:56:56 +00003980 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3981 if (!Ctx)
3982 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003983
3984 // Try to instantiate any non-dependent declaration contexts before
3985 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003986 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003987 return;
3988
Douglas Gregor218937c2011-02-01 19:23:04 +00003989 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003990 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003991 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003992 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003993
Douglas Gregor86d9a522009-09-21 16:56:56 +00003994 // The "template" keyword can follow "::" in the grammar, but only
3995 // put it into the grammar if the nested-name-specifier is dependent.
3996 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3997 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003998 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003999
4000 // Add calls to overridden virtual functions, if there are any.
4001 //
4002 // FIXME: This isn't wonderful, because we don't know whether we're actually
4003 // in a context that permits expressions. This is a general issue with
4004 // qualified-id completions.
4005 if (!EnteringContext)
4006 MaybeAddOverrideCalls(*this, Ctx, Results);
4007 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004008
Douglas Gregorf6961522010-08-27 21:18:54 +00004009 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4010 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4011
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004012 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00004013 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004014 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00004015}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004016
4017void Sema::CodeCompleteUsing(Scope *S) {
4018 if (!CodeCompleter)
4019 return;
4020
Douglas Gregor218937c2011-02-01 19:23:04 +00004021 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004022 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004023 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4024 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004025 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004026
4027 // If we aren't in class scope, we could see the "namespace" keyword.
4028 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00004029 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004030
4031 // After "using", we can see anything that would start a
4032 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004033 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004034 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4035 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004036 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004037
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004038 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004039 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004040 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004041}
4042
4043void Sema::CodeCompleteUsingDirective(Scope *S) {
4044 if (!CodeCompleter)
4045 return;
4046
Douglas Gregor86d9a522009-09-21 16:56:56 +00004047 // After "using namespace", we expect to see a namespace name or namespace
4048 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004049 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004050 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004051 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004052 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004053 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004054 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004055 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4056 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004057 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004058 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004059 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004060 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004061}
4062
4063void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4064 if (!CodeCompleter)
4065 return;
4066
Douglas Gregor86d9a522009-09-21 16:56:56 +00004067 DeclContext *Ctx = (DeclContext *)S->getEntity();
4068 if (!S->getParent())
4069 Ctx = Context.getTranslationUnitDecl();
4070
Douglas Gregor52779fb2010-09-23 23:01:17 +00004071 bool SuppressedGlobalResults
4072 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4073
Douglas Gregor218937c2011-02-01 19:23:04 +00004074 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004075 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004076 SuppressedGlobalResults
4077 ? CodeCompletionContext::CCC_Namespace
4078 : CodeCompletionContext::CCC_Other,
4079 &ResultBuilder::IsNamespace);
4080
4081 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00004082 // We only want to see those namespaces that have already been defined
4083 // within this scope, because its likely that the user is creating an
4084 // extended namespace declaration. Keep track of the most recent
4085 // definition of each namespace.
4086 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4087 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4088 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4089 NS != NSEnd; ++NS)
David Blaikie581deb32012-06-06 20:45:41 +00004090 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004091
4092 // Add the most recent definition (or extended definition) of each
4093 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004094 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004095 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregorba103062012-03-27 23:34:16 +00004096 NS = OrigToLatest.begin(),
4097 NSEnd = OrigToLatest.end();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004098 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00004099 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00004100 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004101 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004102 }
4103
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004104 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004105 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004106 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004107}
4108
4109void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4110 if (!CodeCompleter)
4111 return;
4112
Douglas Gregor86d9a522009-09-21 16:56:56 +00004113 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004114 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004115 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004116 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004117 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004118 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004119 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4120 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004121 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004122 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004123 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004124}
4125
Douglas Gregored8d3222009-09-18 20:05:18 +00004126void Sema::CodeCompleteOperatorName(Scope *S) {
4127 if (!CodeCompleter)
4128 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004129
John McCall0a2c5e22010-08-25 06:19:51 +00004130 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004131 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004132 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004133 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004134 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004135 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004136
Douglas Gregor86d9a522009-09-21 16:56:56 +00004137 // Add the names of overloadable operators.
4138#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4139 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004140 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004141#include "clang/Basic/OperatorKinds.def"
4142
4143 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004144 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004145 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004146 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4147 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004148
4149 // Add any type specifiers
David Blaikie4e4d0842012-03-11 07:00:24 +00004150 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004151 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004152
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004153 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004154 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004155 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004156}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004157
Douglas Gregor0133f522010-08-28 00:00:50 +00004158void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004159 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004160 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004161 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004162 CXXConstructorDecl *Constructor
4163 = static_cast<CXXConstructorDecl *>(ConstructorD);
4164 if (!Constructor)
4165 return;
4166
Douglas Gregor218937c2011-02-01 19:23:04 +00004167 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004168 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004169 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004170 Results.EnterNewScope();
4171
4172 // Fill in any already-initialized fields or base classes.
4173 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4174 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4175 for (unsigned I = 0; I != NumInitializers; ++I) {
4176 if (Initializers[I]->isBaseInitializer())
4177 InitializedBases.insert(
4178 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4179 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004180 InitializedFields.insert(cast<FieldDecl>(
4181 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004182 }
4183
4184 // Add completions for base classes.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004185 CodeCompletionBuilder Builder(Results.getAllocator(),
4186 Results.getCodeCompletionTUInfo());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004187 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004188 CXXRecordDecl *ClassDecl = Constructor->getParent();
4189 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4190 BaseEnd = ClassDecl->bases_end();
4191 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004192 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4193 SawLastInitializer
4194 = NumInitializers > 0 &&
4195 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4196 Context.hasSameUnqualifiedType(Base->getType(),
4197 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004198 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004199 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004200
Douglas Gregor218937c2011-02-01 19:23:04 +00004201 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004202 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004203 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004204 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4205 Builder.AddPlaceholderChunk("args");
4206 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4207 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004208 SawLastInitializer? CCP_NextInitializer
4209 : CCP_MemberDeclaration));
4210 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004211 }
4212
4213 // Add completions for virtual base classes.
4214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4215 BaseEnd = ClassDecl->vbases_end();
4216 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004217 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4218 SawLastInitializer
4219 = NumInitializers > 0 &&
4220 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4221 Context.hasSameUnqualifiedType(Base->getType(),
4222 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004223 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004224 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004225
Douglas Gregor218937c2011-02-01 19:23:04 +00004226 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004227 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004228 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004229 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4230 Builder.AddPlaceholderChunk("args");
4231 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4232 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004233 SawLastInitializer? CCP_NextInitializer
4234 : CCP_MemberDeclaration));
4235 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004236 }
4237
4238 // Add completions for members.
4239 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4240 FieldEnd = ClassDecl->field_end();
4241 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004242 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4243 SawLastInitializer
4244 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004245 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
David Blaikie581deb32012-06-06 20:45:41 +00004246 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004247 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004248 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004249
4250 if (!Field->getDeclName())
4251 continue;
4252
Douglas Gregordae68752011-02-01 22:57:45 +00004253 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004254 Field->getIdentifier()->getName()));
4255 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4256 Builder.AddPlaceholderChunk("args");
4257 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4258 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004259 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004260 : CCP_MemberDeclaration,
Douglas Gregorba103062012-03-27 23:34:16 +00004261 CXCursor_MemberRef,
4262 CXAvailability_Available,
David Blaikie581deb32012-06-06 20:45:41 +00004263 *Field));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004264 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004265 }
4266 Results.ExitScope();
4267
Douglas Gregor52779fb2010-09-23 23:01:17 +00004268 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004269 Results.data(), Results.size());
4270}
4271
Douglas Gregor81f3bff2012-02-15 15:34:24 +00004272/// \brief Determine whether this scope denotes a namespace.
4273static bool isNamespaceScope(Scope *S) {
4274 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
4275 if (!DC)
4276 return false;
4277
4278 return DC->isFileContext();
4279}
4280
4281void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4282 bool AfterAmpersand) {
4283 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004284 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor81f3bff2012-02-15 15:34:24 +00004285 CodeCompletionContext::CCC_Other);
4286 Results.EnterNewScope();
4287
4288 // Note what has already been captured.
4289 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4290 bool IncludedThis = false;
4291 for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4292 CEnd = Intro.Captures.end();
4293 C != CEnd; ++C) {
4294 if (C->Kind == LCK_This) {
4295 IncludedThis = true;
4296 continue;
4297 }
4298
4299 Known.insert(C->Id);
4300 }
4301
4302 // Look for other capturable variables.
4303 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4304 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4305 D != DEnd; ++D) {
4306 VarDecl *Var = dyn_cast<VarDecl>(*D);
4307 if (!Var ||
4308 !Var->hasLocalStorage() ||
4309 Var->hasAttr<BlocksAttr>())
4310 continue;
4311
4312 if (Known.insert(Var->getIdentifier()))
4313 Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
4314 }
4315 }
4316
4317 // Add 'this', if it would be valid.
4318 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4319 addThisCompletion(*this, Results);
4320
4321 Results.ExitScope();
4322
4323 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4324 Results.data(), Results.size());
4325}
4326
James Dennetta40f7922012-06-14 03:11:41 +00004327/// Macro that optionally prepends an "@" to the string literal passed in via
4328/// Keyword, depending on whether NeedAt is true or false.
4329#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4330
Douglas Gregorbca403c2010-01-13 23:51:12 +00004331static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004332 ResultBuilder &Results,
4333 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004334 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004335 // Since we have an implementation, we can end it.
James Dennetta40f7922012-06-14 03:11:41 +00004336 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004337
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004338 CodeCompletionBuilder Builder(Results.getAllocator(),
4339 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004340 if (LangOpts.ObjC2) {
4341 // @dynamic
James Dennetta40f7922012-06-14 03:11:41 +00004342 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004343 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4344 Builder.AddPlaceholderChunk("property");
4345 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004346
4347 // @synthesize
James Dennetta40f7922012-06-14 03:11:41 +00004348 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004349 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4350 Builder.AddPlaceholderChunk("property");
4351 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004352 }
4353}
4354
Douglas Gregorbca403c2010-01-13 23:51:12 +00004355static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004356 ResultBuilder &Results,
4357 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004358 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004359
4360 // Since we have an interface or protocol, we can end it.
James Dennetta40f7922012-06-14 03:11:41 +00004361 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004362
4363 if (LangOpts.ObjC2) {
4364 // @property
James Dennetta40f7922012-06-14 03:11:41 +00004365 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004366
4367 // @required
James Dennetta40f7922012-06-14 03:11:41 +00004368 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004369
4370 // @optional
James Dennetta40f7922012-06-14 03:11:41 +00004371 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004372 }
4373}
4374
Douglas Gregorbca403c2010-01-13 23:51:12 +00004375static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004376 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004377 CodeCompletionBuilder Builder(Results.getAllocator(),
4378 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004379
4380 // @class name ;
James Dennetta40f7922012-06-14 03:11:41 +00004381 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004382 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4383 Builder.AddPlaceholderChunk("name");
4384 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004385
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004386 if (Results.includeCodePatterns()) {
4387 // @interface name
4388 // FIXME: Could introduce the whole pattern, including superclasses and
4389 // such.
James Dennetta40f7922012-06-14 03:11:41 +00004390 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4392 Builder.AddPlaceholderChunk("class");
4393 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004394
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004395 // @protocol name
James Dennetta40f7922012-06-14 03:11:41 +00004396 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004397 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4398 Builder.AddPlaceholderChunk("protocol");
4399 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004400
4401 // @implementation name
James Dennetta40f7922012-06-14 03:11:41 +00004402 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004403 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4404 Builder.AddPlaceholderChunk("class");
4405 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004406 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004407
4408 // @compatibility_alias name
James Dennetta40f7922012-06-14 03:11:41 +00004409 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004410 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4411 Builder.AddPlaceholderChunk("alias");
4412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4413 Builder.AddPlaceholderChunk("class");
4414 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004415}
4416
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004417void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004418 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004419 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004420 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004421 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004422 if (isa<ObjCImplDecl>(CurContext))
David Blaikie4e4d0842012-03-11 07:00:24 +00004423 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004424 else if (CurContext->isObjCContainer())
David Blaikie4e4d0842012-03-11 07:00:24 +00004425 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004426 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004427 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004428 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004429 HandleCodeCompleteResults(this, CodeCompleter,
4430 CodeCompletionContext::CCC_Other,
4431 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004432}
4433
Douglas Gregorbca403c2010-01-13 23:51:12 +00004434static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004435 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004436 CodeCompletionBuilder Builder(Results.getAllocator(),
4437 Results.getCodeCompletionTUInfo());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004438
4439 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004440 const char *EncodeType = "char[]";
David Blaikie4e4d0842012-03-11 07:00:24 +00004441 if (Results.getSema().getLangOpts().CPlusPlus ||
4442 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004443 EncodeType = "const char[]";
Douglas Gregor8ca72082011-10-18 21:20:17 +00004444 Builder.AddResultTypeChunk(EncodeType);
James Dennetta40f7922012-06-14 03:11:41 +00004445 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004446 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4447 Builder.AddPlaceholderChunk("type-name");
4448 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4449 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004450
4451 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004452 Builder.AddResultTypeChunk("Protocol *");
James Dennetta40f7922012-06-14 03:11:41 +00004453 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004454 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4455 Builder.AddPlaceholderChunk("protocol-name");
4456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4457 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004458
4459 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004460 Builder.AddResultTypeChunk("SEL");
James Dennetta40f7922012-06-14 03:11:41 +00004461 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004462 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4463 Builder.AddPlaceholderChunk("selector");
4464 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4465 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004466
4467 // @"string"
4468 Builder.AddResultTypeChunk("NSString *");
4469 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4470 Builder.AddPlaceholderChunk("string");
4471 Builder.AddTextChunk("\"");
4472 Results.AddResult(Result(Builder.TakeString()));
4473
Douglas Gregor79615892012-07-17 23:24:47 +00004474 // @[objects, ...]
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004475 Builder.AddResultTypeChunk("NSArray *");
James Dennetta40f7922012-06-14 03:11:41 +00004476 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004477 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004478 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4479 Results.AddResult(Result(Builder.TakeString()));
4480
Douglas Gregor79615892012-07-17 23:24:47 +00004481 // @{key : object, ...}
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004482 Builder.AddResultTypeChunk("NSDictionary *");
James Dennetta40f7922012-06-14 03:11:41 +00004483 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004484 Builder.AddPlaceholderChunk("key");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004485 Builder.AddChunk(CodeCompletionString::CK_Colon);
4486 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4487 Builder.AddPlaceholderChunk("object, ...");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004488 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4489 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004490
Douglas Gregor79615892012-07-17 23:24:47 +00004491 // @(expression)
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004492 Builder.AddResultTypeChunk("id");
4493 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004494 Builder.AddPlaceholderChunk("expression");
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004495 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4496 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004497}
4498
Douglas Gregorbca403c2010-01-13 23:51:12 +00004499static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004500 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004501 CodeCompletionBuilder Builder(Results.getAllocator(),
4502 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004503
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004504 if (Results.includeCodePatterns()) {
4505 // @try { statements } @catch ( declaration ) { statements } @finally
4506 // { statements }
James Dennetta40f7922012-06-14 03:11:41 +00004507 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004508 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4509 Builder.AddPlaceholderChunk("statements");
4510 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4511 Builder.AddTextChunk("@catch");
4512 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4513 Builder.AddPlaceholderChunk("parameter");
4514 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4515 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4516 Builder.AddPlaceholderChunk("statements");
4517 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4518 Builder.AddTextChunk("@finally");
4519 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4520 Builder.AddPlaceholderChunk("statements");
4521 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4522 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004523 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004524
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004525 // @throw
James Dennetta40f7922012-06-14 03:11:41 +00004526 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004527 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4528 Builder.AddPlaceholderChunk("expression");
4529 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004530
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004531 if (Results.includeCodePatterns()) {
4532 // @synchronized ( expression ) { statements }
James Dennetta40f7922012-06-14 03:11:41 +00004533 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004534 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4535 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4536 Builder.AddPlaceholderChunk("expression");
4537 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4538 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4539 Builder.AddPlaceholderChunk("statements");
4540 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4541 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004542 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004543}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004544
Douglas Gregorbca403c2010-01-13 23:51:12 +00004545static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004546 ResultBuilder &Results,
4547 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004548 typedef CodeCompletionResult Result;
James Dennetta40f7922012-06-14 03:11:41 +00004549 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4550 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4551 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004552 if (LangOpts.ObjC2)
James Dennetta40f7922012-06-14 03:11:41 +00004553 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004554}
4555
4556void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004557 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004558 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004559 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004560 Results.EnterNewScope();
David Blaikie4e4d0842012-03-11 07:00:24 +00004561 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004562 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004563 HandleCodeCompleteResults(this, CodeCompleter,
4564 CodeCompletionContext::CCC_Other,
4565 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004566}
4567
4568void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004569 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004570 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004571 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004572 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004573 AddObjCStatementResults(Results, false);
4574 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004575 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004576 HandleCodeCompleteResults(this, CodeCompleter,
4577 CodeCompletionContext::CCC_Other,
4578 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004579}
4580
4581void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004582 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004583 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004584 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004585 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004586 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004587 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004588 HandleCodeCompleteResults(this, CodeCompleter,
4589 CodeCompletionContext::CCC_Other,
4590 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004591}
4592
Douglas Gregor988358f2009-11-19 00:14:45 +00004593/// \brief Determine whether the addition of the given flag to an Objective-C
4594/// property's attributes will cause a conflict.
4595static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4596 // Check if we've already added this flag.
4597 if (Attributes & NewFlag)
4598 return true;
4599
4600 Attributes |= NewFlag;
4601
4602 // Check for collisions with "readonly".
4603 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
Jordan Rosed7403a72012-08-20 20:01:13 +00004604 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregor988358f2009-11-19 00:14:45 +00004605 return true;
4606
Jordan Rosed7403a72012-08-20 20:01:13 +00004607 // Check for more than one of { assign, copy, retain, strong, weak }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004608 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004609 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004610 ObjCDeclSpec::DQ_PR_copy |
Jordan Rosed7403a72012-08-20 20:01:13 +00004611 ObjCDeclSpec::DQ_PR_retain |
4612 ObjCDeclSpec::DQ_PR_strong |
4613 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregor988358f2009-11-19 00:14:45 +00004614 if (AssignCopyRetMask &&
4615 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004616 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004617 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004618 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rosed7403a72012-08-20 20:01:13 +00004619 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4620 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregor988358f2009-11-19 00:14:45 +00004621 return true;
4622
4623 return false;
4624}
4625
Douglas Gregora93b1082009-11-18 23:08:07 +00004626void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004627 if (!CodeCompleter)
4628 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004629
Steve Naroffece8e712009-10-08 21:55:05 +00004630 unsigned Attributes = ODS.getPropertyAttributes();
4631
Douglas Gregor218937c2011-02-01 19:23:04 +00004632 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004633 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004634 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004635 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004636 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004637 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004638 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004639 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004640 if (!ObjCPropertyFlagConflicts(Attributes,
4641 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4642 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004643 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004644 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004645 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004646 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004647 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4648 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004649 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004650 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004651 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004652 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004653 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4654 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rosed7403a72012-08-20 20:01:13 +00004655
4656 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall0a7dd782012-08-21 02:47:43 +00004657 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Jordan Rosed7403a72012-08-20 20:01:13 +00004658 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
4659 Results.AddResult(CodeCompletionResult("weak"));
4660
Douglas Gregor988358f2009-11-19 00:14:45 +00004661 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004662 CodeCompletionBuilder Setter(Results.getAllocator(),
4663 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00004664 Setter.AddTypedTextChunk("setter");
4665 Setter.AddTextChunk(" = ");
4666 Setter.AddPlaceholderChunk("method");
4667 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004668 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004669 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004670 CodeCompletionBuilder Getter(Results.getAllocator(),
4671 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00004672 Getter.AddTypedTextChunk("getter");
4673 Getter.AddTextChunk(" = ");
4674 Getter.AddPlaceholderChunk("method");
4675 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004676 }
Steve Naroffece8e712009-10-08 21:55:05 +00004677 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004678 HandleCodeCompleteResults(this, CodeCompleter,
4679 CodeCompletionContext::CCC_Other,
4680 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004681}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004682
James Dennettde23c7e2012-06-17 05:33:25 +00004683/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregor4ad96852009-11-19 07:41:15 +00004684/// via code completion.
4685enum ObjCMethodKind {
Dmitri Gribenko49fdccb2012-06-08 23:13:42 +00004686 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4687 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4688 MK_OneArgSelector ///< One-argument selector.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004689};
4690
Douglas Gregor458433d2010-08-26 15:07:07 +00004691static bool isAcceptableObjCSelector(Selector Sel,
4692 ObjCMethodKind WantKind,
4693 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004694 unsigned NumSelIdents,
4695 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004696 if (NumSelIdents > Sel.getNumArgs())
4697 return false;
4698
4699 switch (WantKind) {
4700 case MK_Any: break;
4701 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4702 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4703 }
4704
Douglas Gregorcf544262010-11-17 21:36:08 +00004705 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4706 return false;
4707
Douglas Gregor458433d2010-08-26 15:07:07 +00004708 for (unsigned I = 0; I != NumSelIdents; ++I)
4709 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4710 return false;
4711
4712 return true;
4713}
4714
Douglas Gregor4ad96852009-11-19 07:41:15 +00004715static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4716 ObjCMethodKind WantKind,
4717 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004718 unsigned NumSelIdents,
4719 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004720 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004721 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004722}
Douglas Gregord36adf52010-09-16 16:06:31 +00004723
4724namespace {
4725 /// \brief A set of selectors, which is used to avoid introducing multiple
4726 /// completions with the same selector into the result set.
4727 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4728}
4729
Douglas Gregor36ecb042009-11-17 23:22:23 +00004730/// \brief Add all of the Objective-C methods in the given Objective-C
4731/// container to the set of results.
4732///
4733/// The container will be a class, protocol, category, or implementation of
4734/// any of the above. This mether will recurse to include methods from
4735/// the superclasses of classes along with their categories, protocols, and
4736/// implementations.
4737///
4738/// \param Container the container in which we'll look to find methods.
4739///
James Dennetta40f7922012-06-14 03:11:41 +00004740/// \param WantInstanceMethods Whether to add instance methods (only); if
4741/// false, this routine will add factory methods (only).
Douglas Gregor36ecb042009-11-17 23:22:23 +00004742///
4743/// \param CurContext the context in which we're performing the lookup that
4744/// finds methods.
4745///
Douglas Gregorcf544262010-11-17 21:36:08 +00004746/// \param AllowSameLength Whether we allow a method to be added to the list
4747/// when it has the same number of parameters as we have selector identifiers.
4748///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004749/// \param Results the structure into which we'll add results.
4750static void AddObjCMethods(ObjCContainerDecl *Container,
4751 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004752 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004753 IdentifierInfo **SelIdents,
4754 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004755 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004756 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004757 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004758 ResultBuilder &Results,
4759 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004760 typedef CodeCompletionResult Result;
Douglas Gregorb92a4082012-06-12 13:44:08 +00004761 Container = getContainerDef(Container);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004762 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4763 MEnd = Container->meth_end();
4764 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00004765 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004766 // Check whether the selector identifiers we've been given are a
4767 // subset of the identifiers for this particular method.
David Blaikie581deb32012-06-06 20:45:41 +00004768 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004769 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004770 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004771
David Blaikie262bc182012-04-30 02:36:29 +00004772 if (!Selectors.insert(M->getSelector()))
Douglas Gregord36adf52010-09-16 16:06:31 +00004773 continue;
4774
David Blaikie581deb32012-06-06 20:45:41 +00004775 Result R = Result(*M, 0);
Douglas Gregord3c68542009-11-19 01:08:35 +00004776 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004777 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004778 if (!InOriginalClass)
4779 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004780 Results.MaybeAddResult(R, CurContext);
4781 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004782 }
4783
Douglas Gregore396c7b2010-09-16 15:34:59 +00004784 // Visit the protocols of protocols.
4785 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004786 if (Protocol->hasDefinition()) {
4787 const ObjCList<ObjCProtocolDecl> &Protocols
4788 = Protocol->getReferencedProtocols();
4789 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4790 E = Protocols.end();
4791 I != E; ++I)
4792 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4793 NumSelIdents, CurContext, Selectors, AllowSameLength,
4794 Results, false);
4795 }
Douglas Gregore396c7b2010-09-16 15:34:59 +00004796 }
4797
Douglas Gregor36ecb042009-11-17 23:22:23 +00004798 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00004799 if (!IFace || !IFace->hasDefinition())
Douglas Gregor36ecb042009-11-17 23:22:23 +00004800 return;
4801
4802 // Add methods in protocols.
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00004803 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
4804 E = IFace->protocol_end();
Douglas Gregor36ecb042009-11-17 23:22:23 +00004805 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004806 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004807 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004808
4809 // Add methods in categories.
4810 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4811 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004812 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004813 NumSelIdents, CurContext, Selectors, AllowSameLength,
4814 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004815
4816 // Add a categories protocol methods.
4817 const ObjCList<ObjCProtocolDecl> &Protocols
4818 = CatDecl->getReferencedProtocols();
4819 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4820 E = Protocols.end();
4821 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004822 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004823 NumSelIdents, CurContext, Selectors, AllowSameLength,
4824 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004825
4826 // Add methods in category implementations.
4827 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004828 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004829 NumSelIdents, CurContext, Selectors, AllowSameLength,
4830 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004831 }
4832
4833 // Add methods in superclass.
4834 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004835 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004836 SelIdents, NumSelIdents, CurContext, Selectors,
4837 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004838
4839 // Add methods in our implementation, if any.
4840 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004841 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004842 NumSelIdents, CurContext, Selectors, AllowSameLength,
4843 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004844}
4845
4846
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004847void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004848 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004849 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004850 if (!Class) {
4851 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004852 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004853 Class = Category->getClassInterface();
4854
4855 if (!Class)
4856 return;
4857 }
4858
4859 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004860 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004861 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004862 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004863 Results.EnterNewScope();
4864
Douglas Gregord36adf52010-09-16 16:06:31 +00004865 VisitedSelectorSet Selectors;
4866 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004867 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004868 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004869 HandleCodeCompleteResults(this, CodeCompleter,
4870 CodeCompletionContext::CCC_Other,
4871 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004872}
4873
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004874void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004875 // Try to find the interface where setters might live.
4876 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004877 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004878 if (!Class) {
4879 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004880 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004881 Class = Category->getClassInterface();
4882
4883 if (!Class)
4884 return;
4885 }
4886
4887 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004888 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004889 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004890 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004891 Results.EnterNewScope();
4892
Douglas Gregord36adf52010-09-16 16:06:31 +00004893 VisitedSelectorSet Selectors;
4894 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004895 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004896
4897 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004898 HandleCodeCompleteResults(this, CodeCompleter,
4899 CodeCompletionContext::CCC_Other,
4900 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004901}
4902
Douglas Gregorafc45782011-02-15 22:19:42 +00004903void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4904 bool IsParameter) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004905 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004906 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004907 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004908 Results.EnterNewScope();
4909
4910 // Add context-sensitive, Objective-C parameter-passing keywords.
4911 bool AddedInOut = false;
4912 if ((DS.getObjCDeclQualifier() &
4913 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4914 Results.AddResult("in");
4915 Results.AddResult("inout");
4916 AddedInOut = true;
4917 }
4918 if ((DS.getObjCDeclQualifier() &
4919 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4920 Results.AddResult("out");
4921 if (!AddedInOut)
4922 Results.AddResult("inout");
4923 }
4924 if ((DS.getObjCDeclQualifier() &
4925 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4926 ObjCDeclSpec::DQ_Oneway)) == 0) {
4927 Results.AddResult("bycopy");
4928 Results.AddResult("byref");
4929 Results.AddResult("oneway");
4930 }
4931
Douglas Gregorafc45782011-02-15 22:19:42 +00004932 // If we're completing the return type of an Objective-C method and the
4933 // identifier IBAction refers to a macro, provide a completion item for
4934 // an action, e.g.,
4935 // IBAction)<#selector#>:(id)sender
4936 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4937 Context.Idents.get("IBAction").hasMacroDefinition()) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004938 CodeCompletionBuilder Builder(Results.getAllocator(),
4939 Results.getCodeCompletionTUInfo(),
4940 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorafc45782011-02-15 22:19:42 +00004941 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004942 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004943 Builder.AddPlaceholderChunk("selector");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004944 Builder.AddChunk(CodeCompletionString::CK_Colon);
4945 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004946 Builder.AddTextChunk("id");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004947 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004948 Builder.AddTextChunk("sender");
4949 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4950 }
4951
Douglas Gregord32b0222010-08-24 01:06:58 +00004952 // Add various builtin type names and specifiers.
4953 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4954 Results.ExitScope();
4955
4956 // Add the various type names
4957 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4958 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4959 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4960 CodeCompleter->includeGlobals());
4961
4962 if (CodeCompleter->includeMacros())
4963 AddMacroResults(PP, Results);
4964
4965 HandleCodeCompleteResults(this, CodeCompleter,
4966 CodeCompletionContext::CCC_Type,
4967 Results.data(), Results.size());
4968}
4969
Douglas Gregor22f56992010-04-06 19:22:33 +00004970/// \brief When we have an expression with type "id", we may assume
4971/// that it has some more-specific class type based on knowledge of
4972/// common uses of Objective-C. This routine returns that class type,
4973/// or NULL if no better result could be determined.
4974static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004975 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004976 if (!Msg)
4977 return 0;
4978
4979 Selector Sel = Msg->getSelector();
4980 if (Sel.isNull())
4981 return 0;
4982
4983 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4984 if (!Id)
4985 return 0;
4986
4987 ObjCMethodDecl *Method = Msg->getMethodDecl();
4988 if (!Method)
4989 return 0;
4990
4991 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004992 ObjCInterfaceDecl *IFace = 0;
4993 switch (Msg->getReceiverKind()) {
4994 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004995 if (const ObjCObjectType *ObjType
4996 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4997 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004998 break;
4999
5000 case ObjCMessageExpr::Instance: {
5001 QualType T = Msg->getInstanceReceiver()->getType();
5002 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5003 IFace = Ptr->getInterfaceDecl();
5004 break;
5005 }
5006
5007 case ObjCMessageExpr::SuperInstance:
5008 case ObjCMessageExpr::SuperClass:
5009 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00005010 }
5011
5012 if (!IFace)
5013 return 0;
5014
5015 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5016 if (Method->isInstanceMethod())
5017 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5018 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00005019 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00005020 .Case("autorelease", IFace)
5021 .Case("copy", IFace)
5022 .Case("copyWithZone", IFace)
5023 .Case("mutableCopy", IFace)
5024 .Case("mutableCopyWithZone", IFace)
5025 .Case("awakeFromCoder", IFace)
5026 .Case("replacementObjectFromCoder", IFace)
5027 .Case("class", IFace)
5028 .Case("classForCoder", IFace)
5029 .Case("superclass", Super)
5030 .Default(0);
5031
5032 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5033 .Case("new", IFace)
5034 .Case("alloc", IFace)
5035 .Case("allocWithZone", IFace)
5036 .Case("class", IFace)
5037 .Case("superclass", Super)
5038 .Default(0);
5039}
5040
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005041// Add a special completion for a message send to "super", which fills in the
5042// most likely case of forwarding all of our arguments to the superclass
5043// function.
5044///
5045/// \param S The semantic analysis object.
5046///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00005047/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005048/// the "super" keyword. Otherwise, we just need to provide the arguments.
5049///
5050/// \param SelIdents The identifiers in the selector that have already been
5051/// provided as arguments for a send to "super".
5052///
5053/// \param NumSelIdents The number of identifiers in \p SelIdents.
5054///
5055/// \param Results The set of results to augment.
5056///
5057/// \returns the Objective-C method declaration that would be invoked by
5058/// this "super" completion. If NULL, no completion was added.
5059static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
5060 IdentifierInfo **SelIdents,
5061 unsigned NumSelIdents,
5062 ResultBuilder &Results) {
5063 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5064 if (!CurMethod)
5065 return 0;
5066
5067 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5068 if (!Class)
5069 return 0;
5070
5071 // Try to find a superclass method with the same selector.
5072 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00005073 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5074 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005075 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5076 CurMethod->isInstanceMethod());
5077
Douglas Gregor78bcd912011-02-16 00:51:18 +00005078 // Check in categories or class extensions.
5079 if (!SuperMethod) {
5080 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5081 Category = Category->getNextClassCategory())
5082 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
5083 CurMethod->isInstanceMethod())))
5084 break;
5085 }
5086 }
5087
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005088 if (!SuperMethod)
5089 return 0;
5090
5091 // Check whether the superclass method has the same signature.
5092 if (CurMethod->param_size() != SuperMethod->param_size() ||
5093 CurMethod->isVariadic() != SuperMethod->isVariadic())
5094 return 0;
5095
5096 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5097 CurPEnd = CurMethod->param_end(),
5098 SuperP = SuperMethod->param_begin();
5099 CurP != CurPEnd; ++CurP, ++SuperP) {
5100 // Make sure the parameter types are compatible.
5101 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5102 (*SuperP)->getType()))
5103 return 0;
5104
5105 // Make sure we have a parameter name to forward!
5106 if (!(*CurP)->getIdentifier())
5107 return 0;
5108 }
5109
5110 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005111 CodeCompletionBuilder Builder(Results.getAllocator(),
5112 Results.getCodeCompletionTUInfo());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005113
5114 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00005115 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5116 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005117
5118 // If we need the "super" keyword, add it (plus some spacing).
5119 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005120 Builder.AddTypedTextChunk("super");
5121 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005122 }
5123
5124 Selector Sel = CurMethod->getSelector();
5125 if (Sel.isUnarySelector()) {
5126 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00005127 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005128 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005129 else
Douglas Gregordae68752011-02-01 22:57:45 +00005130 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005131 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005132 } else {
5133 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5134 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5135 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005136 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005137
5138 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005139 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005140 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005141 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005142 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005143 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005144 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005145 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005146 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005147 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005148 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00005149 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005150 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005151 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005152 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005153 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005154 }
5155 }
5156 }
5157
Douglas Gregorba103062012-03-27 23:34:16 +00005158 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5159 CCP_SuperCompletion));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005160 return SuperMethod;
5161}
5162
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005163void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005164 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005165 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005166 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005167 CodeCompletionContext::CCC_ObjCMessageReceiver,
David Blaikie4e4d0842012-03-11 07:00:24 +00005168 getLangOpts().CPlusPlus0x
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005169 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5170 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005171
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005172 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5173 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00005174 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5175 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005176
5177 // If we are in an Objective-C method inside a class that has a superclass,
5178 // add "super" as an option.
5179 if (ObjCMethodDecl *Method = getCurMethodDecl())
5180 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005181 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005182 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005183
5184 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
5185 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005186
David Blaikie4e4d0842012-03-11 07:00:24 +00005187 if (getLangOpts().CPlusPlus0x)
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005188 addThisCompletion(*this, Results);
5189
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005190 Results.ExitScope();
5191
5192 if (CodeCompleter->includeMacros())
5193 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00005194 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005195 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005196
5197}
5198
Douglas Gregor2725ca82010-04-21 19:57:20 +00005199void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5200 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005201 unsigned NumSelIdents,
5202 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00005203 ObjCInterfaceDecl *CDecl = 0;
5204 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5205 // Figure out which interface we're in.
5206 CDecl = CurMethod->getClassInterface();
5207 if (!CDecl)
5208 return;
5209
5210 // Find the superclass of this class.
5211 CDecl = CDecl->getSuperClass();
5212 if (!CDecl)
5213 return;
5214
5215 if (CurMethod->isInstanceMethod()) {
5216 // We are inside an instance method, which means that the message
5217 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005218 // current object.
5219 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005220 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005221 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005222 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005223 }
5224
5225 // Fall through to send to the superclass in CDecl.
5226 } else {
5227 // "super" may be the name of a type or variable. Figure out which
5228 // it is.
5229 IdentifierInfo *Super = &Context.Idents.get("super");
5230 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5231 LookupOrdinaryName);
5232 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5233 // "super" names an interface. Use it.
5234 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005235 if (const ObjCObjectType *Iface
5236 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5237 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005238 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5239 // "super" names an unresolved type; we can't be more specific.
5240 } else {
5241 // Assume that "super" names some kind of value and parse that way.
5242 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005243 SourceLocation TemplateKWLoc;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005244 UnqualifiedId id;
5245 id.setIdentifier(Super, SuperLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005246 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5247 false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005248 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005249 SelIdents, NumSelIdents,
5250 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005251 }
5252
5253 // Fall through
5254 }
5255
John McCallb3d87482010-08-24 05:47:05 +00005256 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005257 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005258 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005259 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005260 NumSelIdents, AtArgumentExpression,
5261 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005262}
5263
Douglas Gregorb9d77572010-09-21 00:03:25 +00005264/// \brief Given a set of code-completion results for the argument of a message
5265/// send, determine the preferred type (if any) for that argument expression.
5266static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5267 unsigned NumSelIdents) {
5268 typedef CodeCompletionResult Result;
5269 ASTContext &Context = Results.getSema().Context;
5270
5271 QualType PreferredType;
5272 unsigned BestPriority = CCP_Unlikely * 2;
5273 Result *ResultsData = Results.data();
5274 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5275 Result &R = ResultsData[I];
5276 if (R.Kind == Result::RK_Declaration &&
5277 isa<ObjCMethodDecl>(R.Declaration)) {
5278 if (R.Priority <= BestPriority) {
5279 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5280 if (NumSelIdents <= Method->param_size()) {
5281 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5282 ->getType();
5283 if (R.Priority < BestPriority || PreferredType.isNull()) {
5284 BestPriority = R.Priority;
5285 PreferredType = MyPreferredType;
5286 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5287 MyPreferredType)) {
5288 PreferredType = QualType();
5289 }
5290 }
5291 }
5292 }
5293 }
5294
5295 return PreferredType;
5296}
5297
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005298static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5299 ParsedType Receiver,
5300 IdentifierInfo **SelIdents,
5301 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005302 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005303 bool IsSuper,
5304 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005305 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005306 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005307
Douglas Gregor24a069f2009-11-17 17:59:40 +00005308 // If the given name refers to an interface type, retrieve the
5309 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005310 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005311 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005312 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005313 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5314 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005315 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005316
Douglas Gregor36ecb042009-11-17 23:22:23 +00005317 // Add all of the factory methods in this Objective-C class, its protocols,
5318 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005319 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005320
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005321 // If this is a send-to-super, try to add the special "super" send
5322 // completion.
5323 if (IsSuper) {
5324 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005325 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5326 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005327 Results.Ignore(SuperMethod);
5328 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005329
Douglas Gregor265f7492010-08-27 15:29:55 +00005330 // If we're inside an Objective-C method definition, prefer its selector to
5331 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005332 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005333 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005334
Douglas Gregord36adf52010-09-16 16:06:31 +00005335 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005336 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005337 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005338 SemaRef.CurContext, Selectors, AtArgumentExpression,
5339 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005340 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005341 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005342
Douglas Gregor719770d2010-04-06 17:30:22 +00005343 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005344 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005345 if (SemaRef.ExternalSource) {
5346 for (uint32_t I = 0,
5347 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005348 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005349 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5350 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005351 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005352
5353 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005354 }
5355 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005356
5357 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5358 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005359 M != MEnd; ++M) {
5360 for (ObjCMethodList *MethList = &M->second.second;
5361 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005362 MethList = MethList->Next) {
5363 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5364 NumSelIdents))
5365 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005366
Douglas Gregor13438f92010-04-06 16:40:00 +00005367 Result R(MethList->Method, 0);
5368 R.StartParameter = NumSelIdents;
5369 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005370 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005371 }
5372 }
5373 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005374
5375 Results.ExitScope();
5376}
Douglas Gregor13438f92010-04-06 16:40:00 +00005377
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005378void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5379 IdentifierInfo **SelIdents,
5380 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005381 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005382 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005383
5384 QualType T = this->GetTypeFromParser(Receiver);
5385
Douglas Gregor218937c2011-02-01 19:23:04 +00005386 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005387 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregore081a612011-07-21 01:05:26 +00005388 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005389 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005390
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005391 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5392 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005393
5394 // If we're actually at the argument expression (rather than prior to the
5395 // selector), we're actually performing code completion for an expression.
5396 // Determine whether we have a single, best method. If so, we can
5397 // code-complete the expression using the corresponding parameter type as
5398 // our preferred type, improving completion results.
5399 if (AtArgumentExpression) {
5400 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005401 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005402 if (PreferredType.isNull())
5403 CodeCompleteOrdinaryName(S, PCC_Expression);
5404 else
5405 CodeCompleteExpression(S, PreferredType);
5406 return;
5407 }
5408
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005409 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005410 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005411 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005412}
5413
Richard Trieuf81e5a92011-09-09 02:00:50 +00005414void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005415 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005416 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005417 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005418 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005419 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005420
5421 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005422
Douglas Gregor36ecb042009-11-17 23:22:23 +00005423 // If necessary, apply function/array conversion to the receiver.
5424 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005425 if (RecExpr) {
5426 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5427 if (Conv.isInvalid()) // conversion failed. bail.
5428 return;
5429 RecExpr = Conv.take();
5430 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005431 QualType ReceiverType = RecExpr? RecExpr->getType()
5432 : Super? Context.getObjCObjectPointerType(
5433 Context.getObjCInterfaceType(Super))
5434 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005435
Douglas Gregorda892642010-11-08 21:12:30 +00005436 // If we're messaging an expression with type "id" or "Class", check
5437 // whether we know something special about the receiver that allows
5438 // us to assume a more-specific receiver type.
5439 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5440 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5441 if (ReceiverType->isObjCClassType())
5442 return CodeCompleteObjCClassMessage(S,
5443 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5444 SelIdents, NumSelIdents,
5445 AtArgumentExpression, Super);
5446
5447 ReceiverType = Context.getObjCObjectPointerType(
5448 Context.getObjCInterfaceType(IFace));
5449 }
5450
Douglas Gregor36ecb042009-11-17 23:22:23 +00005451 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005452 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005453 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregore081a612011-07-21 01:05:26 +00005454 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005455 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005456
Douglas Gregor36ecb042009-11-17 23:22:23 +00005457 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005458
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005459 // If this is a send-to-super, try to add the special "super" send
5460 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005461 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005462 if (ObjCMethodDecl *SuperMethod
5463 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5464 Results))
5465 Results.Ignore(SuperMethod);
5466 }
5467
Douglas Gregor265f7492010-08-27 15:29:55 +00005468 // If we're inside an Objective-C method definition, prefer its selector to
5469 // others.
5470 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5471 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005472
Douglas Gregord36adf52010-09-16 16:06:31 +00005473 // Keep track of the selectors we've already added.
5474 VisitedSelectorSet Selectors;
5475
Douglas Gregorf74a4192009-11-18 00:06:18 +00005476 // Handle messages to Class. This really isn't a message to an instance
5477 // method, so we treat it the same way we would treat a message send to a
5478 // class method.
5479 if (ReceiverType->isObjCClassType() ||
5480 ReceiverType->isObjCQualifiedClassType()) {
5481 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5482 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005483 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005484 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005485 }
5486 }
5487 // Handle messages to a qualified ID ("id<foo>").
5488 else if (const ObjCObjectPointerType *QualID
5489 = ReceiverType->getAsObjCQualifiedIdType()) {
5490 // Search protocols for instance methods.
5491 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5492 E = QualID->qual_end();
5493 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005494 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005495 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005496 }
5497 // Handle messages to a pointer to interface type.
5498 else if (const ObjCObjectPointerType *IFacePtr
5499 = ReceiverType->getAsObjCInterfacePointerType()) {
5500 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005501 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005502 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5503 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005504
5505 // Search protocols for instance methods.
5506 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5507 E = IFacePtr->qual_end();
5508 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005509 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005510 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005511 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005512 // Handle messages to "id".
5513 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005514 // We're messaging "id", so provide all instance methods we know
5515 // about as code-completion results.
5516
5517 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005518 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005519 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005520 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5521 I != N; ++I) {
5522 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005523 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005524 continue;
5525
Sebastian Redldb9d2142010-08-02 23:18:59 +00005526 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005527 }
5528 }
5529
Sebastian Redldb9d2142010-08-02 23:18:59 +00005530 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5531 MEnd = MethodPool.end();
5532 M != MEnd; ++M) {
5533 for (ObjCMethodList *MethList = &M->second.first;
5534 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005535 MethList = MethList->Next) {
5536 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5537 NumSelIdents))
5538 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005539
5540 if (!Selectors.insert(MethList->Method->getSelector()))
5541 continue;
5542
Douglas Gregor13438f92010-04-06 16:40:00 +00005543 Result R(MethList->Method, 0);
5544 R.StartParameter = NumSelIdents;
5545 R.AllParametersAreInformative = false;
5546 Results.MaybeAddResult(R, CurContext);
5547 }
5548 }
5549 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005550 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005551
5552
5553 // If we're actually at the argument expression (rather than prior to the
5554 // selector), we're actually performing code completion for an expression.
5555 // Determine whether we have a single, best method. If so, we can
5556 // code-complete the expression using the corresponding parameter type as
5557 // our preferred type, improving completion results.
5558 if (AtArgumentExpression) {
5559 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5560 NumSelIdents);
5561 if (PreferredType.isNull())
5562 CodeCompleteOrdinaryName(S, PCC_Expression);
5563 else
5564 CodeCompleteExpression(S, PreferredType);
5565 return;
5566 }
5567
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005568 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005569 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005570 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005571}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005572
Douglas Gregorfb629412010-08-23 21:17:50 +00005573void Sema::CodeCompleteObjCForCollection(Scope *S,
5574 DeclGroupPtrTy IterationVar) {
5575 CodeCompleteExpressionData Data;
5576 Data.ObjCCollection = true;
5577
5578 if (IterationVar.getAsOpaquePtr()) {
5579 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5580 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5581 if (*I)
5582 Data.IgnoreDecls.push_back(*I);
5583 }
5584 }
5585
5586 CodeCompleteExpression(S, Data);
5587}
5588
Douglas Gregor458433d2010-08-26 15:07:07 +00005589void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5590 unsigned NumSelIdents) {
5591 // If we have an external source, load the entire class method
5592 // pool from the AST file.
5593 if (ExternalSource) {
5594 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5595 I != N; ++I) {
5596 Selector Sel = ExternalSource->GetExternalSelector(I);
5597 if (Sel.isNull() || MethodPool.count(Sel))
5598 continue;
5599
5600 ReadMethodPool(Sel);
5601 }
5602 }
5603
Douglas Gregor218937c2011-02-01 19:23:04 +00005604 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005605 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005606 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005607 Results.EnterNewScope();
5608 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5609 MEnd = MethodPool.end();
5610 M != MEnd; ++M) {
5611
5612 Selector Sel = M->first;
5613 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5614 continue;
5615
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005616 CodeCompletionBuilder Builder(Results.getAllocator(),
5617 Results.getCodeCompletionTUInfo());
Douglas Gregor458433d2010-08-26 15:07:07 +00005618 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005619 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005620 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005621 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005622 continue;
5623 }
5624
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005625 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005626 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005627 if (I == NumSelIdents) {
5628 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005629 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005630 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005631 Accumulator.clear();
5632 }
5633 }
5634
Benjamin Kramera0651c52011-07-26 16:59:25 +00005635 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005636 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005637 }
Douglas Gregordae68752011-02-01 22:57:45 +00005638 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005639 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005640 }
5641 Results.ExitScope();
5642
5643 HandleCodeCompleteResults(this, CodeCompleter,
5644 CodeCompletionContext::CCC_SelectorName,
5645 Results.data(), Results.size());
5646}
5647
Douglas Gregor55385fe2009-11-18 04:19:12 +00005648/// \brief Add all of the protocol declarations that we find in the given
5649/// (translation unit) context.
5650static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005651 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005652 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005653 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005654
5655 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5656 DEnd = Ctx->decls_end();
5657 D != DEnd; ++D) {
5658 // Record any protocols we find.
5659 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005660 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregor608300b2010-01-14 16:14:35 +00005661 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005662 }
5663}
5664
5665void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5666 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005667 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005668 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005669 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005670
Douglas Gregor70c23352010-12-09 21:44:02 +00005671 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5672 Results.EnterNewScope();
5673
5674 // Tell the result set to ignore all of the protocols we have
5675 // already seen.
5676 // FIXME: This doesn't work when caching code-completion results.
5677 for (unsigned I = 0; I != NumProtocols; ++I)
5678 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5679 Protocols[I].second))
5680 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005681
Douglas Gregor70c23352010-12-09 21:44:02 +00005682 // Add all protocols.
5683 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5684 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005685
Douglas Gregor70c23352010-12-09 21:44:02 +00005686 Results.ExitScope();
5687 }
5688
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005689 HandleCodeCompleteResults(this, CodeCompleter,
5690 CodeCompletionContext::CCC_ObjCProtocolName,
5691 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005692}
5693
5694void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005695 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005696 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005697 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005698
Douglas Gregor70c23352010-12-09 21:44:02 +00005699 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5700 Results.EnterNewScope();
5701
5702 // Add all protocols.
5703 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5704 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005705
Douglas Gregor70c23352010-12-09 21:44:02 +00005706 Results.ExitScope();
5707 }
5708
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005709 HandleCodeCompleteResults(this, CodeCompleter,
5710 CodeCompletionContext::CCC_ObjCProtocolName,
5711 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005712}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005713
5714/// \brief Add all of the Objective-C interface declarations that we find in
5715/// the given (translation unit) context.
5716static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5717 bool OnlyForwardDeclarations,
5718 bool OnlyUnimplemented,
5719 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005720 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005721
5722 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5723 DEnd = Ctx->decls_end();
5724 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005725 // Record any interfaces we find.
5726 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregor7723fec2011-12-15 20:29:51 +00005727 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005728 (!OnlyUnimplemented || !Class->getImplementation()))
5729 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005730 }
5731}
5732
5733void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005734 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005735 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005736 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005737 Results.EnterNewScope();
5738
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005739 if (CodeCompleter->includeGlobals()) {
5740 // Add all classes.
5741 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5742 false, Results);
5743 }
5744
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005745 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005746
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005747 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005748 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005749 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005750}
5751
Douglas Gregorc83c6872010-04-15 22:33:43 +00005752void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5753 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005754 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005755 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005756 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005757 Results.EnterNewScope();
5758
5759 // Make sure that we ignore the class we're currently defining.
5760 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005761 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005762 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005763 Results.Ignore(CurClass);
5764
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005765 if (CodeCompleter->includeGlobals()) {
5766 // Add all classes.
5767 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5768 false, Results);
5769 }
5770
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005771 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005772
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005773 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005774 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005775 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005776}
5777
5778void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005779 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005780 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005781 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005782 Results.EnterNewScope();
5783
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005784 if (CodeCompleter->includeGlobals()) {
5785 // Add all unimplemented classes.
5786 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5787 true, Results);
5788 }
5789
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005790 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005791
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005792 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005793 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005794 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005795}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005796
5797void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005798 IdentifierInfo *ClassName,
5799 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005800 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005801
Douglas Gregor218937c2011-02-01 19:23:04 +00005802 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005803 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005804 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005805
5806 // Ignore any categories we find that have already been implemented by this
5807 // interface.
5808 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5809 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005810 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005811 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5812 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5813 Category = Category->getNextClassCategory())
5814 CategoryNames.insert(Category->getIdentifier());
5815
5816 // Add all of the categories we know about.
5817 Results.EnterNewScope();
5818 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5819 for (DeclContext::decl_iterator D = TU->decls_begin(),
5820 DEnd = TU->decls_end();
5821 D != DEnd; ++D)
5822 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5823 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005824 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005825 Results.ExitScope();
5826
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005827 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005828 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005829 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005830}
5831
5832void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005833 IdentifierInfo *ClassName,
5834 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005835 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005836
5837 // Find the corresponding interface. If we couldn't find the interface, the
5838 // program itself is ill-formed. However, we'll try to be helpful still by
5839 // providing the list of all of the categories we know about.
5840 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005841 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005842 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5843 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005844 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005845
Douglas Gregor218937c2011-02-01 19:23:04 +00005846 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005847 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005848 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005849
5850 // Add all of the categories that have have corresponding interface
5851 // declarations in this class and any of its superclasses, except for
5852 // already-implemented categories in the class itself.
5853 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5854 Results.EnterNewScope();
5855 bool IgnoreImplemented = true;
5856 while (Class) {
5857 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5858 Category = Category->getNextClassCategory())
5859 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5860 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005861 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005862
5863 Class = Class->getSuperClass();
5864 IgnoreImplemented = false;
5865 }
5866 Results.ExitScope();
5867
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005868 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005869 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005870 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005871}
Douglas Gregor322328b2009-11-18 22:32:06 +00005872
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005873void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005874 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005875 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005876 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005877
5878 // Figure out where this @synthesize lives.
5879 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005880 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005881 if (!Container ||
5882 (!isa<ObjCImplementationDecl>(Container) &&
5883 !isa<ObjCCategoryImplDecl>(Container)))
5884 return;
5885
5886 // Ignore any properties that have already been implemented.
Douglas Gregorb92a4082012-06-12 13:44:08 +00005887 Container = getContainerDef(Container);
5888 for (DeclContext::decl_iterator D = Container->decls_begin(),
Douglas Gregor322328b2009-11-18 22:32:06 +00005889 DEnd = Container->decls_end();
5890 D != DEnd; ++D)
5891 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5892 Results.Ignore(PropertyImpl->getPropertyDecl());
5893
5894 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005895 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005896 Results.EnterNewScope();
5897 if (ObjCImplementationDecl *ClassImpl
5898 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005899 AddObjCProperties(ClassImpl->getClassInterface(), false,
5900 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005901 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005902 else
5903 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005904 false, /*AllowNullaryMethods=*/false, CurContext,
5905 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005906 Results.ExitScope();
5907
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005908 HandleCodeCompleteResults(this, CodeCompleter,
5909 CodeCompletionContext::CCC_Other,
5910 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005911}
5912
5913void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005914 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005915 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005916 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005917 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005918 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005919
5920 // Figure out where this @synthesize lives.
5921 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005922 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005923 if (!Container ||
5924 (!isa<ObjCImplementationDecl>(Container) &&
5925 !isa<ObjCCategoryImplDecl>(Container)))
5926 return;
5927
5928 // Figure out which interface we're looking into.
5929 ObjCInterfaceDecl *Class = 0;
5930 if (ObjCImplementationDecl *ClassImpl
5931 = dyn_cast<ObjCImplementationDecl>(Container))
5932 Class = ClassImpl->getClassInterface();
5933 else
5934 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5935 ->getClassInterface();
5936
Douglas Gregore8426052011-04-18 14:40:46 +00005937 // Determine the type of the property we're synthesizing.
5938 QualType PropertyType = Context.getObjCIdType();
5939 if (Class) {
5940 if (ObjCPropertyDecl *Property
5941 = Class->FindPropertyDeclaration(PropertyName)) {
5942 PropertyType
5943 = Property->getType().getNonReferenceType().getUnqualifiedType();
5944
5945 // Give preference to ivars
5946 Results.setPreferredType(PropertyType);
5947 }
5948 }
5949
Douglas Gregor322328b2009-11-18 22:32:06 +00005950 // Add all of the instance variables in this class and its superclasses.
5951 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005952 bool SawSimilarlyNamedIvar = false;
5953 std::string NameWithPrefix;
5954 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005955 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005956 std::string NameWithSuffix = PropertyName->getName().str();
5957 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005958 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005959 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5960 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005961 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5962
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005963 // Determine whether we've seen an ivar with a name similar to the
5964 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005965 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005966 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005967 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005968 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005969
5970 // Reduce the priority of this result by one, to give it a slight
5971 // advantage over other results whose names don't match so closely.
5972 if (Results.size() &&
5973 Results.data()[Results.size() - 1].Kind
5974 == CodeCompletionResult::RK_Declaration &&
5975 Results.data()[Results.size() - 1].Declaration == Ivar)
5976 Results.data()[Results.size() - 1].Priority--;
5977 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005978 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005979 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005980
5981 if (!SawSimilarlyNamedIvar) {
5982 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005983 // an ivar of the appropriate type.
5984 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005985 typedef CodeCompletionResult Result;
5986 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005987 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
5988 Priority,CXAvailability_Available);
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005989
Douglas Gregor8987b232011-09-27 23:30:47 +00005990 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005991 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005992 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005993 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5994 Results.AddResult(Result(Builder.TakeString(), Priority,
5995 CXCursor_ObjCIvarDecl));
5996 }
5997
Douglas Gregor322328b2009-11-18 22:32:06 +00005998 Results.ExitScope();
5999
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006000 HandleCodeCompleteResults(this, CodeCompleter,
6001 CodeCompletionContext::CCC_Other,
6002 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00006003}
Douglas Gregore8f5a172010-04-07 00:21:17 +00006004
Douglas Gregor408be5a2010-08-25 01:08:01 +00006005// Mapping from selectors to the methods that implement that selector, along
6006// with the "in original class" flag.
6007typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
6008 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006009
6010/// \brief Find all of the methods that reside in the given container
6011/// (and its superclasses, protocols, etc.) that meet the given
6012/// criteria. Insert those methods into the map of known methods,
6013/// indexed by selector so they can be easily found.
6014static void FindImplementableMethods(ASTContext &Context,
6015 ObjCContainerDecl *Container,
6016 bool WantInstanceMethods,
6017 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00006018 KnownMethodsMap &KnownMethods,
6019 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006020 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregorb92a4082012-06-12 13:44:08 +00006021 // Make sure we have a definition; that's what we'll walk.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00006022 if (!IFace->hasDefinition())
6023 return;
Douglas Gregorb92a4082012-06-12 13:44:08 +00006024
6025 IFace = IFace->getDefinition();
6026 Container = IFace;
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00006027
Douglas Gregore8f5a172010-04-07 00:21:17 +00006028 const ObjCList<ObjCProtocolDecl> &Protocols
6029 = IFace->getReferencedProtocols();
6030 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00006031 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006032 I != E; ++I)
6033 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006034 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006035
Douglas Gregorea766182010-10-18 18:21:28 +00006036 // Add methods from any class extensions and categories.
6037 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
6038 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00006039 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
6040 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006041 KnownMethods, false);
6042
6043 // Visit the superclass.
6044 if (IFace->getSuperClass())
6045 FindImplementableMethods(Context, IFace->getSuperClass(),
6046 WantInstanceMethods, ReturnType,
6047 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006048 }
6049
6050 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6051 // Recurse into protocols.
6052 const ObjCList<ObjCProtocolDecl> &Protocols
6053 = Category->getReferencedProtocols();
6054 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00006055 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006056 I != E; ++I)
6057 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006058 KnownMethods, InOriginalClass);
6059
6060 // If this category is the original class, jump to the interface.
6061 if (InOriginalClass && Category->getClassInterface())
6062 FindImplementableMethods(Context, Category->getClassInterface(),
6063 WantInstanceMethods, ReturnType, KnownMethods,
6064 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006065 }
6066
6067 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregorb92a4082012-06-12 13:44:08 +00006068 // Make sure we have a definition; that's what we'll walk.
6069 if (!Protocol->hasDefinition())
6070 return;
6071 Protocol = Protocol->getDefinition();
6072 Container = Protocol;
6073
6074 // Recurse into protocols.
6075 const ObjCList<ObjCProtocolDecl> &Protocols
6076 = Protocol->getReferencedProtocols();
6077 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6078 E = Protocols.end();
6079 I != E; ++I)
6080 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6081 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006082 }
6083
6084 // Add methods in this container. This operation occurs last because
6085 // we want the methods from this container to override any methods
6086 // we've previously seen with the same selector.
6087 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
6088 MEnd = Container->meth_end();
6089 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00006090 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006091 if (!ReturnType.isNull() &&
David Blaikie262bc182012-04-30 02:36:29 +00006092 !Context.hasSameUnqualifiedType(ReturnType, M->getResultType()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006093 continue;
6094
David Blaikie581deb32012-06-06 20:45:41 +00006095 KnownMethods[M->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006096 }
6097 }
6098}
6099
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006100/// \brief Add the parenthesized return or parameter type chunk to a code
6101/// completion string.
6102static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor90f5f472012-04-10 18:35:07 +00006103 unsigned ObjCDeclQuals,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006104 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006105 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006106 CodeCompletionBuilder &Builder) {
6107 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor90f5f472012-04-10 18:35:07 +00006108 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6109 if (!Quals.empty())
6110 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor8987b232011-09-27 23:30:47 +00006111 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006112 Builder.getAllocator()));
6113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6114}
6115
6116/// \brief Determine whether the given class is or inherits from a class by
6117/// the given name.
6118static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006119 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006120 if (!Class)
6121 return false;
6122
6123 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6124 return true;
6125
6126 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6127}
6128
6129/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6130/// Key-Value Observing (KVO).
6131static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6132 bool IsInstanceMethod,
6133 QualType ReturnType,
6134 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006135 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006136 ResultBuilder &Results) {
6137 IdentifierInfo *PropName = Property->getIdentifier();
6138 if (!PropName || PropName->getLength() == 0)
6139 return;
6140
Douglas Gregor8987b232011-09-27 23:30:47 +00006141 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6142
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006143 // Builder that will create each code completion.
6144 typedef CodeCompletionResult Result;
6145 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006146 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006147
6148 // The selector table.
6149 SelectorTable &Selectors = Context.Selectors;
6150
6151 // The property name, copied into the code completion allocation region
6152 // on demand.
6153 struct KeyHolder {
6154 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006155 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006156 const char *CopiedKey;
6157
Chris Lattner5f9e2722011-07-23 10:55:15 +00006158 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006159 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6160
6161 operator const char *() {
6162 if (CopiedKey)
6163 return CopiedKey;
6164
6165 return CopiedKey = Allocator.CopyString(Key);
6166 }
6167 } Key(Allocator, PropName->getName());
6168
6169 // The uppercased name of the property name.
6170 std::string UpperKey = PropName->getName();
6171 if (!UpperKey.empty())
6172 UpperKey[0] = toupper(UpperKey[0]);
6173
6174 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6175 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6176 Property->getType());
6177 bool ReturnTypeMatchesVoid
6178 = ReturnType.isNull() || ReturnType->isVoidType();
6179
6180 // Add the normal accessor -(type)key.
6181 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00006182 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006183 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6184 if (ReturnType.isNull())
Douglas Gregor90f5f472012-04-10 18:35:07 +00006185 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6186 Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006187
6188 Builder.AddTypedTextChunk(Key);
6189 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6190 CXCursor_ObjCInstanceMethodDecl));
6191 }
6192
6193 // If we have an integral or boolean property (or the user has provided
6194 // an integral or boolean return type), add the accessor -(type)isKey.
6195 if (IsInstanceMethod &&
6196 ((!ReturnType.isNull() &&
6197 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6198 (ReturnType.isNull() &&
6199 (Property->getType()->isIntegerType() ||
6200 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006201 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006202 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006203 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006204 if (ReturnType.isNull()) {
6205 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6206 Builder.AddTextChunk("BOOL");
6207 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6208 }
6209
6210 Builder.AddTypedTextChunk(
6211 Allocator.CopyString(SelectorId->getName()));
6212 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6213 CXCursor_ObjCInstanceMethodDecl));
6214 }
6215 }
6216
6217 // Add the normal mutator.
6218 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6219 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006220 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006221 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006222 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006223 if (ReturnType.isNull()) {
6224 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6225 Builder.AddTextChunk("void");
6226 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6227 }
6228
6229 Builder.AddTypedTextChunk(
6230 Allocator.CopyString(SelectorId->getName()));
6231 Builder.AddTypedTextChunk(":");
Douglas Gregor90f5f472012-04-10 18:35:07 +00006232 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6233 Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006234 Builder.AddTextChunk(Key);
6235 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6236 CXCursor_ObjCInstanceMethodDecl));
6237 }
6238 }
6239
6240 // Indexed and unordered accessors
6241 unsigned IndexedGetterPriority = CCP_CodePattern;
6242 unsigned IndexedSetterPriority = CCP_CodePattern;
6243 unsigned UnorderedGetterPriority = CCP_CodePattern;
6244 unsigned UnorderedSetterPriority = CCP_CodePattern;
6245 if (const ObjCObjectPointerType *ObjCPointer
6246 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6247 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6248 // If this interface type is not provably derived from a known
6249 // collection, penalize the corresponding completions.
6250 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6251 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6252 if (!InheritsFromClassNamed(IFace, "NSArray"))
6253 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6254 }
6255
6256 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6257 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6258 if (!InheritsFromClassNamed(IFace, "NSSet"))
6259 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6260 }
6261 }
6262 } else {
6263 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6264 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6265 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6266 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6267 }
6268
6269 // Add -(NSUInteger)countOf<key>
6270 if (IsInstanceMethod &&
6271 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006272 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006273 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006274 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006275 if (ReturnType.isNull()) {
6276 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6277 Builder.AddTextChunk("NSUInteger");
6278 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6279 }
6280
6281 Builder.AddTypedTextChunk(
6282 Allocator.CopyString(SelectorId->getName()));
6283 Results.AddResult(Result(Builder.TakeString(),
6284 std::min(IndexedGetterPriority,
6285 UnorderedGetterPriority),
6286 CXCursor_ObjCInstanceMethodDecl));
6287 }
6288 }
6289
6290 // Indexed getters
6291 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6292 if (IsInstanceMethod &&
6293 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006294 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006295 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006296 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006297 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006298 if (ReturnType.isNull()) {
6299 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6300 Builder.AddTextChunk("id");
6301 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6302 }
6303
6304 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6306 Builder.AddTextChunk("NSUInteger");
6307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6308 Builder.AddTextChunk("index");
6309 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6310 CXCursor_ObjCInstanceMethodDecl));
6311 }
6312 }
6313
6314 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6315 if (IsInstanceMethod &&
6316 (ReturnType.isNull() ||
6317 (ReturnType->isObjCObjectPointerType() &&
6318 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6319 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6320 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006321 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006322 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006323 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006324 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006325 if (ReturnType.isNull()) {
6326 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6327 Builder.AddTextChunk("NSArray *");
6328 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6329 }
6330
6331 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6333 Builder.AddTextChunk("NSIndexSet *");
6334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6335 Builder.AddTextChunk("indexes");
6336 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6337 CXCursor_ObjCInstanceMethodDecl));
6338 }
6339 }
6340
6341 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6342 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006343 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006344 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006345 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006346 &Context.Idents.get("range")
6347 };
6348
Douglas Gregore74c25c2011-05-04 23:50:46 +00006349 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006350 if (ReturnType.isNull()) {
6351 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6352 Builder.AddTextChunk("void");
6353 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6354 }
6355
6356 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6357 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6358 Builder.AddPlaceholderChunk("object-type");
6359 Builder.AddTextChunk(" **");
6360 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6361 Builder.AddTextChunk("buffer");
6362 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6363 Builder.AddTypedTextChunk("range:");
6364 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6365 Builder.AddTextChunk("NSRange");
6366 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6367 Builder.AddTextChunk("inRange");
6368 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6369 CXCursor_ObjCInstanceMethodDecl));
6370 }
6371 }
6372
6373 // Mutable indexed accessors
6374
6375 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6376 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006377 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006378 IdentifierInfo *SelectorIds[2] = {
6379 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006380 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 };
6382
Douglas Gregore74c25c2011-05-04 23:50:46 +00006383 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006384 if (ReturnType.isNull()) {
6385 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6386 Builder.AddTextChunk("void");
6387 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6388 }
6389
6390 Builder.AddTypedTextChunk("insertObject:");
6391 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6392 Builder.AddPlaceholderChunk("object-type");
6393 Builder.AddTextChunk(" *");
6394 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6395 Builder.AddTextChunk("object");
6396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6397 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6398 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6399 Builder.AddPlaceholderChunk("NSUInteger");
6400 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6401 Builder.AddTextChunk("index");
6402 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6403 CXCursor_ObjCInstanceMethodDecl));
6404 }
6405 }
6406
6407 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6408 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006409 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006410 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006411 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006412 &Context.Idents.get("atIndexes")
6413 };
6414
Douglas Gregore74c25c2011-05-04 23:50:46 +00006415 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006416 if (ReturnType.isNull()) {
6417 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6418 Builder.AddTextChunk("void");
6419 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6420 }
6421
6422 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6423 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6424 Builder.AddTextChunk("NSArray *");
6425 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6426 Builder.AddTextChunk("array");
6427 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6428 Builder.AddTypedTextChunk("atIndexes:");
6429 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6430 Builder.AddPlaceholderChunk("NSIndexSet *");
6431 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6432 Builder.AddTextChunk("indexes");
6433 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6434 CXCursor_ObjCInstanceMethodDecl));
6435 }
6436 }
6437
6438 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6439 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006440 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006441 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006442 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006443 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006444 if (ReturnType.isNull()) {
6445 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6446 Builder.AddTextChunk("void");
6447 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6448 }
6449
6450 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6451 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6452 Builder.AddTextChunk("NSUInteger");
6453 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6454 Builder.AddTextChunk("index");
6455 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6456 CXCursor_ObjCInstanceMethodDecl));
6457 }
6458 }
6459
6460 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6461 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006462 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006463 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006464 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006465 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006466 if (ReturnType.isNull()) {
6467 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6468 Builder.AddTextChunk("void");
6469 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6470 }
6471
6472 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6473 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6474 Builder.AddTextChunk("NSIndexSet *");
6475 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6476 Builder.AddTextChunk("indexes");
6477 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6478 CXCursor_ObjCInstanceMethodDecl));
6479 }
6480 }
6481
6482 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6483 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006484 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006485 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006486 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006487 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006488 &Context.Idents.get("withObject")
6489 };
6490
Douglas Gregore74c25c2011-05-04 23:50:46 +00006491 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006492 if (ReturnType.isNull()) {
6493 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6494 Builder.AddTextChunk("void");
6495 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6496 }
6497
6498 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6499 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6500 Builder.AddPlaceholderChunk("NSUInteger");
6501 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6502 Builder.AddTextChunk("index");
6503 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6504 Builder.AddTypedTextChunk("withObject:");
6505 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6506 Builder.AddTextChunk("id");
6507 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6508 Builder.AddTextChunk("object");
6509 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6510 CXCursor_ObjCInstanceMethodDecl));
6511 }
6512 }
6513
6514 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6515 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006516 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006517 = (Twine("replace") + UpperKey + "AtIndexes").str();
6518 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006519 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006520 &Context.Idents.get(SelectorName1),
6521 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006522 };
6523
Douglas Gregore74c25c2011-05-04 23:50:46 +00006524 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006525 if (ReturnType.isNull()) {
6526 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6527 Builder.AddTextChunk("void");
6528 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6529 }
6530
6531 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6532 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6533 Builder.AddPlaceholderChunk("NSIndexSet *");
6534 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6535 Builder.AddTextChunk("indexes");
6536 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6537 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6538 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6539 Builder.AddTextChunk("NSArray *");
6540 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6541 Builder.AddTextChunk("array");
6542 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6543 CXCursor_ObjCInstanceMethodDecl));
6544 }
6545 }
6546
6547 // Unordered getters
6548 // - (NSEnumerator *)enumeratorOfKey
6549 if (IsInstanceMethod &&
6550 (ReturnType.isNull() ||
6551 (ReturnType->isObjCObjectPointerType() &&
6552 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6553 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6554 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006555 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006556 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006557 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006558 if (ReturnType.isNull()) {
6559 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6560 Builder.AddTextChunk("NSEnumerator *");
6561 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6562 }
6563
6564 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6565 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6566 CXCursor_ObjCInstanceMethodDecl));
6567 }
6568 }
6569
6570 // - (type *)memberOfKey:(type *)object
6571 if (IsInstanceMethod &&
6572 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006573 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006574 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006575 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006576 if (ReturnType.isNull()) {
6577 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6578 Builder.AddPlaceholderChunk("object-type");
6579 Builder.AddTextChunk(" *");
6580 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6581 }
6582
6583 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6584 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6585 if (ReturnType.isNull()) {
6586 Builder.AddPlaceholderChunk("object-type");
6587 Builder.AddTextChunk(" *");
6588 } else {
6589 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006590 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006591 Builder.getAllocator()));
6592 }
6593 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6594 Builder.AddTextChunk("object");
6595 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6596 CXCursor_ObjCInstanceMethodDecl));
6597 }
6598 }
6599
6600 // Mutable unordered accessors
6601 // - (void)addKeyObject:(type *)object
6602 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006603 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006604 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006605 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006606 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006607 if (ReturnType.isNull()) {
6608 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6609 Builder.AddTextChunk("void");
6610 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6611 }
6612
6613 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6614 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6615 Builder.AddPlaceholderChunk("object-type");
6616 Builder.AddTextChunk(" *");
6617 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6618 Builder.AddTextChunk("object");
6619 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6620 CXCursor_ObjCInstanceMethodDecl));
6621 }
6622 }
6623
6624 // - (void)addKey:(NSSet *)objects
6625 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006626 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006627 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006628 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006629 if (ReturnType.isNull()) {
6630 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6631 Builder.AddTextChunk("void");
6632 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6633 }
6634
6635 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6636 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6637 Builder.AddTextChunk("NSSet *");
6638 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6639 Builder.AddTextChunk("objects");
6640 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6641 CXCursor_ObjCInstanceMethodDecl));
6642 }
6643 }
6644
6645 // - (void)removeKeyObject:(type *)object
6646 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006647 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006648 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006649 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006650 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006651 if (ReturnType.isNull()) {
6652 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6653 Builder.AddTextChunk("void");
6654 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6655 }
6656
6657 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6658 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6659 Builder.AddPlaceholderChunk("object-type");
6660 Builder.AddTextChunk(" *");
6661 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6662 Builder.AddTextChunk("object");
6663 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6664 CXCursor_ObjCInstanceMethodDecl));
6665 }
6666 }
6667
6668 // - (void)removeKey:(NSSet *)objects
6669 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006670 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006671 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006672 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006673 if (ReturnType.isNull()) {
6674 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6675 Builder.AddTextChunk("void");
6676 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6677 }
6678
6679 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6680 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6681 Builder.AddTextChunk("NSSet *");
6682 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6683 Builder.AddTextChunk("objects");
6684 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6685 CXCursor_ObjCInstanceMethodDecl));
6686 }
6687 }
6688
6689 // - (void)intersectKey:(NSSet *)objects
6690 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006691 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006692 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006693 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006694 if (ReturnType.isNull()) {
6695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6696 Builder.AddTextChunk("void");
6697 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6698 }
6699
6700 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6701 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6702 Builder.AddTextChunk("NSSet *");
6703 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6704 Builder.AddTextChunk("objects");
6705 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6706 CXCursor_ObjCInstanceMethodDecl));
6707 }
6708 }
6709
6710 // Key-Value Observing
6711 // + (NSSet *)keyPathsForValuesAffectingKey
6712 if (!IsInstanceMethod &&
6713 (ReturnType.isNull() ||
6714 (ReturnType->isObjCObjectPointerType() &&
6715 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6716 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6717 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006718 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006719 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006720 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006721 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006722 if (ReturnType.isNull()) {
6723 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6724 Builder.AddTextChunk("NSSet *");
6725 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6726 }
6727
6728 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6729 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006730 CXCursor_ObjCClassMethodDecl));
6731 }
6732 }
6733
6734 // + (BOOL)automaticallyNotifiesObserversForKey
6735 if (!IsInstanceMethod &&
6736 (ReturnType.isNull() ||
6737 ReturnType->isIntegerType() ||
6738 ReturnType->isBooleanType())) {
6739 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006740 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006741 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6742 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6743 if (ReturnType.isNull()) {
6744 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6745 Builder.AddTextChunk("BOOL");
6746 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6747 }
6748
6749 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6750 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6751 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006752 }
6753 }
6754}
6755
Douglas Gregore8f5a172010-04-07 00:21:17 +00006756void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6757 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006758 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006759 // Determine the return type of the method we're declaring, if
6760 // provided.
6761 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006762 Decl *IDecl = 0;
6763 if (CurContext->isObjCContainer()) {
6764 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6765 IDecl = cast<Decl>(OCD);
6766 }
Douglas Gregorea766182010-10-18 18:21:28 +00006767 // Determine where we should start searching for methods.
6768 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006769 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006770 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006771 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6772 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006773 IsInImplementation = true;
6774 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006775 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006776 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006777 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006778 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006779 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006780 }
6781
6782 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006783 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006784 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006785 }
6786
Douglas Gregorea766182010-10-18 18:21:28 +00006787 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006788 HandleCodeCompleteResults(this, CodeCompleter,
6789 CodeCompletionContext::CCC_Other,
6790 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006791 return;
6792 }
6793
6794 // Find all of the methods that we could declare/implement here.
6795 KnownMethodsMap KnownMethods;
6796 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006797 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006798
Douglas Gregore8f5a172010-04-07 00:21:17 +00006799 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006800 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006801 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006802 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00006803 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006804 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006805 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006806 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6807 MEnd = KnownMethods.end();
6808 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006809 ObjCMethodDecl *Method = M->second.first;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006810 CodeCompletionBuilder Builder(Results.getAllocator(),
6811 Results.getCodeCompletionTUInfo());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006812
6813 // If the result type was not already provided, add it to the
6814 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006815 if (ReturnType.isNull())
Douglas Gregor90f5f472012-04-10 18:35:07 +00006816 AddObjCPassingTypeChunk(Method->getResultType(),
6817 Method->getObjCDeclQualifier(),
6818 Context, Policy,
6819 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006820
6821 Selector Sel = Method->getSelector();
6822
6823 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006824 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006825 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006826
6827 // Add parameters to the pattern.
6828 unsigned I = 0;
6829 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6830 PEnd = Method->param_end();
6831 P != PEnd; (void)++P, ++I) {
6832 // Add the part of the selector name.
6833 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006834 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006835 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6837 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006838 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006839 } else
6840 break;
6841
6842 // Add the parameter type.
Douglas Gregor90f5f472012-04-10 18:35:07 +00006843 AddObjCPassingTypeChunk((*P)->getOriginalType(),
6844 (*P)->getObjCDeclQualifier(),
6845 Context, Policy,
Douglas Gregor8987b232011-09-27 23:30:47 +00006846 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006847
6848 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006849 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006850 }
6851
6852 if (Method->isVariadic()) {
6853 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006854 Builder.AddChunk(CodeCompletionString::CK_Comma);
6855 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006856 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006857
Douglas Gregor447107d2010-05-28 00:57:46 +00006858 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006859 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006860 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6861 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6862 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006863 if (!Method->getResultType()->isVoidType()) {
6864 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006865 Builder.AddTextChunk("return");
6866 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6867 Builder.AddPlaceholderChunk("expression");
6868 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006869 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006870 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006871
Douglas Gregor218937c2011-02-01 19:23:04 +00006872 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6873 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006874 }
6875
Douglas Gregor408be5a2010-08-25 01:08:01 +00006876 unsigned Priority = CCP_CodePattern;
6877 if (!M->second.second)
6878 Priority += CCD_InBaseClass;
6879
Douglas Gregorba103062012-03-27 23:34:16 +00006880 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006881 }
6882
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006883 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6884 // the properties in this class and its categories.
David Blaikie4e4d0842012-03-11 07:00:24 +00006885 if (Context.getLangOpts().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006886 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006887 Containers.push_back(SearchDecl);
6888
Douglas Gregore74c25c2011-05-04 23:50:46 +00006889 VisitedSelectorSet KnownSelectors;
6890 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6891 MEnd = KnownMethods.end();
6892 M != MEnd; ++M)
6893 KnownSelectors.insert(M->first);
6894
6895
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006896 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6897 if (!IFace)
6898 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6899 IFace = Category->getClassInterface();
6900
6901 if (IFace) {
6902 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6903 Category = Category->getNextClassCategory())
6904 Containers.push_back(Category);
6905 }
6906
6907 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6908 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6909 PEnd = Containers[I]->prop_end();
6910 P != PEnd; ++P) {
David Blaikie581deb32012-06-06 20:45:41 +00006911 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006912 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006913 }
6914 }
6915 }
6916
Douglas Gregore8f5a172010-04-07 00:21:17 +00006917 Results.ExitScope();
6918
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006919 HandleCodeCompleteResults(this, CodeCompleter,
6920 CodeCompletionContext::CCC_Other,
6921 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006922}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006923
6924void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6925 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006926 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006927 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006928 IdentifierInfo **SelIdents,
6929 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006930 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006931 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006932 if (ExternalSource) {
6933 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6934 I != N; ++I) {
6935 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006936 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006937 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006938
6939 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006940 }
6941 }
6942
6943 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006944 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006945 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006946 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00006947 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006948
6949 if (ReturnTy)
6950 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006951
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006952 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006953 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6954 MEnd = MethodPool.end();
6955 M != MEnd; ++M) {
6956 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6957 &M->second.second;
6958 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006959 MethList = MethList->Next) {
6960 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6961 NumSelIdents))
6962 continue;
6963
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006964 if (AtParameterName) {
6965 // Suggest parameter names we've seen before.
6966 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6967 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6968 if (Param->getIdentifier()) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006969 CodeCompletionBuilder Builder(Results.getAllocator(),
6970 Results.getCodeCompletionTUInfo());
Douglas Gregordae68752011-02-01 22:57:45 +00006971 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006972 Param->getIdentifier()->getName()));
6973 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006974 }
6975 }
6976
6977 continue;
6978 }
6979
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006980 Result R(MethList->Method, 0);
6981 R.StartParameter = NumSelIdents;
6982 R.AllParametersAreInformative = false;
6983 R.DeclaringEntity = true;
6984 Results.MaybeAddResult(R, CurContext);
6985 }
6986 }
6987
6988 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006989 HandleCodeCompleteResults(this, CodeCompleter,
6990 CodeCompletionContext::CCC_Other,
6991 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006992}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006993
Douglas Gregorf29c5232010-08-24 22:20:20 +00006994void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006995 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006996 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006997 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006998 Results.EnterNewScope();
6999
7000 // #if <condition>
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007001 CodeCompletionBuilder Builder(Results.getAllocator(),
7002 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00007003 Builder.AddTypedTextChunk("if");
7004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7005 Builder.AddPlaceholderChunk("condition");
7006 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007007
7008 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007009 Builder.AddTypedTextChunk("ifdef");
7010 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7011 Builder.AddPlaceholderChunk("macro");
7012 Results.AddResult(Builder.TakeString());
7013
Douglas Gregorf44e8542010-08-24 19:08:16 +00007014 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007015 Builder.AddTypedTextChunk("ifndef");
7016 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7017 Builder.AddPlaceholderChunk("macro");
7018 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007019
7020 if (InConditional) {
7021 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00007022 Builder.AddTypedTextChunk("elif");
7023 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7024 Builder.AddPlaceholderChunk("condition");
7025 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007026
7027 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00007028 Builder.AddTypedTextChunk("else");
7029 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007030
7031 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00007032 Builder.AddTypedTextChunk("endif");
7033 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007034 }
7035
7036 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007037 Builder.AddTypedTextChunk("include");
7038 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7039 Builder.AddTextChunk("\"");
7040 Builder.AddPlaceholderChunk("header");
7041 Builder.AddTextChunk("\"");
7042 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007043
7044 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007045 Builder.AddTypedTextChunk("include");
7046 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7047 Builder.AddTextChunk("<");
7048 Builder.AddPlaceholderChunk("header");
7049 Builder.AddTextChunk(">");
7050 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007051
7052 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007053 Builder.AddTypedTextChunk("define");
7054 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7055 Builder.AddPlaceholderChunk("macro");
7056 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007057
7058 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00007059 Builder.AddTypedTextChunk("define");
7060 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7061 Builder.AddPlaceholderChunk("macro");
7062 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7063 Builder.AddPlaceholderChunk("args");
7064 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7065 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007066
7067 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007068 Builder.AddTypedTextChunk("undef");
7069 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7070 Builder.AddPlaceholderChunk("macro");
7071 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007072
7073 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00007074 Builder.AddTypedTextChunk("line");
7075 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7076 Builder.AddPlaceholderChunk("number");
7077 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007078
7079 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00007080 Builder.AddTypedTextChunk("line");
7081 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7082 Builder.AddPlaceholderChunk("number");
7083 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7084 Builder.AddTextChunk("\"");
7085 Builder.AddPlaceholderChunk("filename");
7086 Builder.AddTextChunk("\"");
7087 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007088
7089 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00007090 Builder.AddTypedTextChunk("error");
7091 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7092 Builder.AddPlaceholderChunk("message");
7093 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007094
7095 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00007096 Builder.AddTypedTextChunk("pragma");
7097 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7098 Builder.AddPlaceholderChunk("arguments");
7099 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007100
David Blaikie4e4d0842012-03-11 07:00:24 +00007101 if (getLangOpts().ObjC1) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00007102 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007103 Builder.AddTypedTextChunk("import");
7104 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7105 Builder.AddTextChunk("\"");
7106 Builder.AddPlaceholderChunk("header");
7107 Builder.AddTextChunk("\"");
7108 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007109
7110 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007111 Builder.AddTypedTextChunk("import");
7112 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7113 Builder.AddTextChunk("<");
7114 Builder.AddPlaceholderChunk("header");
7115 Builder.AddTextChunk(">");
7116 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007117 }
7118
7119 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007120 Builder.AddTypedTextChunk("include_next");
7121 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7122 Builder.AddTextChunk("\"");
7123 Builder.AddPlaceholderChunk("header");
7124 Builder.AddTextChunk("\"");
7125 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007126
7127 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007128 Builder.AddTypedTextChunk("include_next");
7129 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7130 Builder.AddTextChunk("<");
7131 Builder.AddPlaceholderChunk("header");
7132 Builder.AddTextChunk(">");
7133 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007134
7135 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00007136 Builder.AddTypedTextChunk("warning");
7137 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7138 Builder.AddPlaceholderChunk("message");
7139 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007140
7141 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7142 // completions for them. And __include_macros is a Clang-internal extension
7143 // that we don't want to encourage anyone to use.
7144
7145 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7146 Results.ExitScope();
7147
Douglas Gregorf44e8542010-08-24 19:08:16 +00007148 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00007149 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00007150 Results.data(), Results.size());
7151}
7152
7153void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00007154 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00007155 S->getFnParent()? Sema::PCC_RecoveryInFunction
7156 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00007157}
7158
Douglas Gregorf29c5232010-08-24 22:20:20 +00007159void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00007160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007161 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007162 IsDefinition? CodeCompletionContext::CCC_MacroName
7163 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007164 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7165 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007166 CodeCompletionBuilder Builder(Results.getAllocator(),
7167 Results.getCodeCompletionTUInfo());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007168 Results.EnterNewScope();
7169 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7170 MEnd = PP.macro_end();
7171 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00007172 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00007173 M->first->getName()));
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00007174 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7175 CCP_CodePattern,
7176 CXCursor_MacroDefinition));
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007177 }
7178 Results.ExitScope();
7179 } else if (IsDefinition) {
7180 // FIXME: Can we detect when the user just wrote an include guard above?
7181 }
7182
Douglas Gregor52779fb2010-09-23 23:01:17 +00007183 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007184 Results.data(), Results.size());
7185}
7186
Douglas Gregorf29c5232010-08-24 22:20:20 +00007187void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00007188 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007189 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007190 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00007191
7192 if (!CodeCompleter || CodeCompleter->includeMacros())
7193 AddMacroResults(PP, Results);
7194
7195 // defined (<macro>)
7196 Results.EnterNewScope();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007197 CodeCompletionBuilder Builder(Results.getAllocator(),
7198 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00007199 Builder.AddTypedTextChunk("defined");
7200 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7201 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7202 Builder.AddPlaceholderChunk("macro");
7203 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7204 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00007205 Results.ExitScope();
7206
7207 HandleCodeCompleteResults(this, CodeCompleter,
7208 CodeCompletionContext::CCC_PreprocessorExpression,
7209 Results.data(), Results.size());
7210}
7211
7212void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7213 IdentifierInfo *Macro,
7214 MacroInfo *MacroInfo,
7215 unsigned Argument) {
7216 // FIXME: In the future, we could provide "overload" results, much like we
7217 // do for function calls.
7218
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00007219 // Now just ignore this. There will be another code-completion callback
7220 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00007221}
7222
Douglas Gregor55817af2010-08-25 17:04:25 +00007223void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00007224 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00007225 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00007226 0, 0);
7227}
7228
Douglas Gregordae68752011-02-01 22:57:45 +00007229void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007230 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner5f9e2722011-07-23 10:55:15 +00007231 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007232 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7233 CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00007234 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7235 CodeCompletionDeclConsumer Consumer(Builder,
7236 Context.getTranslationUnitDecl());
7237 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7238 Consumer);
7239 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00007240
7241 if (!CodeCompleter || CodeCompleter->includeMacros())
7242 AddMacroResults(PP, Builder);
7243
7244 Results.clear();
7245 Results.insert(Results.end(),
7246 Builder.data(), Builder.data() + Builder.size());
7247}