blob: 1fc5d8f2cea5d360efe92be5881b40edea9f01f9 [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 }
Douglas Gregor352697a2011-06-03 23:08:58 +00002885
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002886 default:
2887 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2888 switch (TD->getTagKind()) {
Joao Matos6666ed42012-08-31 18:45:21 +00002889 case TTK_Interface: // fall through
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002890 case TTK_Struct: return CXCursor_StructDecl;
2891 case TTK_Class: return CXCursor_ClassDecl;
2892 case TTK_Union: return CXCursor_UnionDecl;
2893 case TTK_Enum: return CXCursor_EnumDecl;
2894 }
2895 }
2896 }
2897
2898 return CXCursor_UnexposedDecl;
2899}
2900
Douglas Gregor590c7d52010-07-08 20:55:51 +00002901static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2902 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002903 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002904
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002905 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002906
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002907 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2908 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002909 M != MEnd; ++M) {
Alexander Kornienko8a64bb52012-08-29 00:20:03 +00002910 // FIXME: Eventually, we'd want to be able to look back to the macro
2911 // definition that was actually active at the point of code completion (even
2912 // if that macro has since been #undef'd).
2913 if (M->first->hasMacroDefinition())
2914 Results.AddResult(Result(M->first,
Douglas Gregor1827e102010-08-16 16:18:59 +00002915 getMacroUsagePriority(M->first->getName(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002916 PP.getLangOpts(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002917 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002918 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002919
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002920 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002921
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002922}
2923
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002924static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2925 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002926 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002927
2928 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002929
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002930 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2931 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2932 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2933 Results.AddResult(Result("__func__", CCP_Constant));
2934 Results.ExitScope();
2935}
2936
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002937static void HandleCodeCompleteResults(Sema *S,
2938 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002939 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002940 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002941 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002942 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002943 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002944}
2945
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002946static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2947 Sema::ParserCompletionContext PCC) {
2948 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002949 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002950 return CodeCompletionContext::CCC_TopLevel;
2951
John McCallf312b1e2010-08-26 23:41:50 +00002952 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002953 return CodeCompletionContext::CCC_ClassStructUnion;
2954
John McCallf312b1e2010-08-26 23:41:50 +00002955 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002956 return CodeCompletionContext::CCC_ObjCInterface;
2957
John McCallf312b1e2010-08-26 23:41:50 +00002958 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002959 return CodeCompletionContext::CCC_ObjCImplementation;
2960
John McCallf312b1e2010-08-26 23:41:50 +00002961 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002962 return CodeCompletionContext::CCC_ObjCIvarList;
2963
John McCallf312b1e2010-08-26 23:41:50 +00002964 case Sema::PCC_Template:
2965 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002966 if (S.CurContext->isFileContext())
2967 return CodeCompletionContext::CCC_TopLevel;
David Blaikie7530c032012-01-17 06:56:22 +00002968 if (S.CurContext->isRecord())
Douglas Gregor52779fb2010-09-23 23:01:17 +00002969 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie7530c032012-01-17 06:56:22 +00002970 return CodeCompletionContext::CCC_Other;
Douglas Gregor52779fb2010-09-23 23:01:17 +00002971
John McCallf312b1e2010-08-26 23:41:50 +00002972 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002973 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002974
John McCallf312b1e2010-08-26 23:41:50 +00002975 case Sema::PCC_ForInit:
David Blaikie4e4d0842012-03-11 07:00:24 +00002976 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
2977 S.getLangOpts().ObjC1)
Douglas Gregora5450a02010-10-18 22:01:46 +00002978 return CodeCompletionContext::CCC_ParenthesizedExpression;
2979 else
2980 return CodeCompletionContext::CCC_Expression;
2981
2982 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002983 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002984 return CodeCompletionContext::CCC_Expression;
2985
John McCallf312b1e2010-08-26 23:41:50 +00002986 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002987 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002988
John McCallf312b1e2010-08-26 23:41:50 +00002989 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002990 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002991
2992 case Sema::PCC_ParenthesizedExpression:
2993 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002994
2995 case Sema::PCC_LocalDeclarationSpecifiers:
2996 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002997 }
David Blaikie7530c032012-01-17 06:56:22 +00002998
2999 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003000}
3001
Douglas Gregorf6961522010-08-27 21:18:54 +00003002/// \brief If we're in a C++ virtual member function, add completion results
3003/// that invoke the functions we override, since it's common to invoke the
3004/// overridden function as well as adding new functionality.
3005///
3006/// \param S The semantic analysis object for which we are generating results.
3007///
3008/// \param InContext This context in which the nested-name-specifier preceding
3009/// the code-completion point
3010static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3011 ResultBuilder &Results) {
3012 // Look through blocks.
3013 DeclContext *CurContext = S.CurContext;
3014 while (isa<BlockDecl>(CurContext))
3015 CurContext = CurContext->getParent();
3016
3017
3018 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3019 if (!Method || !Method->isVirtual())
3020 return;
3021
3022 // We need to have names for all of the parameters, if we're going to
3023 // generate a forwarding call.
3024 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3025 PEnd = Method->param_end();
3026 P != PEnd;
3027 ++P) {
3028 if (!(*P)->getDeclName())
3029 return;
3030 }
3031
Douglas Gregor8987b232011-09-27 23:30:47 +00003032 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00003033 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3034 MEnd = Method->end_overridden_methods();
3035 M != MEnd; ++M) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003036 CodeCompletionBuilder Builder(Results.getAllocator(),
3037 Results.getCodeCompletionTUInfo());
Douglas Gregorf6961522010-08-27 21:18:54 +00003038 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
3039 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3040 continue;
3041
3042 // If we need a nested-name-specifier, add one now.
3043 if (!InContext) {
3044 NestedNameSpecifier *NNS
3045 = getRequiredQualification(S.Context, CurContext,
3046 Overridden->getDeclContext());
3047 if (NNS) {
3048 std::string Str;
3049 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00003050 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003051 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003052 }
3053 } else if (!InContext->Equals(Overridden->getDeclContext()))
3054 continue;
3055
Douglas Gregordae68752011-02-01 22:57:45 +00003056 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003057 Overridden->getNameAsString()));
3058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003059 bool FirstParam = true;
3060 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3061 PEnd = Method->param_end();
3062 P != PEnd; ++P) {
3063 if (FirstParam)
3064 FirstParam = false;
3065 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003066 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003067
Douglas Gregordae68752011-02-01 22:57:45 +00003068 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003069 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003070 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003071 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3072 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003073 CCP_SuperCompletion,
Douglas Gregorba103062012-03-27 23:34:16 +00003074 CXCursor_CXXMethod,
3075 CXAvailability_Available,
3076 Overridden));
Douglas Gregorf6961522010-08-27 21:18:54 +00003077 Results.Ignore(Overridden);
3078 }
3079}
3080
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003081void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3082 ModuleIdPath Path) {
3083 typedef CodeCompletionResult Result;
3084 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003085 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003086 CodeCompletionContext::CCC_Other);
3087 Results.EnterNewScope();
3088
3089 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003090 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorc5b2e582012-01-29 18:15:03 +00003091 typedef CodeCompletionResult Result;
3092 if (Path.empty()) {
3093 // Enumerate all top-level modules.
3094 llvm::SmallVector<Module *, 8> Modules;
3095 PP.getHeaderSearchInfo().collectAllModules(Modules);
3096 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3097 Builder.AddTypedTextChunk(
3098 Builder.getAllocator().CopyString(Modules[I]->Name));
3099 Results.AddResult(Result(Builder.TakeString(),
3100 CCP_Declaration,
3101 CXCursor_NotImplemented,
3102 Modules[I]->isAvailable()
3103 ? CXAvailability_Available
3104 : CXAvailability_NotAvailable));
3105 }
3106 } else {
3107 // Load the named module.
3108 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3109 Module::AllVisible,
3110 /*IsInclusionDirective=*/false);
3111 // Enumerate submodules.
3112 if (Mod) {
3113 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3114 SubEnd = Mod->submodule_end();
3115 Sub != SubEnd; ++Sub) {
3116
3117 Builder.AddTypedTextChunk(
3118 Builder.getAllocator().CopyString((*Sub)->Name));
3119 Results.AddResult(Result(Builder.TakeString(),
3120 CCP_Declaration,
3121 CXCursor_NotImplemented,
3122 (*Sub)->isAvailable()
3123 ? CXAvailability_Available
3124 : CXAvailability_NotAvailable));
3125 }
3126 }
3127 }
3128 Results.ExitScope();
3129 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3130 Results.data(),Results.size());
3131}
3132
Douglas Gregor01dfea02010-01-10 23:08:15 +00003133void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003134 ParserCompletionContext CompletionContext) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003135 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003136 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003137 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003138 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003139
Douglas Gregor01dfea02010-01-10 23:08:15 +00003140 // Determine how to filter results, e.g., so that the names of
3141 // values (functions, enumerators, function templates, etc.) are
3142 // only allowed where we can have an expression.
3143 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003144 case PCC_Namespace:
3145 case PCC_Class:
3146 case PCC_ObjCInterface:
3147 case PCC_ObjCImplementation:
3148 case PCC_ObjCInstanceVariableList:
3149 case PCC_Template:
3150 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003151 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003152 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003153 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3154 break;
3155
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003156 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003157 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003158 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003159 case PCC_ForInit:
3160 case PCC_Condition:
David Blaikie4e4d0842012-03-11 07:00:24 +00003161 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003162 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3163 else
3164 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003165
David Blaikie4e4d0842012-03-11 07:00:24 +00003166 if (getLangOpts().CPlusPlus)
Douglas Gregorf6961522010-08-27 21:18:54 +00003167 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003168 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003169
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003170 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003171 // Unfiltered
3172 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003173 }
3174
Douglas Gregor3cdee122010-08-26 16:36:48 +00003175 // If we are in a C++ non-static member function, check the qualifiers on
3176 // the member function to filter/prioritize the results list.
3177 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3178 if (CurMethod->isInstance())
3179 Results.setObjectTypeQualifiers(
3180 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3181
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003182 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003183 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3184 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003185
Douglas Gregorbca403c2010-01-13 23:51:12 +00003186 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003187 Results.ExitScope();
3188
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003189 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003190 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003191 case PCC_Expression:
3192 case PCC_Statement:
3193 case PCC_RecoveryInFunction:
3194 if (S->getFnParent())
David Blaikie4e4d0842012-03-11 07:00:24 +00003195 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor72db1082010-08-24 01:11:00 +00003196 break;
3197
3198 case PCC_Namespace:
3199 case PCC_Class:
3200 case PCC_ObjCInterface:
3201 case PCC_ObjCImplementation:
3202 case PCC_ObjCInstanceVariableList:
3203 case PCC_Template:
3204 case PCC_MemberTemplate:
3205 case PCC_ForInit:
3206 case PCC_Condition:
3207 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003208 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003209 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003210 }
3211
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003212 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003213 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003214
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003215 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003216 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003217}
3218
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003219static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3220 ParsedType Receiver,
3221 IdentifierInfo **SelIdents,
3222 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003223 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003224 bool IsSuper,
3225 ResultBuilder &Results);
3226
3227void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3228 bool AllowNonIdentifiers,
3229 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003230 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003231 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003232 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003233 AllowNestedNameSpecifiers
3234 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3235 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003236 Results.EnterNewScope();
3237
3238 // Type qualifiers can come after names.
3239 Results.AddResult(Result("const"));
3240 Results.AddResult(Result("volatile"));
David Blaikie4e4d0842012-03-11 07:00:24 +00003241 if (getLangOpts().C99)
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003242 Results.AddResult(Result("restrict"));
3243
David Blaikie4e4d0842012-03-11 07:00:24 +00003244 if (getLangOpts().CPlusPlus) {
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003245 if (AllowNonIdentifiers) {
3246 Results.AddResult(Result("operator"));
3247 }
3248
3249 // Add nested-name-specifiers.
3250 if (AllowNestedNameSpecifiers) {
3251 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003252 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003253 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3254 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3255 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003256 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003257 }
3258 }
3259 Results.ExitScope();
3260
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003261 // If we're in a context where we might have an expression (rather than a
3262 // declaration), and what we've seen so far is an Objective-C type that could
3263 // be a receiver of a class message, this may be a class message send with
3264 // the initial opening bracket '[' missing. Add appropriate completions.
3265 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3266 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3267 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3268 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3269 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3270 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3271 DS.getTypeQualifiers() == 0 &&
3272 S &&
3273 (S->getFlags() & Scope::DeclScope) != 0 &&
3274 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3275 Scope::FunctionPrototypeScope |
3276 Scope::AtCatchScope)) == 0) {
3277 ParsedType T = DS.getRepAsType();
3278 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003279 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003280 }
3281
Douglas Gregor4497dd42010-08-24 04:59:56 +00003282 // Note that we intentionally suppress macro results here, since we do not
3283 // encourage using macros to produce the names of entities.
3284
Douglas Gregor52779fb2010-09-23 23:01:17 +00003285 HandleCodeCompleteResults(this, CodeCompleter,
3286 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003287 Results.data(), Results.size());
3288}
3289
Douglas Gregorfb629412010-08-23 21:17:50 +00003290struct Sema::CodeCompleteExpressionData {
3291 CodeCompleteExpressionData(QualType PreferredType = QualType())
3292 : PreferredType(PreferredType), IntegralConstantExpression(false),
3293 ObjCCollection(false) { }
3294
3295 QualType PreferredType;
3296 bool IntegralConstantExpression;
3297 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003298 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003299};
3300
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003301/// \brief Perform code-completion in an expression context when we know what
3302/// type we're looking for.
Douglas Gregorfb629412010-08-23 21:17:50 +00003303void Sema::CodeCompleteExpression(Scope *S,
3304 const CodeCompleteExpressionData &Data) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003305 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003306 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003307 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003308 if (Data.ObjCCollection)
3309 Results.setFilter(&ResultBuilder::IsObjCCollection);
3310 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003311 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikie4e4d0842012-03-11 07:00:24 +00003312 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003313 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3314 else
3315 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003316
3317 if (!Data.PreferredType.isNull())
3318 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3319
3320 // Ignore any declarations that we were told that we don't care about.
3321 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3322 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003323
3324 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003325 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3326 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003327
3328 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003329 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003330 Results.ExitScope();
3331
Douglas Gregor590c7d52010-07-08 20:55:51 +00003332 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003333 if (!Data.PreferredType.isNull())
3334 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3335 || Data.PreferredType->isMemberPointerType()
3336 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003337
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003338 if (S->getFnParent() &&
3339 !Data.ObjCCollection &&
3340 !Data.IntegralConstantExpression)
David Blaikie4e4d0842012-03-11 07:00:24 +00003341 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003342
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003343 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003344 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003345 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003346 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3347 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003348 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003349}
3350
Douglas Gregorac5fd842010-09-18 01:28:11 +00003351void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3352 if (E.isInvalid())
3353 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikie4e4d0842012-03-11 07:00:24 +00003354 else if (getLangOpts().ObjC1)
Douglas Gregorac5fd842010-09-18 01:28:11 +00003355 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003356}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003357
Douglas Gregor73449212010-12-09 23:01:55 +00003358/// \brief The set of properties that have already been added, referenced by
3359/// property name.
3360typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3361
Douglas Gregorb92a4082012-06-12 13:44:08 +00003362/// \brief Retrieve the container definition, if any?
3363static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3364 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3365 if (Interface->hasDefinition())
3366 return Interface->getDefinition();
3367
3368 return Interface;
3369 }
3370
3371 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3372 if (Protocol->hasDefinition())
3373 return Protocol->getDefinition();
3374
3375 return Protocol;
3376 }
3377 return Container;
3378}
3379
3380static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003381 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003382 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003383 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003384 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003385 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003386 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003387
Douglas Gregorb92a4082012-06-12 13:44:08 +00003388 // Retrieve the definition.
3389 Container = getContainerDef(Container);
3390
Douglas Gregor95ac6552009-11-18 01:29:26 +00003391 // Add properties in this container.
3392 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3393 PEnd = Container->prop_end();
3394 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003395 ++P) {
3396 if (AddedProperties.insert(P->getIdentifier()))
David Blaikie581deb32012-06-06 20:45:41 +00003397 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor73449212010-12-09 23:01:55 +00003398 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003399
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003400 // Add nullary methods
3401 if (AllowNullaryMethods) {
3402 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003403 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003404 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3405 MEnd = Container->meth_end();
3406 M != MEnd; ++M) {
3407 if (M->getSelector().isUnarySelector())
3408 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3409 if (AddedProperties.insert(Name)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003410 CodeCompletionBuilder Builder(Results.getAllocator(),
3411 Results.getCodeCompletionTUInfo());
David Blaikie581deb32012-06-06 20:45:41 +00003412 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003413 Builder.AddTypedTextChunk(
3414 Results.getAllocator().CopyString(Name->getName()));
3415
David Blaikie581deb32012-06-06 20:45:41 +00003416 Results.MaybeAddResult(Result(Builder.TakeString(), *M,
Douglas Gregorba103062012-03-27 23:34:16 +00003417 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003418 CurContext);
3419 }
3420 }
3421 }
3422
3423
Douglas Gregor95ac6552009-11-18 01:29:26 +00003424 // Add properties in referenced protocols.
3425 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3426 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3427 PEnd = Protocol->protocol_end();
3428 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003429 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3430 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003431 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003432 if (AllowCategories) {
3433 // Look through categories.
3434 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3435 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003436 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3437 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003438 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003439
3440 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003441 for (ObjCInterfaceDecl::all_protocol_iterator
3442 I = IFace->all_referenced_protocol_begin(),
3443 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003444 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3445 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003446
3447 // Look in the superclass.
3448 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003449 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3450 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003451 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003452 } else if (const ObjCCategoryDecl *Category
3453 = dyn_cast<ObjCCategoryDecl>(Container)) {
3454 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003455 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3456 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003457 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003458 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3459 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003460 }
3461}
3462
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003463void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003464 SourceLocation OpLoc,
3465 bool IsArrow) {
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003466 if (!Base || !CodeCompleter)
Douglas Gregor81b747b2009-09-17 21:32:03 +00003467 return;
3468
Douglas Gregorf5cd27d2012-01-23 15:59:30 +00003469 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3470 if (ConvertedBase.isInvalid())
3471 return;
3472 Base = ConvertedBase.get();
3473
John McCall0a2c5e22010-08-25 06:19:51 +00003474 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003475
Douglas Gregor81b747b2009-09-17 21:32:03 +00003476 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003477
3478 if (IsArrow) {
3479 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3480 BaseType = Ptr->getPointeeType();
3481 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003482 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003483 else
3484 return;
3485 }
3486
Douglas Gregor3da626b2011-07-07 16:03:39 +00003487 enum CodeCompletionContext::Kind contextKind;
3488
3489 if (IsArrow) {
3490 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3491 }
3492 else {
3493 if (BaseType->isObjCObjectPointerType() ||
3494 BaseType->isObjCObjectOrInterfaceType()) {
3495 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3496 }
3497 else {
3498 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3499 }
3500 }
3501
Douglas Gregor218937c2011-02-01 19:23:04 +00003502 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003503 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003504 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003505 BaseType),
3506 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003507 Results.EnterNewScope();
3508 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003509 // Indicate that we are performing a member access, and the cv-qualifiers
3510 // for the base object type.
3511 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3512
Douglas Gregor95ac6552009-11-18 01:29:26 +00003513 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003514 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003515 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003516 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3517 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003518
David Blaikie4e4d0842012-03-11 07:00:24 +00003519 if (getLangOpts().CPlusPlus) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003520 if (!Results.empty()) {
3521 // The "template" keyword can follow "->" or "." in the grammar.
3522 // However, we only want to suggest the template keyword if something
3523 // is dependent.
3524 bool IsDependent = BaseType->isDependentType();
3525 if (!IsDependent) {
3526 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3527 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3528 IsDependent = Ctx->isDependentContext();
3529 break;
3530 }
3531 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003532
Douglas Gregor95ac6552009-11-18 01:29:26 +00003533 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003534 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003535 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003536 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003537 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3538 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003539 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003540
3541 // Add property results based on our interface.
3542 const ObjCObjectPointerType *ObjCPtr
3543 = BaseType->getAsObjCInterfacePointerType();
3544 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003545 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3546 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003547 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003548
3549 // Add properties from the protocols in a qualified interface.
3550 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3551 E = ObjCPtr->qual_end();
3552 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003553 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3554 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003555 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003556 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003557 // Objective-C instance variable access.
3558 ObjCInterfaceDecl *Class = 0;
3559 if (const ObjCObjectPointerType *ObjCPtr
3560 = BaseType->getAs<ObjCObjectPointerType>())
3561 Class = ObjCPtr->getInterfaceDecl();
3562 else
John McCallc12c5bb2010-05-15 11:32:37 +00003563 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003564
3565 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003566 if (Class) {
3567 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3568 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003569 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3570 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003571 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003572 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003573
3574 // FIXME: How do we cope with isa?
3575
3576 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003577
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003578 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003579 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003580 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003581 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003582}
3583
Douglas Gregor374929f2009-09-18 15:37:17 +00003584void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3585 if (!CodeCompleter)
3586 return;
3587
Douglas Gregor86d9a522009-09-21 16:56:56 +00003588 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003589 enum CodeCompletionContext::Kind ContextKind
3590 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003591 switch ((DeclSpec::TST)TagSpec) {
3592 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003593 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003594 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003595 break;
3596
3597 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003598 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003599 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003600 break;
3601
3602 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003603 case DeclSpec::TST_class:
Joao Matos6666ed42012-08-31 18:45:21 +00003604 case DeclSpec::TST_interface:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003605 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003606 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003607 break;
3608
3609 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003610 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003611 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003612
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003613 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3614 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003615 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003616
3617 // First pass: look for tags.
3618 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003619 LookupVisibleDecls(S, LookupTagName, Consumer,
3620 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003621
Douglas Gregor8071e422010-08-15 06:18:01 +00003622 if (CodeCompleter->includeGlobals()) {
3623 // Second pass: look for nested name specifiers.
3624 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3625 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3626 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003627
Douglas Gregor52779fb2010-09-23 23:01:17 +00003628 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003629 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003630}
3631
Douglas Gregor1a480c42010-08-27 17:35:51 +00003632void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003633 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003634 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003635 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003636 Results.EnterNewScope();
3637 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3638 Results.AddResult("const");
3639 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3640 Results.AddResult("volatile");
David Blaikie4e4d0842012-03-11 07:00:24 +00003641 if (getLangOpts().C99 &&
Douglas Gregor1a480c42010-08-27 17:35:51 +00003642 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3643 Results.AddResult("restrict");
3644 Results.ExitScope();
3645 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003646 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003647 Results.data(), Results.size());
3648}
3649
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003650void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003651 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003652 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003653
John McCall781472f2010-08-25 08:40:02 +00003654 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003655 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3656 if (!type->isEnumeralType()) {
3657 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003658 Data.IntegralConstantExpression = true;
3659 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003660 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003661 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003662
3663 // Code-complete the cases of a switch statement over an enumeration type
3664 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003665 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregorb92a4082012-06-12 13:44:08 +00003666 if (EnumDecl *Def = Enum->getDefinition())
3667 Enum = Def;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003668
3669 // Determine which enumerators we have already seen in the switch statement.
3670 // FIXME: Ideally, we would also be able to look *past* the code-completion
3671 // token, in case we are code-completing in the middle of the switch and not
3672 // at the end. However, we aren't able to do so at the moment.
3673 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003674 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003675 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3676 SC = SC->getNextSwitchCase()) {
3677 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3678 if (!Case)
3679 continue;
3680
3681 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3682 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3683 if (EnumConstantDecl *Enumerator
3684 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3685 // We look into the AST of the case statement to determine which
3686 // enumerator was named. Alternatively, we could compute the value of
3687 // the integral constant expression, then compare it against the
3688 // values of each enumerator. However, value-based approach would not
3689 // work as well with C++ templates where enumerators declared within a
3690 // template are type- and value-dependent.
3691 EnumeratorsSeen.insert(Enumerator);
3692
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003693 // If this is a qualified-id, keep track of the nested-name-specifier
3694 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003695 //
3696 // switch (TagD.getKind()) {
3697 // case TagDecl::TK_enum:
3698 // break;
3699 // case XXX
3700 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003701 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003702 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3703 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003704 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003705 }
3706 }
3707
David Blaikie4e4d0842012-03-11 07:00:24 +00003708 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003709 // If there are no prior enumerators in C++, check whether we have to
3710 // qualify the names of the enumerators that we suggest, because they
3711 // may not be visible in this scope.
Douglas Gregorb223d8c2012-02-01 05:02:47 +00003712 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003713 }
3714
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003715 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003716 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003717 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003718 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003719 Results.EnterNewScope();
3720 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3721 EEnd = Enum->enumerator_end();
3722 E != EEnd; ++E) {
David Blaikie581deb32012-06-06 20:45:41 +00003723 if (EnumeratorsSeen.count(*E))
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003724 continue;
3725
David Blaikie581deb32012-06-06 20:45:41 +00003726 CodeCompletionResult R(*E, Qualifier);
Douglas Gregor5c722c702011-02-18 23:30:37 +00003727 R.Priority = CCP_EnumInCase;
3728 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003729 }
3730 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003731
Douglas Gregor3da626b2011-07-07 16:03:39 +00003732 //We need to make sure we're setting the right context,
3733 //so only say we include macros if the code completer says we do
3734 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3735 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003736 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003737 kind = CodeCompletionContext::CCC_OtherWithMacros;
3738 }
3739
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003740 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003741 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003742 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003743}
3744
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003745namespace {
3746 struct IsBetterOverloadCandidate {
3747 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003748 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003749
3750 public:
John McCall5769d612010-02-08 23:07:23 +00003751 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3752 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003753
3754 bool
3755 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003756 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003757 }
3758 };
3759}
3760
Ahmed Charles13a140c2012-02-25 11:00:22 +00003761static bool anyNullArguments(llvm::ArrayRef<Expr*> Args) {
3762 if (Args.size() && !Args.data())
Douglas Gregord28dcd72010-05-30 06:10:08 +00003763 return true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003764
3765 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregord28dcd72010-05-30 06:10:08 +00003766 if (!Args[I])
3767 return true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003768
Douglas Gregord28dcd72010-05-30 06:10:08 +00003769 return false;
3770}
3771
Richard Trieuf81e5a92011-09-09 02:00:50 +00003772void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003773 llvm::ArrayRef<Expr *> Args) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003774 if (!CodeCompleter)
3775 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003776
3777 // When we're code-completing for a call, we fall back to ordinary
3778 // name code-completion whenever we can't produce specific
3779 // results. We may want to revisit this strategy in the future,
3780 // e.g., by merging the two kinds of results.
3781
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003782 Expr *Fn = (Expr *)FnIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003783
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003784 // Ignore type-dependent call expressions entirely.
Ahmed Charles13a140c2012-02-25 11:00:22 +00003785 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3786 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003787 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003788 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003789 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003790
John McCall3b4294e2009-12-16 12:17:52 +00003791 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003792 SourceLocation Loc = Fn->getExprLoc();
3793 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003794
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003795 // FIXME: What if we're calling something that isn't a function declaration?
3796 // FIXME: What if we're calling a pseudo-destructor?
3797 // FIXME: What if we're calling a member function?
3798
Douglas Gregorc0265402010-01-21 15:46:19 +00003799 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003800 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003801
John McCall3b4294e2009-12-16 12:17:52 +00003802 Expr *NakedFn = Fn->IgnoreParenCasts();
3803 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charles13a140c2012-02-25 11:00:22 +00003804 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
John McCall3b4294e2009-12-16 12:17:52 +00003805 /*PartialOverloading=*/ true);
3806 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3807 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003808 if (FDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003809 if (!getLangOpts().CPlusPlus ||
Douglas Gregord28dcd72010-05-30 06:10:08 +00003810 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003811 Results.push_back(ResultCandidate(FDecl));
3812 else
John McCall86820f52010-01-26 01:37:31 +00003813 // FIXME: access?
Ahmed Charles13a140c2012-02-25 11:00:22 +00003814 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
3815 CandidateSet, false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003816 }
John McCall3b4294e2009-12-16 12:17:52 +00003817 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003818
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003819 QualType ParamType;
3820
Douglas Gregorc0265402010-01-21 15:46:19 +00003821 if (!CandidateSet.empty()) {
3822 // Sort the overload candidate set by placing the best overloads first.
3823 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003824 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003825
Douglas Gregorc0265402010-01-21 15:46:19 +00003826 // Add the remaining viable overload candidates as code-completion reslults.
3827 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3828 CandEnd = CandidateSet.end();
3829 Cand != CandEnd; ++Cand) {
3830 if (Cand->Viable)
3831 Results.push_back(ResultCandidate(Cand->Function));
3832 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003833
3834 // From the viable candidates, try to determine the type of this parameter.
3835 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3836 if (const FunctionType *FType = Results[I].getFunctionType())
3837 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
Ahmed Charles13a140c2012-02-25 11:00:22 +00003838 if (Args.size() < Proto->getNumArgs()) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003839 if (ParamType.isNull())
Ahmed Charles13a140c2012-02-25 11:00:22 +00003840 ParamType = Proto->getArgType(Args.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003841 else if (!Context.hasSameUnqualifiedType(
3842 ParamType.getNonReferenceType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00003843 Proto->getArgType(Args.size()).getNonReferenceType())) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003844 ParamType = QualType();
3845 break;
3846 }
3847 }
3848 }
3849 } else {
3850 // Try to determine the parameter type from the type of the expression
3851 // being called.
3852 QualType FunctionType = Fn->getType();
3853 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3854 FunctionType = Ptr->getPointeeType();
3855 else if (const BlockPointerType *BlockPtr
3856 = FunctionType->getAs<BlockPointerType>())
3857 FunctionType = BlockPtr->getPointeeType();
3858 else if (const MemberPointerType *MemPtr
3859 = FunctionType->getAs<MemberPointerType>())
3860 FunctionType = MemPtr->getPointeeType();
3861
3862 if (const FunctionProtoType *Proto
3863 = FunctionType->getAs<FunctionProtoType>()) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00003864 if (Args.size() < Proto->getNumArgs())
3865 ParamType = Proto->getArgType(Args.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003866 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003867 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003868
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003869 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003870 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003871 else
3872 CodeCompleteExpression(S, ParamType);
3873
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003874 if (!Results.empty())
Ahmed Charles13a140c2012-02-25 11:00:22 +00003875 CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
Douglas Gregoref96eac2009-12-11 19:06:04 +00003876 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003877}
3878
John McCalld226f652010-08-21 09:40:31 +00003879void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3880 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003881 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003882 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003883 return;
3884 }
3885
3886 CodeCompleteExpression(S, VD->getType());
3887}
3888
3889void Sema::CodeCompleteReturn(Scope *S) {
3890 QualType ResultType;
3891 if (isa<BlockDecl>(CurContext)) {
3892 if (BlockScopeInfo *BSI = getCurBlock())
3893 ResultType = BSI->ReturnType;
3894 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3895 ResultType = Function->getResultType();
3896 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3897 ResultType = Method->getResultType();
3898
3899 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003900 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003901 else
3902 CodeCompleteExpression(S, ResultType);
3903}
3904
Douglas Gregord2d8be62011-07-30 08:36:53 +00003905void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregord2d8be62011-07-30 08:36:53 +00003906 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003907 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord2d8be62011-07-30 08:36:53 +00003908 mapCodeCompletionContext(*this, PCC_Statement));
3909 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3910 Results.EnterNewScope();
3911
3912 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3913 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3914 CodeCompleter->includeGlobals());
3915
3916 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3917
3918 // "else" block
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003919 CodeCompletionBuilder Builder(Results.getAllocator(),
3920 Results.getCodeCompletionTUInfo());
Douglas Gregord2d8be62011-07-30 08:36:53 +00003921 Builder.AddTypedTextChunk("else");
Douglas Gregorf11641a2012-02-16 17:49:04 +00003922 if (Results.includeCodePatterns()) {
3923 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3924 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3925 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3926 Builder.AddPlaceholderChunk("statements");
3927 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3928 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3929 }
Douglas Gregord2d8be62011-07-30 08:36:53 +00003930 Results.AddResult(Builder.TakeString());
3931
3932 // "else if" block
3933 Builder.AddTypedTextChunk("else");
3934 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3935 Builder.AddTextChunk("if");
3936 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3937 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikie4e4d0842012-03-11 07:00:24 +00003938 if (getLangOpts().CPlusPlus)
Douglas Gregord2d8be62011-07-30 08:36:53 +00003939 Builder.AddPlaceholderChunk("condition");
3940 else
3941 Builder.AddPlaceholderChunk("expression");
3942 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf11641a2012-02-16 17:49:04 +00003943 if (Results.includeCodePatterns()) {
3944 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3945 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3946 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3947 Builder.AddPlaceholderChunk("statements");
3948 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3949 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3950 }
Douglas Gregord2d8be62011-07-30 08:36:53 +00003951 Results.AddResult(Builder.TakeString());
3952
3953 Results.ExitScope();
3954
3955 if (S->getFnParent())
David Blaikie4e4d0842012-03-11 07:00:24 +00003956 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregord2d8be62011-07-30 08:36:53 +00003957
3958 if (CodeCompleter->includeMacros())
3959 AddMacroResults(PP, Results);
3960
3961 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3962 Results.data(),Results.size());
3963}
3964
Richard Trieuf81e5a92011-09-09 02:00:50 +00003965void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003966 if (LHS)
3967 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3968 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003969 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003970}
3971
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003972void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003973 bool EnteringContext) {
3974 if (!SS.getScopeRep() || !CodeCompleter)
3975 return;
3976
Douglas Gregor86d9a522009-09-21 16:56:56 +00003977 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3978 if (!Ctx)
3979 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003980
3981 // Try to instantiate any non-dependent declaration contexts before
3982 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003983 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003984 return;
3985
Douglas Gregor218937c2011-02-01 19:23:04 +00003986 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00003987 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00003988 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003989 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003990
Douglas Gregor86d9a522009-09-21 16:56:56 +00003991 // The "template" keyword can follow "::" in the grammar, but only
3992 // put it into the grammar if the nested-name-specifier is dependent.
3993 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3994 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003995 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003996
3997 // Add calls to overridden virtual functions, if there are any.
3998 //
3999 // FIXME: This isn't wonderful, because we don't know whether we're actually
4000 // in a context that permits expressions. This is a general issue with
4001 // qualified-id completions.
4002 if (!EnteringContext)
4003 MaybeAddOverrideCalls(*this, Ctx, Results);
4004 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004005
Douglas Gregorf6961522010-08-27 21:18:54 +00004006 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4007 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4008
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004009 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00004010 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004011 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00004012}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004013
4014void Sema::CodeCompleteUsing(Scope *S) {
4015 if (!CodeCompleter)
4016 return;
4017
Douglas Gregor218937c2011-02-01 19:23:04 +00004018 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004019 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004020 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4021 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004022 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004023
4024 // If we aren't in class scope, we could see the "namespace" keyword.
4025 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00004026 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004027
4028 // After "using", we can see anything that would start a
4029 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004030 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004031 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4032 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004033 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004034
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004035 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004036 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004037 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004038}
4039
4040void Sema::CodeCompleteUsingDirective(Scope *S) {
4041 if (!CodeCompleter)
4042 return;
4043
Douglas Gregor86d9a522009-09-21 16:56:56 +00004044 // After "using namespace", we expect to see a namespace name or namespace
4045 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004046 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004047 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004048 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004049 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004050 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004051 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004052 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4053 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004054 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004055 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004056 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004057 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004058}
4059
4060void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4061 if (!CodeCompleter)
4062 return;
4063
Douglas Gregor86d9a522009-09-21 16:56:56 +00004064 DeclContext *Ctx = (DeclContext *)S->getEntity();
4065 if (!S->getParent())
4066 Ctx = Context.getTranslationUnitDecl();
4067
Douglas Gregor52779fb2010-09-23 23:01:17 +00004068 bool SuppressedGlobalResults
4069 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4070
Douglas Gregor218937c2011-02-01 19:23:04 +00004071 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004072 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004073 SuppressedGlobalResults
4074 ? CodeCompletionContext::CCC_Namespace
4075 : CodeCompletionContext::CCC_Other,
4076 &ResultBuilder::IsNamespace);
4077
4078 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00004079 // We only want to see those namespaces that have already been defined
4080 // within this scope, because its likely that the user is creating an
4081 // extended namespace declaration. Keep track of the most recent
4082 // definition of each namespace.
4083 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4084 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4085 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4086 NS != NSEnd; ++NS)
David Blaikie581deb32012-06-06 20:45:41 +00004087 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004088
4089 // Add the most recent definition (or extended definition) of each
4090 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004091 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004092 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregorba103062012-03-27 23:34:16 +00004093 NS = OrigToLatest.begin(),
4094 NSEnd = OrigToLatest.end();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004095 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00004096 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00004097 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004098 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004099 }
4100
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004101 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004102 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004103 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004104}
4105
4106void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4107 if (!CodeCompleter)
4108 return;
4109
Douglas Gregor86d9a522009-09-21 16:56:56 +00004110 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004111 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004112 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004113 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004114 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004115 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004116 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4117 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004118 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004119 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004120 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004121}
4122
Douglas Gregored8d3222009-09-18 20:05:18 +00004123void Sema::CodeCompleteOperatorName(Scope *S) {
4124 if (!CodeCompleter)
4125 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004126
John McCall0a2c5e22010-08-25 06:19:51 +00004127 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004128 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004129 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004130 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004131 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004132 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004133
Douglas Gregor86d9a522009-09-21 16:56:56 +00004134 // Add the names of overloadable operators.
4135#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4136 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004137 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004138#include "clang/Basic/OperatorKinds.def"
4139
4140 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004141 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004142 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004143 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4144 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004145
4146 // Add any type specifiers
David Blaikie4e4d0842012-03-11 07:00:24 +00004147 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004148 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004149
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004150 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004151 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004152 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004153}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004154
Douglas Gregor0133f522010-08-28 00:00:50 +00004155void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004156 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004157 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004158 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004159 CXXConstructorDecl *Constructor
4160 = static_cast<CXXConstructorDecl *>(ConstructorD);
4161 if (!Constructor)
4162 return;
4163
Douglas Gregor218937c2011-02-01 19:23:04 +00004164 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004165 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004166 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004167 Results.EnterNewScope();
4168
4169 // Fill in any already-initialized fields or base classes.
4170 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4171 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4172 for (unsigned I = 0; I != NumInitializers; ++I) {
4173 if (Initializers[I]->isBaseInitializer())
4174 InitializedBases.insert(
4175 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4176 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004177 InitializedFields.insert(cast<FieldDecl>(
4178 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004179 }
4180
4181 // Add completions for base classes.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004182 CodeCompletionBuilder Builder(Results.getAllocator(),
4183 Results.getCodeCompletionTUInfo());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004184 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004185 CXXRecordDecl *ClassDecl = Constructor->getParent();
4186 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4187 BaseEnd = ClassDecl->bases_end();
4188 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004189 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4190 SawLastInitializer
4191 = NumInitializers > 0 &&
4192 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4193 Context.hasSameUnqualifiedType(Base->getType(),
4194 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004195 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004196 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004197
Douglas Gregor218937c2011-02-01 19:23:04 +00004198 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004199 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004200 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004201 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4202 Builder.AddPlaceholderChunk("args");
4203 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4204 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004205 SawLastInitializer? CCP_NextInitializer
4206 : CCP_MemberDeclaration));
4207 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004208 }
4209
4210 // Add completions for virtual base classes.
4211 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4212 BaseEnd = ClassDecl->vbases_end();
4213 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004214 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4215 SawLastInitializer
4216 = NumInitializers > 0 &&
4217 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4218 Context.hasSameUnqualifiedType(Base->getType(),
4219 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004220 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004221 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004222
Douglas Gregor218937c2011-02-01 19:23:04 +00004223 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004224 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004225 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4227 Builder.AddPlaceholderChunk("args");
4228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4229 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004230 SawLastInitializer? CCP_NextInitializer
4231 : CCP_MemberDeclaration));
4232 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004233 }
4234
4235 // Add completions for members.
4236 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4237 FieldEnd = ClassDecl->field_end();
4238 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004239 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4240 SawLastInitializer
4241 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004242 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
David Blaikie581deb32012-06-06 20:45:41 +00004243 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004244 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004245 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004246
4247 if (!Field->getDeclName())
4248 continue;
4249
Douglas Gregordae68752011-02-01 22:57:45 +00004250 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004251 Field->getIdentifier()->getName()));
4252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4253 Builder.AddPlaceholderChunk("args");
4254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4255 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004256 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004257 : CCP_MemberDeclaration,
Douglas Gregorba103062012-03-27 23:34:16 +00004258 CXCursor_MemberRef,
4259 CXAvailability_Available,
David Blaikie581deb32012-06-06 20:45:41 +00004260 *Field));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004261 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004262 }
4263 Results.ExitScope();
4264
Douglas Gregor52779fb2010-09-23 23:01:17 +00004265 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004266 Results.data(), Results.size());
4267}
4268
Douglas Gregor81f3bff2012-02-15 15:34:24 +00004269/// \brief Determine whether this scope denotes a namespace.
4270static bool isNamespaceScope(Scope *S) {
4271 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
4272 if (!DC)
4273 return false;
4274
4275 return DC->isFileContext();
4276}
4277
4278void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4279 bool AfterAmpersand) {
4280 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004281 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor81f3bff2012-02-15 15:34:24 +00004282 CodeCompletionContext::CCC_Other);
4283 Results.EnterNewScope();
4284
4285 // Note what has already been captured.
4286 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4287 bool IncludedThis = false;
4288 for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4289 CEnd = Intro.Captures.end();
4290 C != CEnd; ++C) {
4291 if (C->Kind == LCK_This) {
4292 IncludedThis = true;
4293 continue;
4294 }
4295
4296 Known.insert(C->Id);
4297 }
4298
4299 // Look for other capturable variables.
4300 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4301 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4302 D != DEnd; ++D) {
4303 VarDecl *Var = dyn_cast<VarDecl>(*D);
4304 if (!Var ||
4305 !Var->hasLocalStorage() ||
4306 Var->hasAttr<BlocksAttr>())
4307 continue;
4308
4309 if (Known.insert(Var->getIdentifier()))
4310 Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
4311 }
4312 }
4313
4314 // Add 'this', if it would be valid.
4315 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4316 addThisCompletion(*this, Results);
4317
4318 Results.ExitScope();
4319
4320 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4321 Results.data(), Results.size());
4322}
4323
James Dennetta40f7922012-06-14 03:11:41 +00004324/// Macro that optionally prepends an "@" to the string literal passed in via
4325/// Keyword, depending on whether NeedAt is true or false.
4326#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4327
Douglas Gregorbca403c2010-01-13 23:51:12 +00004328static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004329 ResultBuilder &Results,
4330 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004331 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004332 // Since we have an implementation, we can end it.
James Dennetta40f7922012-06-14 03:11:41 +00004333 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004334
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004335 CodeCompletionBuilder Builder(Results.getAllocator(),
4336 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004337 if (LangOpts.ObjC2) {
4338 // @dynamic
James Dennetta40f7922012-06-14 03:11:41 +00004339 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4341 Builder.AddPlaceholderChunk("property");
4342 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004343
4344 // @synthesize
James Dennetta40f7922012-06-14 03:11:41 +00004345 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004346 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4347 Builder.AddPlaceholderChunk("property");
4348 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004349 }
4350}
4351
Douglas Gregorbca403c2010-01-13 23:51:12 +00004352static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004353 ResultBuilder &Results,
4354 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004355 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004356
4357 // Since we have an interface or protocol, we can end it.
James Dennetta40f7922012-06-14 03:11:41 +00004358 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004359
4360 if (LangOpts.ObjC2) {
4361 // @property
James Dennetta40f7922012-06-14 03:11:41 +00004362 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004363
4364 // @required
James Dennetta40f7922012-06-14 03:11:41 +00004365 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004366
4367 // @optional
James Dennetta40f7922012-06-14 03:11:41 +00004368 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004369 }
4370}
4371
Douglas Gregorbca403c2010-01-13 23:51:12 +00004372static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004373 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004374 CodeCompletionBuilder Builder(Results.getAllocator(),
4375 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004376
4377 // @class name ;
James Dennetta40f7922012-06-14 03:11:41 +00004378 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4380 Builder.AddPlaceholderChunk("name");
4381 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004382
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004383 if (Results.includeCodePatterns()) {
4384 // @interface name
4385 // FIXME: Could introduce the whole pattern, including superclasses and
4386 // such.
James Dennetta40f7922012-06-14 03:11:41 +00004387 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004388 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4389 Builder.AddPlaceholderChunk("class");
4390 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004391
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004392 // @protocol name
James Dennetta40f7922012-06-14 03:11:41 +00004393 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004394 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4395 Builder.AddPlaceholderChunk("protocol");
4396 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004397
4398 // @implementation name
James Dennetta40f7922012-06-14 03:11:41 +00004399 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4401 Builder.AddPlaceholderChunk("class");
4402 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004403 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004404
4405 // @compatibility_alias name
James Dennetta40f7922012-06-14 03:11:41 +00004406 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004407 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4408 Builder.AddPlaceholderChunk("alias");
4409 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4410 Builder.AddPlaceholderChunk("class");
4411 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004412}
4413
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004414void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004415 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004416 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004417 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004418 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004419 if (isa<ObjCImplDecl>(CurContext))
David Blaikie4e4d0842012-03-11 07:00:24 +00004420 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004421 else if (CurContext->isObjCContainer())
David Blaikie4e4d0842012-03-11 07:00:24 +00004422 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004423 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004424 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004425 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004426 HandleCodeCompleteResults(this, CodeCompleter,
4427 CodeCompletionContext::CCC_Other,
4428 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004429}
4430
Douglas Gregorbca403c2010-01-13 23:51:12 +00004431static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004432 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004433 CodeCompletionBuilder Builder(Results.getAllocator(),
4434 Results.getCodeCompletionTUInfo());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004435
4436 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004437 const char *EncodeType = "char[]";
David Blaikie4e4d0842012-03-11 07:00:24 +00004438 if (Results.getSema().getLangOpts().CPlusPlus ||
4439 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004440 EncodeType = "const char[]";
Douglas Gregor8ca72082011-10-18 21:20:17 +00004441 Builder.AddResultTypeChunk(EncodeType);
James Dennetta40f7922012-06-14 03:11:41 +00004442 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004443 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4444 Builder.AddPlaceholderChunk("type-name");
4445 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004447
4448 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004449 Builder.AddResultTypeChunk("Protocol *");
James Dennetta40f7922012-06-14 03:11:41 +00004450 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004451 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4452 Builder.AddPlaceholderChunk("protocol-name");
4453 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4454 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004455
4456 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004457 Builder.AddResultTypeChunk("SEL");
James Dennetta40f7922012-06-14 03:11:41 +00004458 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004459 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4460 Builder.AddPlaceholderChunk("selector");
4461 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4462 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004463
4464 // @"string"
4465 Builder.AddResultTypeChunk("NSString *");
4466 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4467 Builder.AddPlaceholderChunk("string");
4468 Builder.AddTextChunk("\"");
4469 Results.AddResult(Result(Builder.TakeString()));
4470
Douglas Gregor79615892012-07-17 23:24:47 +00004471 // @[objects, ...]
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004472 Builder.AddResultTypeChunk("NSArray *");
James Dennetta40f7922012-06-14 03:11:41 +00004473 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004474 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004475 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4476 Results.AddResult(Result(Builder.TakeString()));
4477
Douglas Gregor79615892012-07-17 23:24:47 +00004478 // @{key : object, ...}
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004479 Builder.AddResultTypeChunk("NSDictionary *");
James Dennetta40f7922012-06-14 03:11:41 +00004480 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004481 Builder.AddPlaceholderChunk("key");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004482 Builder.AddChunk(CodeCompletionString::CK_Colon);
4483 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4484 Builder.AddPlaceholderChunk("object, ...");
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004485 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4486 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004487
Douglas Gregor79615892012-07-17 23:24:47 +00004488 // @(expression)
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004489 Builder.AddResultTypeChunk("id");
4490 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004491 Builder.AddPlaceholderChunk("expression");
Jordan Rose1f6e22d2012-06-15 18:19:56 +00004492 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4493 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004494}
4495
Douglas Gregorbca403c2010-01-13 23:51:12 +00004496static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004497 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004498 CodeCompletionBuilder Builder(Results.getAllocator(),
4499 Results.getCodeCompletionTUInfo());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004500
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004501 if (Results.includeCodePatterns()) {
4502 // @try { statements } @catch ( declaration ) { statements } @finally
4503 // { statements }
James Dennetta40f7922012-06-14 03:11:41 +00004504 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004505 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4506 Builder.AddPlaceholderChunk("statements");
4507 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4508 Builder.AddTextChunk("@catch");
4509 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4510 Builder.AddPlaceholderChunk("parameter");
4511 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4512 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4513 Builder.AddPlaceholderChunk("statements");
4514 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4515 Builder.AddTextChunk("@finally");
4516 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4517 Builder.AddPlaceholderChunk("statements");
4518 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4519 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004520 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004521
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004522 // @throw
James Dennetta40f7922012-06-14 03:11:41 +00004523 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004524 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4525 Builder.AddPlaceholderChunk("expression");
4526 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004527
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004528 if (Results.includeCodePatterns()) {
4529 // @synchronized ( expression ) { statements }
James Dennetta40f7922012-06-14 03:11:41 +00004530 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregor218937c2011-02-01 19:23:04 +00004531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4532 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4533 Builder.AddPlaceholderChunk("expression");
4534 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4535 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4536 Builder.AddPlaceholderChunk("statements");
4537 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4538 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004539 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004540}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004541
Douglas Gregorbca403c2010-01-13 23:51:12 +00004542static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004543 ResultBuilder &Results,
4544 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004545 typedef CodeCompletionResult Result;
James Dennetta40f7922012-06-14 03:11:41 +00004546 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4547 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4548 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004549 if (LangOpts.ObjC2)
James Dennetta40f7922012-06-14 03:11:41 +00004550 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004551}
4552
4553void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004554 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004555 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004556 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004557 Results.EnterNewScope();
David Blaikie4e4d0842012-03-11 07:00:24 +00004558 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004559 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004560 HandleCodeCompleteResults(this, CodeCompleter,
4561 CodeCompletionContext::CCC_Other,
4562 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004563}
4564
4565void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004566 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004567 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004568 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004569 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004570 AddObjCStatementResults(Results, false);
4571 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004572 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004573 HandleCodeCompleteResults(this, CodeCompleter,
4574 CodeCompletionContext::CCC_Other,
4575 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004576}
4577
4578void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004579 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004580 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004581 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004582 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004583 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004584 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004585 HandleCodeCompleteResults(this, CodeCompleter,
4586 CodeCompletionContext::CCC_Other,
4587 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004588}
4589
Douglas Gregor988358f2009-11-19 00:14:45 +00004590/// \brief Determine whether the addition of the given flag to an Objective-C
4591/// property's attributes will cause a conflict.
4592static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4593 // Check if we've already added this flag.
4594 if (Attributes & NewFlag)
4595 return true;
4596
4597 Attributes |= NewFlag;
4598
4599 // Check for collisions with "readonly".
4600 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
Jordan Rosed7403a72012-08-20 20:01:13 +00004601 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregor988358f2009-11-19 00:14:45 +00004602 return true;
4603
Jordan Rosed7403a72012-08-20 20:01:13 +00004604 // Check for more than one of { assign, copy, retain, strong, weak }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004605 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004606 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004607 ObjCDeclSpec::DQ_PR_copy |
Jordan Rosed7403a72012-08-20 20:01:13 +00004608 ObjCDeclSpec::DQ_PR_retain |
4609 ObjCDeclSpec::DQ_PR_strong |
4610 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregor988358f2009-11-19 00:14:45 +00004611 if (AssignCopyRetMask &&
4612 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004613 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004614 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004615 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rosed7403a72012-08-20 20:01:13 +00004616 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4617 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregor988358f2009-11-19 00:14:45 +00004618 return true;
4619
4620 return false;
4621}
4622
Douglas Gregora93b1082009-11-18 23:08:07 +00004623void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004624 if (!CodeCompleter)
4625 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004626
Steve Naroffece8e712009-10-08 21:55:05 +00004627 unsigned Attributes = ODS.getPropertyAttributes();
4628
Douglas Gregor218937c2011-02-01 19:23:04 +00004629 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004630 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004631 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004632 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004633 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004634 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004635 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004636 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004637 if (!ObjCPropertyFlagConflicts(Attributes,
4638 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4639 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004640 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004641 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004642 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004643 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004644 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4645 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004646 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004647 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004648 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004649 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004650 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4651 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rosed7403a72012-08-20 20:01:13 +00004652
4653 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall0a7dd782012-08-21 02:47:43 +00004654 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Jordan Rosed7403a72012-08-20 20:01:13 +00004655 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
4656 Results.AddResult(CodeCompletionResult("weak"));
4657
Douglas Gregor988358f2009-11-19 00:14:45 +00004658 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004659 CodeCompletionBuilder Setter(Results.getAllocator(),
4660 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00004661 Setter.AddTypedTextChunk("setter");
4662 Setter.AddTextChunk(" = ");
4663 Setter.AddPlaceholderChunk("method");
4664 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004665 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004666 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004667 CodeCompletionBuilder Getter(Results.getAllocator(),
4668 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00004669 Getter.AddTypedTextChunk("getter");
4670 Getter.AddTextChunk(" = ");
4671 Getter.AddPlaceholderChunk("method");
4672 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004673 }
Steve Naroffece8e712009-10-08 21:55:05 +00004674 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004675 HandleCodeCompleteResults(this, CodeCompleter,
4676 CodeCompletionContext::CCC_Other,
4677 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004678}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004679
James Dennettde23c7e2012-06-17 05:33:25 +00004680/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregor4ad96852009-11-19 07:41:15 +00004681/// via code completion.
4682enum ObjCMethodKind {
Dmitri Gribenko49fdccb2012-06-08 23:13:42 +00004683 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4684 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4685 MK_OneArgSelector ///< One-argument selector.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004686};
4687
Douglas Gregor458433d2010-08-26 15:07:07 +00004688static bool isAcceptableObjCSelector(Selector Sel,
4689 ObjCMethodKind WantKind,
4690 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004691 unsigned NumSelIdents,
4692 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004693 if (NumSelIdents > Sel.getNumArgs())
4694 return false;
4695
4696 switch (WantKind) {
4697 case MK_Any: break;
4698 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4699 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4700 }
4701
Douglas Gregorcf544262010-11-17 21:36:08 +00004702 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4703 return false;
4704
Douglas Gregor458433d2010-08-26 15:07:07 +00004705 for (unsigned I = 0; I != NumSelIdents; ++I)
4706 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4707 return false;
4708
4709 return true;
4710}
4711
Douglas Gregor4ad96852009-11-19 07:41:15 +00004712static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4713 ObjCMethodKind WantKind,
4714 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004715 unsigned NumSelIdents,
4716 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004717 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004718 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004719}
Douglas Gregord36adf52010-09-16 16:06:31 +00004720
4721namespace {
4722 /// \brief A set of selectors, which is used to avoid introducing multiple
4723 /// completions with the same selector into the result set.
4724 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4725}
4726
Douglas Gregor36ecb042009-11-17 23:22:23 +00004727/// \brief Add all of the Objective-C methods in the given Objective-C
4728/// container to the set of results.
4729///
4730/// The container will be a class, protocol, category, or implementation of
4731/// any of the above. This mether will recurse to include methods from
4732/// the superclasses of classes along with their categories, protocols, and
4733/// implementations.
4734///
4735/// \param Container the container in which we'll look to find methods.
4736///
James Dennetta40f7922012-06-14 03:11:41 +00004737/// \param WantInstanceMethods Whether to add instance methods (only); if
4738/// false, this routine will add factory methods (only).
Douglas Gregor36ecb042009-11-17 23:22:23 +00004739///
4740/// \param CurContext the context in which we're performing the lookup that
4741/// finds methods.
4742///
Douglas Gregorcf544262010-11-17 21:36:08 +00004743/// \param AllowSameLength Whether we allow a method to be added to the list
4744/// when it has the same number of parameters as we have selector identifiers.
4745///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004746/// \param Results the structure into which we'll add results.
4747static void AddObjCMethods(ObjCContainerDecl *Container,
4748 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004749 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004750 IdentifierInfo **SelIdents,
4751 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004752 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004753 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004754 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004755 ResultBuilder &Results,
4756 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004757 typedef CodeCompletionResult Result;
Douglas Gregorb92a4082012-06-12 13:44:08 +00004758 Container = getContainerDef(Container);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004759 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4760 MEnd = Container->meth_end();
4761 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00004762 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004763 // Check whether the selector identifiers we've been given are a
4764 // subset of the identifiers for this particular method.
David Blaikie581deb32012-06-06 20:45:41 +00004765 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004766 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004767 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004768
David Blaikie262bc182012-04-30 02:36:29 +00004769 if (!Selectors.insert(M->getSelector()))
Douglas Gregord36adf52010-09-16 16:06:31 +00004770 continue;
4771
David Blaikie581deb32012-06-06 20:45:41 +00004772 Result R = Result(*M, 0);
Douglas Gregord3c68542009-11-19 01:08:35 +00004773 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004774 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004775 if (!InOriginalClass)
4776 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004777 Results.MaybeAddResult(R, CurContext);
4778 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004779 }
4780
Douglas Gregore396c7b2010-09-16 15:34:59 +00004781 // Visit the protocols of protocols.
4782 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004783 if (Protocol->hasDefinition()) {
4784 const ObjCList<ObjCProtocolDecl> &Protocols
4785 = Protocol->getReferencedProtocols();
4786 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4787 E = Protocols.end();
4788 I != E; ++I)
4789 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4790 NumSelIdents, CurContext, Selectors, AllowSameLength,
4791 Results, false);
4792 }
Douglas Gregore396c7b2010-09-16 15:34:59 +00004793 }
4794
Douglas Gregor36ecb042009-11-17 23:22:23 +00004795 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00004796 if (!IFace || !IFace->hasDefinition())
Douglas Gregor36ecb042009-11-17 23:22:23 +00004797 return;
4798
4799 // Add methods in protocols.
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00004800 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
4801 E = IFace->protocol_end();
Douglas Gregor36ecb042009-11-17 23:22:23 +00004802 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004803 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004804 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004805
4806 // Add methods in categories.
4807 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4808 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004809 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004810 NumSelIdents, CurContext, Selectors, AllowSameLength,
4811 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004812
4813 // Add a categories protocol methods.
4814 const ObjCList<ObjCProtocolDecl> &Protocols
4815 = CatDecl->getReferencedProtocols();
4816 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4817 E = Protocols.end();
4818 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004819 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004820 NumSelIdents, CurContext, Selectors, AllowSameLength,
4821 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004822
4823 // Add methods in category implementations.
4824 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004825 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004826 NumSelIdents, CurContext, Selectors, AllowSameLength,
4827 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004828 }
4829
4830 // Add methods in superclass.
4831 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004832 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004833 SelIdents, NumSelIdents, CurContext, Selectors,
4834 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004835
4836 // Add methods in our implementation, if any.
4837 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004838 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004839 NumSelIdents, CurContext, Selectors, AllowSameLength,
4840 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004841}
4842
4843
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004844void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004845 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004846 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004847 if (!Class) {
4848 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004849 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004850 Class = Category->getClassInterface();
4851
4852 if (!Class)
4853 return;
4854 }
4855
4856 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004857 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004858 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004859 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004860 Results.EnterNewScope();
4861
Douglas Gregord36adf52010-09-16 16:06:31 +00004862 VisitedSelectorSet Selectors;
4863 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004864 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004865 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004866 HandleCodeCompleteResults(this, CodeCompleter,
4867 CodeCompletionContext::CCC_Other,
4868 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004869}
4870
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004871void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004872 // Try to find the interface where setters might live.
4873 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004874 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004875 if (!Class) {
4876 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004877 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004878 Class = Category->getClassInterface();
4879
4880 if (!Class)
4881 return;
4882 }
4883
4884 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004885 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004886 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004887 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004888 Results.EnterNewScope();
4889
Douglas Gregord36adf52010-09-16 16:06:31 +00004890 VisitedSelectorSet Selectors;
4891 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004892 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004893
4894 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004895 HandleCodeCompleteResults(this, CodeCompleter,
4896 CodeCompletionContext::CCC_Other,
4897 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004898}
4899
Douglas Gregorafc45782011-02-15 22:19:42 +00004900void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4901 bool IsParameter) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004902 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004903 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00004904 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004905 Results.EnterNewScope();
4906
4907 // Add context-sensitive, Objective-C parameter-passing keywords.
4908 bool AddedInOut = false;
4909 if ((DS.getObjCDeclQualifier() &
4910 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4911 Results.AddResult("in");
4912 Results.AddResult("inout");
4913 AddedInOut = true;
4914 }
4915 if ((DS.getObjCDeclQualifier() &
4916 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4917 Results.AddResult("out");
4918 if (!AddedInOut)
4919 Results.AddResult("inout");
4920 }
4921 if ((DS.getObjCDeclQualifier() &
4922 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4923 ObjCDeclSpec::DQ_Oneway)) == 0) {
4924 Results.AddResult("bycopy");
4925 Results.AddResult("byref");
4926 Results.AddResult("oneway");
4927 }
4928
Douglas Gregorafc45782011-02-15 22:19:42 +00004929 // If we're completing the return type of an Objective-C method and the
4930 // identifier IBAction refers to a macro, provide a completion item for
4931 // an action, e.g.,
4932 // IBAction)<#selector#>:(id)sender
4933 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4934 Context.Idents.get("IBAction").hasMacroDefinition()) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00004935 CodeCompletionBuilder Builder(Results.getAllocator(),
4936 Results.getCodeCompletionTUInfo(),
4937 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorafc45782011-02-15 22:19:42 +00004938 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004939 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004940 Builder.AddPlaceholderChunk("selector");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004941 Builder.AddChunk(CodeCompletionString::CK_Colon);
4942 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004943 Builder.AddTextChunk("id");
Benjamin Kramer1eb18af2012-03-26 16:57:36 +00004944 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorafc45782011-02-15 22:19:42 +00004945 Builder.AddTextChunk("sender");
4946 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4947 }
4948
Douglas Gregord32b0222010-08-24 01:06:58 +00004949 // Add various builtin type names and specifiers.
4950 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4951 Results.ExitScope();
4952
4953 // Add the various type names
4954 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4955 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4956 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4957 CodeCompleter->includeGlobals());
4958
4959 if (CodeCompleter->includeMacros())
4960 AddMacroResults(PP, Results);
4961
4962 HandleCodeCompleteResults(this, CodeCompleter,
4963 CodeCompletionContext::CCC_Type,
4964 Results.data(), Results.size());
4965}
4966
Douglas Gregor22f56992010-04-06 19:22:33 +00004967/// \brief When we have an expression with type "id", we may assume
4968/// that it has some more-specific class type based on knowledge of
4969/// common uses of Objective-C. This routine returns that class type,
4970/// or NULL if no better result could be determined.
4971static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004972 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004973 if (!Msg)
4974 return 0;
4975
4976 Selector Sel = Msg->getSelector();
4977 if (Sel.isNull())
4978 return 0;
4979
4980 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4981 if (!Id)
4982 return 0;
4983
4984 ObjCMethodDecl *Method = Msg->getMethodDecl();
4985 if (!Method)
4986 return 0;
4987
4988 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004989 ObjCInterfaceDecl *IFace = 0;
4990 switch (Msg->getReceiverKind()) {
4991 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004992 if (const ObjCObjectType *ObjType
4993 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4994 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004995 break;
4996
4997 case ObjCMessageExpr::Instance: {
4998 QualType T = Msg->getInstanceReceiver()->getType();
4999 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5000 IFace = Ptr->getInterfaceDecl();
5001 break;
5002 }
5003
5004 case ObjCMessageExpr::SuperInstance:
5005 case ObjCMessageExpr::SuperClass:
5006 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00005007 }
5008
5009 if (!IFace)
5010 return 0;
5011
5012 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5013 if (Method->isInstanceMethod())
5014 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5015 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00005016 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00005017 .Case("autorelease", IFace)
5018 .Case("copy", IFace)
5019 .Case("copyWithZone", IFace)
5020 .Case("mutableCopy", IFace)
5021 .Case("mutableCopyWithZone", IFace)
5022 .Case("awakeFromCoder", IFace)
5023 .Case("replacementObjectFromCoder", IFace)
5024 .Case("class", IFace)
5025 .Case("classForCoder", IFace)
5026 .Case("superclass", Super)
5027 .Default(0);
5028
5029 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5030 .Case("new", IFace)
5031 .Case("alloc", IFace)
5032 .Case("allocWithZone", IFace)
5033 .Case("class", IFace)
5034 .Case("superclass", Super)
5035 .Default(0);
5036}
5037
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005038// Add a special completion for a message send to "super", which fills in the
5039// most likely case of forwarding all of our arguments to the superclass
5040// function.
5041///
5042/// \param S The semantic analysis object.
5043///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00005044/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005045/// the "super" keyword. Otherwise, we just need to provide the arguments.
5046///
5047/// \param SelIdents The identifiers in the selector that have already been
5048/// provided as arguments for a send to "super".
5049///
5050/// \param NumSelIdents The number of identifiers in \p SelIdents.
5051///
5052/// \param Results The set of results to augment.
5053///
5054/// \returns the Objective-C method declaration that would be invoked by
5055/// this "super" completion. If NULL, no completion was added.
5056static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
5057 IdentifierInfo **SelIdents,
5058 unsigned NumSelIdents,
5059 ResultBuilder &Results) {
5060 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5061 if (!CurMethod)
5062 return 0;
5063
5064 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5065 if (!Class)
5066 return 0;
5067
5068 // Try to find a superclass method with the same selector.
5069 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00005070 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5071 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005072 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5073 CurMethod->isInstanceMethod());
5074
Douglas Gregor78bcd912011-02-16 00:51:18 +00005075 // Check in categories or class extensions.
5076 if (!SuperMethod) {
5077 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5078 Category = Category->getNextClassCategory())
5079 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
5080 CurMethod->isInstanceMethod())))
5081 break;
5082 }
5083 }
5084
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005085 if (!SuperMethod)
5086 return 0;
5087
5088 // Check whether the superclass method has the same signature.
5089 if (CurMethod->param_size() != SuperMethod->param_size() ||
5090 CurMethod->isVariadic() != SuperMethod->isVariadic())
5091 return 0;
5092
5093 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5094 CurPEnd = CurMethod->param_end(),
5095 SuperP = SuperMethod->param_begin();
5096 CurP != CurPEnd; ++CurP, ++SuperP) {
5097 // Make sure the parameter types are compatible.
5098 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5099 (*SuperP)->getType()))
5100 return 0;
5101
5102 // Make sure we have a parameter name to forward!
5103 if (!(*CurP)->getIdentifier())
5104 return 0;
5105 }
5106
5107 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005108 CodeCompletionBuilder Builder(Results.getAllocator(),
5109 Results.getCodeCompletionTUInfo());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005110
5111 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00005112 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5113 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005114
5115 // If we need the "super" keyword, add it (plus some spacing).
5116 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005117 Builder.AddTypedTextChunk("super");
5118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005119 }
5120
5121 Selector Sel = CurMethod->getSelector();
5122 if (Sel.isUnarySelector()) {
5123 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00005124 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005125 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005126 else
Douglas Gregordae68752011-02-01 22:57:45 +00005127 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005128 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005129 } else {
5130 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5131 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5132 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005133 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005134
5135 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00005136 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005137 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005138 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005139 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005140 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005141 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005142 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005143 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005144 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005145 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00005146 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00005147 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005148 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00005149 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005150 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005151 }
5152 }
5153 }
5154
Douglas Gregorba103062012-03-27 23:34:16 +00005155 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5156 CCP_SuperCompletion));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005157 return SuperMethod;
5158}
5159
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005160void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005161 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005162 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005163 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005164 CodeCompletionContext::CCC_ObjCMessageReceiver,
David Blaikie4e4d0842012-03-11 07:00:24 +00005165 getLangOpts().CPlusPlus0x
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005166 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5167 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005168
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005169 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5170 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00005171 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5172 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005173
5174 // If we are in an Objective-C method inside a class that has a superclass,
5175 // add "super" as an option.
5176 if (ObjCMethodDecl *Method = getCurMethodDecl())
5177 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005178 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005179 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005180
5181 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
5182 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005183
David Blaikie4e4d0842012-03-11 07:00:24 +00005184 if (getLangOpts().CPlusPlus0x)
Douglas Gregor81f3bff2012-02-15 15:34:24 +00005185 addThisCompletion(*this, Results);
5186
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005187 Results.ExitScope();
5188
5189 if (CodeCompleter->includeMacros())
5190 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00005191 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005192 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00005193
5194}
5195
Douglas Gregor2725ca82010-04-21 19:57:20 +00005196void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5197 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005198 unsigned NumSelIdents,
5199 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00005200 ObjCInterfaceDecl *CDecl = 0;
5201 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5202 // Figure out which interface we're in.
5203 CDecl = CurMethod->getClassInterface();
5204 if (!CDecl)
5205 return;
5206
5207 // Find the superclass of this class.
5208 CDecl = CDecl->getSuperClass();
5209 if (!CDecl)
5210 return;
5211
5212 if (CurMethod->isInstanceMethod()) {
5213 // We are inside an instance method, which means that the message
5214 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005215 // current object.
5216 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005217 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005218 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005219 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005220 }
5221
5222 // Fall through to send to the superclass in CDecl.
5223 } else {
5224 // "super" may be the name of a type or variable. Figure out which
5225 // it is.
5226 IdentifierInfo *Super = &Context.Idents.get("super");
5227 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5228 LookupOrdinaryName);
5229 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5230 // "super" names an interface. Use it.
5231 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005232 if (const ObjCObjectType *Iface
5233 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5234 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005235 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5236 // "super" names an unresolved type; we can't be more specific.
5237 } else {
5238 // Assume that "super" names some kind of value and parse that way.
5239 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005240 SourceLocation TemplateKWLoc;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005241 UnqualifiedId id;
5242 id.setIdentifier(Super, SuperLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00005243 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5244 false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005245 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005246 SelIdents, NumSelIdents,
5247 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005248 }
5249
5250 // Fall through
5251 }
5252
John McCallb3d87482010-08-24 05:47:05 +00005253 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005254 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005255 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005256 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005257 NumSelIdents, AtArgumentExpression,
5258 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005259}
5260
Douglas Gregorb9d77572010-09-21 00:03:25 +00005261/// \brief Given a set of code-completion results for the argument of a message
5262/// send, determine the preferred type (if any) for that argument expression.
5263static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5264 unsigned NumSelIdents) {
5265 typedef CodeCompletionResult Result;
5266 ASTContext &Context = Results.getSema().Context;
5267
5268 QualType PreferredType;
5269 unsigned BestPriority = CCP_Unlikely * 2;
5270 Result *ResultsData = Results.data();
5271 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5272 Result &R = ResultsData[I];
5273 if (R.Kind == Result::RK_Declaration &&
5274 isa<ObjCMethodDecl>(R.Declaration)) {
5275 if (R.Priority <= BestPriority) {
5276 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5277 if (NumSelIdents <= Method->param_size()) {
5278 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5279 ->getType();
5280 if (R.Priority < BestPriority || PreferredType.isNull()) {
5281 BestPriority = R.Priority;
5282 PreferredType = MyPreferredType;
5283 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5284 MyPreferredType)) {
5285 PreferredType = QualType();
5286 }
5287 }
5288 }
5289 }
5290 }
5291
5292 return PreferredType;
5293}
5294
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005295static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5296 ParsedType Receiver,
5297 IdentifierInfo **SelIdents,
5298 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005299 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005300 bool IsSuper,
5301 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005302 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005303 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005304
Douglas Gregor24a069f2009-11-17 17:59:40 +00005305 // If the given name refers to an interface type, retrieve the
5306 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005307 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005308 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005309 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005310 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5311 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005312 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005313
Douglas Gregor36ecb042009-11-17 23:22:23 +00005314 // Add all of the factory methods in this Objective-C class, its protocols,
5315 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005316 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005317
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005318 // If this is a send-to-super, try to add the special "super" send
5319 // completion.
5320 if (IsSuper) {
5321 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005322 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5323 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005324 Results.Ignore(SuperMethod);
5325 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005326
Douglas Gregor265f7492010-08-27 15:29:55 +00005327 // If we're inside an Objective-C method definition, prefer its selector to
5328 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005329 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005330 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005331
Douglas Gregord36adf52010-09-16 16:06:31 +00005332 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005333 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005334 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005335 SemaRef.CurContext, Selectors, AtArgumentExpression,
5336 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005337 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005338 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005339
Douglas Gregor719770d2010-04-06 17:30:22 +00005340 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005341 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005342 if (SemaRef.ExternalSource) {
5343 for (uint32_t I = 0,
5344 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005345 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005346 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5347 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005348 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005349
5350 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005351 }
5352 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005353
5354 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5355 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005356 M != MEnd; ++M) {
5357 for (ObjCMethodList *MethList = &M->second.second;
5358 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005359 MethList = MethList->Next) {
5360 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5361 NumSelIdents))
5362 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005363
Douglas Gregor13438f92010-04-06 16:40:00 +00005364 Result R(MethList->Method, 0);
5365 R.StartParameter = NumSelIdents;
5366 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005367 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005368 }
5369 }
5370 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005371
5372 Results.ExitScope();
5373}
Douglas Gregor13438f92010-04-06 16:40:00 +00005374
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005375void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5376 IdentifierInfo **SelIdents,
5377 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005378 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005379 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005380
5381 QualType T = this->GetTypeFromParser(Receiver);
5382
Douglas Gregor218937c2011-02-01 19:23:04 +00005383 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005384 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregore081a612011-07-21 01:05:26 +00005385 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005386 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005387
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005388 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5389 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005390
5391 // If we're actually at the argument expression (rather than prior to the
5392 // selector), we're actually performing code completion for an expression.
5393 // Determine whether we have a single, best method. If so, we can
5394 // code-complete the expression using the corresponding parameter type as
5395 // our preferred type, improving completion results.
5396 if (AtArgumentExpression) {
5397 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005398 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005399 if (PreferredType.isNull())
5400 CodeCompleteOrdinaryName(S, PCC_Expression);
5401 else
5402 CodeCompleteExpression(S, PreferredType);
5403 return;
5404 }
5405
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005406 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005407 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005408 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005409}
5410
Richard Trieuf81e5a92011-09-09 02:00:50 +00005411void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005412 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005413 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005414 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005415 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005416 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005417
5418 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005419
Douglas Gregor36ecb042009-11-17 23:22:23 +00005420 // If necessary, apply function/array conversion to the receiver.
5421 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005422 if (RecExpr) {
5423 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5424 if (Conv.isInvalid()) // conversion failed. bail.
5425 return;
5426 RecExpr = Conv.take();
5427 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005428 QualType ReceiverType = RecExpr? RecExpr->getType()
5429 : Super? Context.getObjCObjectPointerType(
5430 Context.getObjCInterfaceType(Super))
5431 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005432
Douglas Gregorda892642010-11-08 21:12:30 +00005433 // If we're messaging an expression with type "id" or "Class", check
5434 // whether we know something special about the receiver that allows
5435 // us to assume a more-specific receiver type.
5436 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5437 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5438 if (ReceiverType->isObjCClassType())
5439 return CodeCompleteObjCClassMessage(S,
5440 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5441 SelIdents, NumSelIdents,
5442 AtArgumentExpression, Super);
5443
5444 ReceiverType = Context.getObjCObjectPointerType(
5445 Context.getObjCInterfaceType(IFace));
5446 }
5447
Douglas Gregor36ecb042009-11-17 23:22:23 +00005448 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005449 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005450 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregore081a612011-07-21 01:05:26 +00005451 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005452 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005453
Douglas Gregor36ecb042009-11-17 23:22:23 +00005454 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005455
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005456 // If this is a send-to-super, try to add the special "super" send
5457 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005458 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005459 if (ObjCMethodDecl *SuperMethod
5460 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5461 Results))
5462 Results.Ignore(SuperMethod);
5463 }
5464
Douglas Gregor265f7492010-08-27 15:29:55 +00005465 // If we're inside an Objective-C method definition, prefer its selector to
5466 // others.
5467 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5468 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005469
Douglas Gregord36adf52010-09-16 16:06:31 +00005470 // Keep track of the selectors we've already added.
5471 VisitedSelectorSet Selectors;
5472
Douglas Gregorf74a4192009-11-18 00:06:18 +00005473 // Handle messages to Class. This really isn't a message to an instance
5474 // method, so we treat it the same way we would treat a message send to a
5475 // class method.
5476 if (ReceiverType->isObjCClassType() ||
5477 ReceiverType->isObjCQualifiedClassType()) {
5478 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5479 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005480 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005481 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005482 }
5483 }
5484 // Handle messages to a qualified ID ("id<foo>").
5485 else if (const ObjCObjectPointerType *QualID
5486 = ReceiverType->getAsObjCQualifiedIdType()) {
5487 // Search protocols for instance methods.
5488 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5489 E = QualID->qual_end();
5490 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005491 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005492 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005493 }
5494 // Handle messages to a pointer to interface type.
5495 else if (const ObjCObjectPointerType *IFacePtr
5496 = ReceiverType->getAsObjCInterfacePointerType()) {
5497 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005498 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005499 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5500 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005501
5502 // Search protocols for instance methods.
5503 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5504 E = IFacePtr->qual_end();
5505 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005506 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005507 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005508 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005509 // Handle messages to "id".
5510 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005511 // We're messaging "id", so provide all instance methods we know
5512 // about as code-completion results.
5513
5514 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005515 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005516 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005517 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5518 I != N; ++I) {
5519 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005520 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005521 continue;
5522
Sebastian Redldb9d2142010-08-02 23:18:59 +00005523 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005524 }
5525 }
5526
Sebastian Redldb9d2142010-08-02 23:18:59 +00005527 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5528 MEnd = MethodPool.end();
5529 M != MEnd; ++M) {
5530 for (ObjCMethodList *MethList = &M->second.first;
5531 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005532 MethList = MethList->Next) {
5533 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5534 NumSelIdents))
5535 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005536
5537 if (!Selectors.insert(MethList->Method->getSelector()))
5538 continue;
5539
Douglas Gregor13438f92010-04-06 16:40:00 +00005540 Result R(MethList->Method, 0);
5541 R.StartParameter = NumSelIdents;
5542 R.AllParametersAreInformative = false;
5543 Results.MaybeAddResult(R, CurContext);
5544 }
5545 }
5546 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005547 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005548
5549
5550 // If we're actually at the argument expression (rather than prior to the
5551 // selector), we're actually performing code completion for an expression.
5552 // Determine whether we have a single, best method. If so, we can
5553 // code-complete the expression using the corresponding parameter type as
5554 // our preferred type, improving completion results.
5555 if (AtArgumentExpression) {
5556 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5557 NumSelIdents);
5558 if (PreferredType.isNull())
5559 CodeCompleteOrdinaryName(S, PCC_Expression);
5560 else
5561 CodeCompleteExpression(S, PreferredType);
5562 return;
5563 }
5564
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005565 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005566 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005567 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005568}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005569
Douglas Gregorfb629412010-08-23 21:17:50 +00005570void Sema::CodeCompleteObjCForCollection(Scope *S,
5571 DeclGroupPtrTy IterationVar) {
5572 CodeCompleteExpressionData Data;
5573 Data.ObjCCollection = true;
5574
5575 if (IterationVar.getAsOpaquePtr()) {
5576 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5577 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5578 if (*I)
5579 Data.IgnoreDecls.push_back(*I);
5580 }
5581 }
5582
5583 CodeCompleteExpression(S, Data);
5584}
5585
Douglas Gregor458433d2010-08-26 15:07:07 +00005586void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5587 unsigned NumSelIdents) {
5588 // If we have an external source, load the entire class method
5589 // pool from the AST file.
5590 if (ExternalSource) {
5591 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5592 I != N; ++I) {
5593 Selector Sel = ExternalSource->GetExternalSelector(I);
5594 if (Sel.isNull() || MethodPool.count(Sel))
5595 continue;
5596
5597 ReadMethodPool(Sel);
5598 }
5599 }
5600
Douglas Gregor218937c2011-02-01 19:23:04 +00005601 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005602 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005603 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005604 Results.EnterNewScope();
5605 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5606 MEnd = MethodPool.end();
5607 M != MEnd; ++M) {
5608
5609 Selector Sel = M->first;
5610 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5611 continue;
5612
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005613 CodeCompletionBuilder Builder(Results.getAllocator(),
5614 Results.getCodeCompletionTUInfo());
Douglas Gregor458433d2010-08-26 15:07:07 +00005615 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005616 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005617 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005618 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005619 continue;
5620 }
5621
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005622 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005623 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005624 if (I == NumSelIdents) {
5625 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005626 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005627 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005628 Accumulator.clear();
5629 }
5630 }
5631
Benjamin Kramera0651c52011-07-26 16:59:25 +00005632 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005633 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005634 }
Douglas Gregordae68752011-02-01 22:57:45 +00005635 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005636 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005637 }
5638 Results.ExitScope();
5639
5640 HandleCodeCompleteResults(this, CodeCompleter,
5641 CodeCompletionContext::CCC_SelectorName,
5642 Results.data(), Results.size());
5643}
5644
Douglas Gregor55385fe2009-11-18 04:19:12 +00005645/// \brief Add all of the protocol declarations that we find in the given
5646/// (translation unit) context.
5647static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005648 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005649 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005650 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005651
5652 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5653 DEnd = Ctx->decls_end();
5654 D != DEnd; ++D) {
5655 // Record any protocols we find.
5656 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005657 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregor608300b2010-01-14 16:14:35 +00005658 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005659 }
5660}
5661
5662void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5663 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005664 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005665 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005666 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005667
Douglas Gregor70c23352010-12-09 21:44:02 +00005668 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5669 Results.EnterNewScope();
5670
5671 // Tell the result set to ignore all of the protocols we have
5672 // already seen.
5673 // FIXME: This doesn't work when caching code-completion results.
5674 for (unsigned I = 0; I != NumProtocols; ++I)
5675 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5676 Protocols[I].second))
5677 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005678
Douglas Gregor70c23352010-12-09 21:44:02 +00005679 // Add all protocols.
5680 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5681 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005682
Douglas Gregor70c23352010-12-09 21:44:02 +00005683 Results.ExitScope();
5684 }
5685
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005686 HandleCodeCompleteResults(this, CodeCompleter,
5687 CodeCompletionContext::CCC_ObjCProtocolName,
5688 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005689}
5690
5691void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005692 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005693 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005694 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005695
Douglas Gregor70c23352010-12-09 21:44:02 +00005696 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5697 Results.EnterNewScope();
5698
5699 // Add all protocols.
5700 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5701 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005702
Douglas Gregor70c23352010-12-09 21:44:02 +00005703 Results.ExitScope();
5704 }
5705
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005706 HandleCodeCompleteResults(this, CodeCompleter,
5707 CodeCompletionContext::CCC_ObjCProtocolName,
5708 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005709}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005710
5711/// \brief Add all of the Objective-C interface declarations that we find in
5712/// the given (translation unit) context.
5713static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5714 bool OnlyForwardDeclarations,
5715 bool OnlyUnimplemented,
5716 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005717 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005718
5719 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5720 DEnd = Ctx->decls_end();
5721 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005722 // Record any interfaces we find.
5723 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregor7723fec2011-12-15 20:29:51 +00005724 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005725 (!OnlyUnimplemented || !Class->getImplementation()))
5726 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005727 }
5728}
5729
5730void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005731 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005732 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005733 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005734 Results.EnterNewScope();
5735
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005736 if (CodeCompleter->includeGlobals()) {
5737 // Add all classes.
5738 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5739 false, Results);
5740 }
5741
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005742 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005743
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005744 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005745 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005746 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005747}
5748
Douglas Gregorc83c6872010-04-15 22:33:43 +00005749void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5750 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005751 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005752 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005753 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005754 Results.EnterNewScope();
5755
5756 // Make sure that we ignore the class we're currently defining.
5757 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005758 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005759 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005760 Results.Ignore(CurClass);
5761
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005762 if (CodeCompleter->includeGlobals()) {
5763 // Add all classes.
5764 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5765 false, Results);
5766 }
5767
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005768 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005769
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005770 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005771 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005772 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005773}
5774
5775void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005776 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005777 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005778 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005779 Results.EnterNewScope();
5780
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005781 if (CodeCompleter->includeGlobals()) {
5782 // Add all unimplemented classes.
5783 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5784 true, Results);
5785 }
5786
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005787 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005788
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005789 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005790 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005791 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005792}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005793
5794void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005795 IdentifierInfo *ClassName,
5796 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005797 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005798
Douglas Gregor218937c2011-02-01 19:23:04 +00005799 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005800 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005801 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005802
5803 // Ignore any categories we find that have already been implemented by this
5804 // interface.
5805 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5806 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005807 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005808 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5809 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5810 Category = Category->getNextClassCategory())
5811 CategoryNames.insert(Category->getIdentifier());
5812
5813 // Add all of the categories we know about.
5814 Results.EnterNewScope();
5815 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5816 for (DeclContext::decl_iterator D = TU->decls_begin(),
5817 DEnd = TU->decls_end();
5818 D != DEnd; ++D)
5819 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5820 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005821 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005822 Results.ExitScope();
5823
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005824 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005825 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005826 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005827}
5828
5829void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005830 IdentifierInfo *ClassName,
5831 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005832 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005833
5834 // Find the corresponding interface. If we couldn't find the interface, the
5835 // program itself is ill-formed. However, we'll try to be helpful still by
5836 // providing the list of all of the categories we know about.
5837 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005838 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005839 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5840 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005841 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005842
Douglas Gregor218937c2011-02-01 19:23:04 +00005843 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005844 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005845 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005846
5847 // Add all of the categories that have have corresponding interface
5848 // declarations in this class and any of its superclasses, except for
5849 // already-implemented categories in the class itself.
5850 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5851 Results.EnterNewScope();
5852 bool IgnoreImplemented = true;
5853 while (Class) {
5854 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5855 Category = Category->getNextClassCategory())
5856 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5857 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005858 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005859
5860 Class = Class->getSuperClass();
5861 IgnoreImplemented = false;
5862 }
5863 Results.ExitScope();
5864
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005865 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005866 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005867 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005868}
Douglas Gregor322328b2009-11-18 22:32:06 +00005869
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005870void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005871 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005872 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005873 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005874
5875 // Figure out where this @synthesize lives.
5876 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005877 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005878 if (!Container ||
5879 (!isa<ObjCImplementationDecl>(Container) &&
5880 !isa<ObjCCategoryImplDecl>(Container)))
5881 return;
5882
5883 // Ignore any properties that have already been implemented.
Douglas Gregorb92a4082012-06-12 13:44:08 +00005884 Container = getContainerDef(Container);
5885 for (DeclContext::decl_iterator D = Container->decls_begin(),
Douglas Gregor322328b2009-11-18 22:32:06 +00005886 DEnd = Container->decls_end();
5887 D != DEnd; ++D)
5888 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5889 Results.Ignore(PropertyImpl->getPropertyDecl());
5890
5891 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005892 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005893 Results.EnterNewScope();
5894 if (ObjCImplementationDecl *ClassImpl
5895 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005896 AddObjCProperties(ClassImpl->getClassInterface(), false,
5897 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005898 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005899 else
5900 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005901 false, /*AllowNullaryMethods=*/false, CurContext,
5902 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005903 Results.ExitScope();
5904
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005905 HandleCodeCompleteResults(this, CodeCompleter,
5906 CodeCompletionContext::CCC_Other,
5907 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005908}
5909
5910void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005911 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005912 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005913 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005914 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00005915 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005916
5917 // Figure out where this @synthesize lives.
5918 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005919 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005920 if (!Container ||
5921 (!isa<ObjCImplementationDecl>(Container) &&
5922 !isa<ObjCCategoryImplDecl>(Container)))
5923 return;
5924
5925 // Figure out which interface we're looking into.
5926 ObjCInterfaceDecl *Class = 0;
5927 if (ObjCImplementationDecl *ClassImpl
5928 = dyn_cast<ObjCImplementationDecl>(Container))
5929 Class = ClassImpl->getClassInterface();
5930 else
5931 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5932 ->getClassInterface();
5933
Douglas Gregore8426052011-04-18 14:40:46 +00005934 // Determine the type of the property we're synthesizing.
5935 QualType PropertyType = Context.getObjCIdType();
5936 if (Class) {
5937 if (ObjCPropertyDecl *Property
5938 = Class->FindPropertyDeclaration(PropertyName)) {
5939 PropertyType
5940 = Property->getType().getNonReferenceType().getUnqualifiedType();
5941
5942 // Give preference to ivars
5943 Results.setPreferredType(PropertyType);
5944 }
5945 }
5946
Douglas Gregor322328b2009-11-18 22:32:06 +00005947 // Add all of the instance variables in this class and its superclasses.
5948 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005949 bool SawSimilarlyNamedIvar = false;
5950 std::string NameWithPrefix;
5951 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005952 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005953 std::string NameWithSuffix = PropertyName->getName().str();
5954 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005955 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005956 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5957 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005958 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5959
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005960 // Determine whether we've seen an ivar with a name similar to the
5961 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005962 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005963 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005964 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005965 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005966
5967 // Reduce the priority of this result by one, to give it a slight
5968 // advantage over other results whose names don't match so closely.
5969 if (Results.size() &&
5970 Results.data()[Results.size() - 1].Kind
5971 == CodeCompletionResult::RK_Declaration &&
5972 Results.data()[Results.size() - 1].Declaration == Ivar)
5973 Results.data()[Results.size() - 1].Priority--;
5974 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005975 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005976 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005977
5978 if (!SawSimilarlyNamedIvar) {
5979 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005980 // an ivar of the appropriate type.
5981 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005982 typedef CodeCompletionResult Result;
5983 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00005984 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
5985 Priority,CXAvailability_Available);
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005986
Douglas Gregor8987b232011-09-27 23:30:47 +00005987 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005988 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005989 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005990 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5991 Results.AddResult(Result(Builder.TakeString(), Priority,
5992 CXCursor_ObjCIvarDecl));
5993 }
5994
Douglas Gregor322328b2009-11-18 22:32:06 +00005995 Results.ExitScope();
5996
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005997 HandleCodeCompleteResults(this, CodeCompleter,
5998 CodeCompletionContext::CCC_Other,
5999 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00006000}
Douglas Gregore8f5a172010-04-07 00:21:17 +00006001
Douglas Gregor408be5a2010-08-25 01:08:01 +00006002// Mapping from selectors to the methods that implement that selector, along
6003// with the "in original class" flag.
6004typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
6005 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006006
6007/// \brief Find all of the methods that reside in the given container
6008/// (and its superclasses, protocols, etc.) that meet the given
6009/// criteria. Insert those methods into the map of known methods,
6010/// indexed by selector so they can be easily found.
6011static void FindImplementableMethods(ASTContext &Context,
6012 ObjCContainerDecl *Container,
6013 bool WantInstanceMethods,
6014 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00006015 KnownMethodsMap &KnownMethods,
6016 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006017 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregorb92a4082012-06-12 13:44:08 +00006018 // Make sure we have a definition; that's what we'll walk.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00006019 if (!IFace->hasDefinition())
6020 return;
Douglas Gregorb92a4082012-06-12 13:44:08 +00006021
6022 IFace = IFace->getDefinition();
6023 Container = IFace;
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00006024
Douglas Gregore8f5a172010-04-07 00:21:17 +00006025 const ObjCList<ObjCProtocolDecl> &Protocols
6026 = IFace->getReferencedProtocols();
6027 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00006028 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006029 I != E; ++I)
6030 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006031 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006032
Douglas Gregorea766182010-10-18 18:21:28 +00006033 // Add methods from any class extensions and categories.
6034 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
6035 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00006036 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
6037 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006038 KnownMethods, false);
6039
6040 // Visit the superclass.
6041 if (IFace->getSuperClass())
6042 FindImplementableMethods(Context, IFace->getSuperClass(),
6043 WantInstanceMethods, ReturnType,
6044 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006045 }
6046
6047 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6048 // Recurse into protocols.
6049 const ObjCList<ObjCProtocolDecl> &Protocols
6050 = Category->getReferencedProtocols();
6051 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00006052 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006053 I != E; ++I)
6054 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00006055 KnownMethods, InOriginalClass);
6056
6057 // If this category is the original class, jump to the interface.
6058 if (InOriginalClass && Category->getClassInterface())
6059 FindImplementableMethods(Context, Category->getClassInterface(),
6060 WantInstanceMethods, ReturnType, KnownMethods,
6061 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006062 }
6063
6064 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregorb92a4082012-06-12 13:44:08 +00006065 // Make sure we have a definition; that's what we'll walk.
6066 if (!Protocol->hasDefinition())
6067 return;
6068 Protocol = Protocol->getDefinition();
6069 Container = Protocol;
6070
6071 // Recurse into protocols.
6072 const ObjCList<ObjCProtocolDecl> &Protocols
6073 = Protocol->getReferencedProtocols();
6074 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6075 E = Protocols.end();
6076 I != E; ++I)
6077 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6078 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006079 }
6080
6081 // Add methods in this container. This operation occurs last because
6082 // we want the methods from this container to override any methods
6083 // we've previously seen with the same selector.
6084 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
6085 MEnd = Container->meth_end();
6086 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00006087 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006088 if (!ReturnType.isNull() &&
David Blaikie262bc182012-04-30 02:36:29 +00006089 !Context.hasSameUnqualifiedType(ReturnType, M->getResultType()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006090 continue;
6091
David Blaikie581deb32012-06-06 20:45:41 +00006092 KnownMethods[M->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006093 }
6094 }
6095}
6096
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006097/// \brief Add the parenthesized return or parameter type chunk to a code
6098/// completion string.
6099static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor90f5f472012-04-10 18:35:07 +00006100 unsigned ObjCDeclQuals,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006101 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006102 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006103 CodeCompletionBuilder &Builder) {
6104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor90f5f472012-04-10 18:35:07 +00006105 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6106 if (!Quals.empty())
6107 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor8987b232011-09-27 23:30:47 +00006108 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006109 Builder.getAllocator()));
6110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6111}
6112
6113/// \brief Determine whether the given class is or inherits from a class by
6114/// the given name.
6115static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006116 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006117 if (!Class)
6118 return false;
6119
6120 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6121 return true;
6122
6123 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6124}
6125
6126/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6127/// Key-Value Observing (KVO).
6128static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6129 bool IsInstanceMethod,
6130 QualType ReturnType,
6131 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006132 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006133 ResultBuilder &Results) {
6134 IdentifierInfo *PropName = Property->getIdentifier();
6135 if (!PropName || PropName->getLength() == 0)
6136 return;
6137
Douglas Gregor8987b232011-09-27 23:30:47 +00006138 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6139
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006140 // Builder that will create each code completion.
6141 typedef CodeCompletionResult Result;
6142 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006143 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006144
6145 // The selector table.
6146 SelectorTable &Selectors = Context.Selectors;
6147
6148 // The property name, copied into the code completion allocation region
6149 // on demand.
6150 struct KeyHolder {
6151 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006152 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006153 const char *CopiedKey;
6154
Chris Lattner5f9e2722011-07-23 10:55:15 +00006155 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006156 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6157
6158 operator const char *() {
6159 if (CopiedKey)
6160 return CopiedKey;
6161
6162 return CopiedKey = Allocator.CopyString(Key);
6163 }
6164 } Key(Allocator, PropName->getName());
6165
6166 // The uppercased name of the property name.
6167 std::string UpperKey = PropName->getName();
6168 if (!UpperKey.empty())
6169 UpperKey[0] = toupper(UpperKey[0]);
6170
6171 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6172 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6173 Property->getType());
6174 bool ReturnTypeMatchesVoid
6175 = ReturnType.isNull() || ReturnType->isVoidType();
6176
6177 // Add the normal accessor -(type)key.
6178 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00006179 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006180 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6181 if (ReturnType.isNull())
Douglas Gregor90f5f472012-04-10 18:35:07 +00006182 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6183 Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006184
6185 Builder.AddTypedTextChunk(Key);
6186 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6187 CXCursor_ObjCInstanceMethodDecl));
6188 }
6189
6190 // If we have an integral or boolean property (or the user has provided
6191 // an integral or boolean return type), add the accessor -(type)isKey.
6192 if (IsInstanceMethod &&
6193 ((!ReturnType.isNull() &&
6194 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6195 (ReturnType.isNull() &&
6196 (Property->getType()->isIntegerType() ||
6197 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006198 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006199 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006200 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006201 if (ReturnType.isNull()) {
6202 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6203 Builder.AddTextChunk("BOOL");
6204 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6205 }
6206
6207 Builder.AddTypedTextChunk(
6208 Allocator.CopyString(SelectorId->getName()));
6209 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6210 CXCursor_ObjCInstanceMethodDecl));
6211 }
6212 }
6213
6214 // Add the normal mutator.
6215 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6216 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006217 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006218 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006219 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006220 if (ReturnType.isNull()) {
6221 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6222 Builder.AddTextChunk("void");
6223 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6224 }
6225
6226 Builder.AddTypedTextChunk(
6227 Allocator.CopyString(SelectorId->getName()));
6228 Builder.AddTypedTextChunk(":");
Douglas Gregor90f5f472012-04-10 18:35:07 +00006229 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6230 Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006231 Builder.AddTextChunk(Key);
6232 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6233 CXCursor_ObjCInstanceMethodDecl));
6234 }
6235 }
6236
6237 // Indexed and unordered accessors
6238 unsigned IndexedGetterPriority = CCP_CodePattern;
6239 unsigned IndexedSetterPriority = CCP_CodePattern;
6240 unsigned UnorderedGetterPriority = CCP_CodePattern;
6241 unsigned UnorderedSetterPriority = CCP_CodePattern;
6242 if (const ObjCObjectPointerType *ObjCPointer
6243 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6244 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6245 // If this interface type is not provably derived from a known
6246 // collection, penalize the corresponding completions.
6247 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6248 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6249 if (!InheritsFromClassNamed(IFace, "NSArray"))
6250 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6251 }
6252
6253 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6254 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6255 if (!InheritsFromClassNamed(IFace, "NSSet"))
6256 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6257 }
6258 }
6259 } else {
6260 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6261 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6262 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6263 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6264 }
6265
6266 // Add -(NSUInteger)countOf<key>
6267 if (IsInstanceMethod &&
6268 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006269 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006270 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006271 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 if (ReturnType.isNull()) {
6273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6274 Builder.AddTextChunk("NSUInteger");
6275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6276 }
6277
6278 Builder.AddTypedTextChunk(
6279 Allocator.CopyString(SelectorId->getName()));
6280 Results.AddResult(Result(Builder.TakeString(),
6281 std::min(IndexedGetterPriority,
6282 UnorderedGetterPriority),
6283 CXCursor_ObjCInstanceMethodDecl));
6284 }
6285 }
6286
6287 // Indexed getters
6288 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6289 if (IsInstanceMethod &&
6290 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006291 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006292 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006293 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006294 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006295 if (ReturnType.isNull()) {
6296 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6297 Builder.AddTextChunk("id");
6298 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6299 }
6300
6301 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6302 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6303 Builder.AddTextChunk("NSUInteger");
6304 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6305 Builder.AddTextChunk("index");
6306 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6307 CXCursor_ObjCInstanceMethodDecl));
6308 }
6309 }
6310
6311 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6312 if (IsInstanceMethod &&
6313 (ReturnType.isNull() ||
6314 (ReturnType->isObjCObjectPointerType() &&
6315 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6316 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6317 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006318 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006319 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006320 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006321 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006322 if (ReturnType.isNull()) {
6323 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6324 Builder.AddTextChunk("NSArray *");
6325 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6326 }
6327
6328 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6329 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6330 Builder.AddTextChunk("NSIndexSet *");
6331 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6332 Builder.AddTextChunk("indexes");
6333 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6334 CXCursor_ObjCInstanceMethodDecl));
6335 }
6336 }
6337
6338 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6339 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006340 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006341 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006342 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006343 &Context.Idents.get("range")
6344 };
6345
Douglas Gregore74c25c2011-05-04 23:50:46 +00006346 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006347 if (ReturnType.isNull()) {
6348 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6349 Builder.AddTextChunk("void");
6350 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6351 }
6352
6353 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6354 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6355 Builder.AddPlaceholderChunk("object-type");
6356 Builder.AddTextChunk(" **");
6357 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6358 Builder.AddTextChunk("buffer");
6359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6360 Builder.AddTypedTextChunk("range:");
6361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6362 Builder.AddTextChunk("NSRange");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 Builder.AddTextChunk("inRange");
6365 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6366 CXCursor_ObjCInstanceMethodDecl));
6367 }
6368 }
6369
6370 // Mutable indexed accessors
6371
6372 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6373 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006374 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006375 IdentifierInfo *SelectorIds[2] = {
6376 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006377 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006378 };
6379
Douglas Gregore74c25c2011-05-04 23:50:46 +00006380 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 if (ReturnType.isNull()) {
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("void");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 }
6386
6387 Builder.AddTypedTextChunk("insertObject:");
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddPlaceholderChunk("object-type");
6390 Builder.AddTextChunk(" *");
6391 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6392 Builder.AddTextChunk("object");
6393 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6394 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6395 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6396 Builder.AddPlaceholderChunk("NSUInteger");
6397 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6398 Builder.AddTextChunk("index");
6399 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6400 CXCursor_ObjCInstanceMethodDecl));
6401 }
6402 }
6403
6404 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6405 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006406 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006407 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006408 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006409 &Context.Idents.get("atIndexes")
6410 };
6411
Douglas Gregore74c25c2011-05-04 23:50:46 +00006412 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006413 if (ReturnType.isNull()) {
6414 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6415 Builder.AddTextChunk("void");
6416 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6417 }
6418
6419 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6420 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6421 Builder.AddTextChunk("NSArray *");
6422 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6423 Builder.AddTextChunk("array");
6424 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6425 Builder.AddTypedTextChunk("atIndexes:");
6426 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6427 Builder.AddPlaceholderChunk("NSIndexSet *");
6428 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6429 Builder.AddTextChunk("indexes");
6430 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6431 CXCursor_ObjCInstanceMethodDecl));
6432 }
6433 }
6434
6435 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6436 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006437 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006438 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006439 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006440 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006441 if (ReturnType.isNull()) {
6442 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6443 Builder.AddTextChunk("void");
6444 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6445 }
6446
6447 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6448 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6449 Builder.AddTextChunk("NSUInteger");
6450 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6451 Builder.AddTextChunk("index");
6452 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6453 CXCursor_ObjCInstanceMethodDecl));
6454 }
6455 }
6456
6457 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6458 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006459 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006460 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006461 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006462 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006463 if (ReturnType.isNull()) {
6464 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6465 Builder.AddTextChunk("void");
6466 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6467 }
6468
6469 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6470 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6471 Builder.AddTextChunk("NSIndexSet *");
6472 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6473 Builder.AddTextChunk("indexes");
6474 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6475 CXCursor_ObjCInstanceMethodDecl));
6476 }
6477 }
6478
6479 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6480 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006481 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006482 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006483 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006484 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006485 &Context.Idents.get("withObject")
6486 };
6487
Douglas Gregore74c25c2011-05-04 23:50:46 +00006488 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006489 if (ReturnType.isNull()) {
6490 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6491 Builder.AddTextChunk("void");
6492 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6493 }
6494
6495 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6496 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6497 Builder.AddPlaceholderChunk("NSUInteger");
6498 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6499 Builder.AddTextChunk("index");
6500 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6501 Builder.AddTypedTextChunk("withObject:");
6502 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6503 Builder.AddTextChunk("id");
6504 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6505 Builder.AddTextChunk("object");
6506 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6507 CXCursor_ObjCInstanceMethodDecl));
6508 }
6509 }
6510
6511 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6512 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006513 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006514 = (Twine("replace") + UpperKey + "AtIndexes").str();
6515 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006516 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006517 &Context.Idents.get(SelectorName1),
6518 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006519 };
6520
Douglas Gregore74c25c2011-05-04 23:50:46 +00006521 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006522 if (ReturnType.isNull()) {
6523 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6524 Builder.AddTextChunk("void");
6525 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6526 }
6527
6528 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6529 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6530 Builder.AddPlaceholderChunk("NSIndexSet *");
6531 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6532 Builder.AddTextChunk("indexes");
6533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6534 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6535 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6536 Builder.AddTextChunk("NSArray *");
6537 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6538 Builder.AddTextChunk("array");
6539 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6540 CXCursor_ObjCInstanceMethodDecl));
6541 }
6542 }
6543
6544 // Unordered getters
6545 // - (NSEnumerator *)enumeratorOfKey
6546 if (IsInstanceMethod &&
6547 (ReturnType.isNull() ||
6548 (ReturnType->isObjCObjectPointerType() &&
6549 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6550 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6551 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006552 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006553 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006554 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006555 if (ReturnType.isNull()) {
6556 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6557 Builder.AddTextChunk("NSEnumerator *");
6558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6559 }
6560
6561 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6562 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6563 CXCursor_ObjCInstanceMethodDecl));
6564 }
6565 }
6566
6567 // - (type *)memberOfKey:(type *)object
6568 if (IsInstanceMethod &&
6569 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006570 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006571 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006572 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006573 if (ReturnType.isNull()) {
6574 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6575 Builder.AddPlaceholderChunk("object-type");
6576 Builder.AddTextChunk(" *");
6577 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6578 }
6579
6580 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6581 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6582 if (ReturnType.isNull()) {
6583 Builder.AddPlaceholderChunk("object-type");
6584 Builder.AddTextChunk(" *");
6585 } else {
6586 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006587 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006588 Builder.getAllocator()));
6589 }
6590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6591 Builder.AddTextChunk("object");
6592 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6593 CXCursor_ObjCInstanceMethodDecl));
6594 }
6595 }
6596
6597 // Mutable unordered accessors
6598 // - (void)addKeyObject:(type *)object
6599 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006600 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006601 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006602 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006603 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006604 if (ReturnType.isNull()) {
6605 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6606 Builder.AddTextChunk("void");
6607 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6608 }
6609
6610 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6611 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6612 Builder.AddPlaceholderChunk("object-type");
6613 Builder.AddTextChunk(" *");
6614 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6615 Builder.AddTextChunk("object");
6616 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6617 CXCursor_ObjCInstanceMethodDecl));
6618 }
6619 }
6620
6621 // - (void)addKey:(NSSet *)objects
6622 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006623 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006624 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006625 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006626 if (ReturnType.isNull()) {
6627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6628 Builder.AddTextChunk("void");
6629 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6630 }
6631
6632 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6633 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6634 Builder.AddTextChunk("NSSet *");
6635 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6636 Builder.AddTextChunk("objects");
6637 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6638 CXCursor_ObjCInstanceMethodDecl));
6639 }
6640 }
6641
6642 // - (void)removeKeyObject:(type *)object
6643 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006644 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006645 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006646 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006647 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006648 if (ReturnType.isNull()) {
6649 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6650 Builder.AddTextChunk("void");
6651 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6652 }
6653
6654 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6655 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6656 Builder.AddPlaceholderChunk("object-type");
6657 Builder.AddTextChunk(" *");
6658 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6659 Builder.AddTextChunk("object");
6660 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6661 CXCursor_ObjCInstanceMethodDecl));
6662 }
6663 }
6664
6665 // - (void)removeKey:(NSSet *)objects
6666 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006667 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006668 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006669 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006670 if (ReturnType.isNull()) {
6671 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6672 Builder.AddTextChunk("void");
6673 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6674 }
6675
6676 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6677 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6678 Builder.AddTextChunk("NSSet *");
6679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6680 Builder.AddTextChunk("objects");
6681 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6682 CXCursor_ObjCInstanceMethodDecl));
6683 }
6684 }
6685
6686 // - (void)intersectKey:(NSSet *)objects
6687 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006688 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006689 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006690 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006691 if (ReturnType.isNull()) {
6692 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6693 Builder.AddTextChunk("void");
6694 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6695 }
6696
6697 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6699 Builder.AddTextChunk("NSSet *");
6700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6701 Builder.AddTextChunk("objects");
6702 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6703 CXCursor_ObjCInstanceMethodDecl));
6704 }
6705 }
6706
6707 // Key-Value Observing
6708 // + (NSSet *)keyPathsForValuesAffectingKey
6709 if (!IsInstanceMethod &&
6710 (ReturnType.isNull() ||
6711 (ReturnType->isObjCObjectPointerType() &&
6712 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6713 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6714 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006715 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006716 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006717 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006718 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006719 if (ReturnType.isNull()) {
6720 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6721 Builder.AddTextChunk("NSSet *");
6722 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6723 }
6724
6725 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6726 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006727 CXCursor_ObjCClassMethodDecl));
6728 }
6729 }
6730
6731 // + (BOOL)automaticallyNotifiesObserversForKey
6732 if (!IsInstanceMethod &&
6733 (ReturnType.isNull() ||
6734 ReturnType->isIntegerType() ||
6735 ReturnType->isBooleanType())) {
6736 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006737 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006738 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6739 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6740 if (ReturnType.isNull()) {
6741 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6742 Builder.AddTextChunk("BOOL");
6743 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6744 }
6745
6746 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6747 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6748 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006749 }
6750 }
6751}
6752
Douglas Gregore8f5a172010-04-07 00:21:17 +00006753void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6754 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006755 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006756 // Determine the return type of the method we're declaring, if
6757 // provided.
6758 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006759 Decl *IDecl = 0;
6760 if (CurContext->isObjCContainer()) {
6761 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6762 IDecl = cast<Decl>(OCD);
6763 }
Douglas Gregorea766182010-10-18 18:21:28 +00006764 // Determine where we should start searching for methods.
6765 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006766 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006767 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006768 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6769 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006770 IsInImplementation = true;
6771 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006772 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006773 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006774 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006775 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006776 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006777 }
6778
6779 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006780 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006781 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006782 }
6783
Douglas Gregorea766182010-10-18 18:21:28 +00006784 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006785 HandleCodeCompleteResults(this, CodeCompleter,
6786 CodeCompletionContext::CCC_Other,
6787 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006788 return;
6789 }
6790
6791 // Find all of the methods that we could declare/implement here.
6792 KnownMethodsMap KnownMethods;
6793 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006794 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006795
Douglas Gregore8f5a172010-04-07 00:21:17 +00006796 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006797 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006798 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006799 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00006800 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006801 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006802 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006803 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6804 MEnd = KnownMethods.end();
6805 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006806 ObjCMethodDecl *Method = M->second.first;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006807 CodeCompletionBuilder Builder(Results.getAllocator(),
6808 Results.getCodeCompletionTUInfo());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006809
6810 // If the result type was not already provided, add it to the
6811 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006812 if (ReturnType.isNull())
Douglas Gregor90f5f472012-04-10 18:35:07 +00006813 AddObjCPassingTypeChunk(Method->getResultType(),
6814 Method->getObjCDeclQualifier(),
6815 Context, Policy,
6816 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006817
6818 Selector Sel = Method->getSelector();
6819
6820 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006821 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006822 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006823
6824 // Add parameters to the pattern.
6825 unsigned I = 0;
6826 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6827 PEnd = Method->param_end();
6828 P != PEnd; (void)++P, ++I) {
6829 // Add the part of the selector name.
6830 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006831 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006832 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006833 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6834 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006835 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006836 } else
6837 break;
6838
6839 // Add the parameter type.
Douglas Gregor90f5f472012-04-10 18:35:07 +00006840 AddObjCPassingTypeChunk((*P)->getOriginalType(),
6841 (*P)->getObjCDeclQualifier(),
6842 Context, Policy,
Douglas Gregor8987b232011-09-27 23:30:47 +00006843 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006844
6845 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006846 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006847 }
6848
6849 if (Method->isVariadic()) {
6850 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006851 Builder.AddChunk(CodeCompletionString::CK_Comma);
6852 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006853 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006854
Douglas Gregor447107d2010-05-28 00:57:46 +00006855 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006856 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6858 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6859 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006860 if (!Method->getResultType()->isVoidType()) {
6861 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006862 Builder.AddTextChunk("return");
6863 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6864 Builder.AddPlaceholderChunk("expression");
6865 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006866 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006867 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006868
Douglas Gregor218937c2011-02-01 19:23:04 +00006869 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6870 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006871 }
6872
Douglas Gregor408be5a2010-08-25 01:08:01 +00006873 unsigned Priority = CCP_CodePattern;
6874 if (!M->second.second)
6875 Priority += CCD_InBaseClass;
6876
Douglas Gregorba103062012-03-27 23:34:16 +00006877 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006878 }
6879
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006880 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6881 // the properties in this class and its categories.
David Blaikie4e4d0842012-03-11 07:00:24 +00006882 if (Context.getLangOpts().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006883 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006884 Containers.push_back(SearchDecl);
6885
Douglas Gregore74c25c2011-05-04 23:50:46 +00006886 VisitedSelectorSet KnownSelectors;
6887 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6888 MEnd = KnownMethods.end();
6889 M != MEnd; ++M)
6890 KnownSelectors.insert(M->first);
6891
6892
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006893 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6894 if (!IFace)
6895 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6896 IFace = Category->getClassInterface();
6897
6898 if (IFace) {
6899 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6900 Category = Category->getNextClassCategory())
6901 Containers.push_back(Category);
6902 }
6903
6904 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6905 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6906 PEnd = Containers[I]->prop_end();
6907 P != PEnd; ++P) {
David Blaikie581deb32012-06-06 20:45:41 +00006908 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006909 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006910 }
6911 }
6912 }
6913
Douglas Gregore8f5a172010-04-07 00:21:17 +00006914 Results.ExitScope();
6915
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006916 HandleCodeCompleteResults(this, CodeCompleter,
6917 CodeCompletionContext::CCC_Other,
6918 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006919}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006920
6921void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6922 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006923 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006924 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006925 IdentifierInfo **SelIdents,
6926 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006927 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006928 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006929 if (ExternalSource) {
6930 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6931 I != N; ++I) {
6932 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006933 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006934 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006935
6936 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006937 }
6938 }
6939
6940 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006941 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006942 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006943 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor218937c2011-02-01 19:23:04 +00006944 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006945
6946 if (ReturnTy)
6947 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006948
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006949 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006950 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6951 MEnd = MethodPool.end();
6952 M != MEnd; ++M) {
6953 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6954 &M->second.second;
6955 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006956 MethList = MethList->Next) {
6957 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6958 NumSelIdents))
6959 continue;
6960
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006961 if (AtParameterName) {
6962 // Suggest parameter names we've seen before.
6963 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6964 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6965 if (Param->getIdentifier()) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006966 CodeCompletionBuilder Builder(Results.getAllocator(),
6967 Results.getCodeCompletionTUInfo());
Douglas Gregordae68752011-02-01 22:57:45 +00006968 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006969 Param->getIdentifier()->getName()));
6970 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006971 }
6972 }
6973
6974 continue;
6975 }
6976
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006977 Result R(MethList->Method, 0);
6978 R.StartParameter = NumSelIdents;
6979 R.AllParametersAreInformative = false;
6980 R.DeclaringEntity = true;
6981 Results.MaybeAddResult(R, CurContext);
6982 }
6983 }
6984
6985 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006986 HandleCodeCompleteResults(this, CodeCompleter,
6987 CodeCompletionContext::CCC_Other,
6988 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006989}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006990
Douglas Gregorf29c5232010-08-24 22:20:20 +00006991void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006992 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006993 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006994 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006995 Results.EnterNewScope();
6996
6997 // #if <condition>
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00006998 CodeCompletionBuilder Builder(Results.getAllocator(),
6999 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00007000 Builder.AddTypedTextChunk("if");
7001 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7002 Builder.AddPlaceholderChunk("condition");
7003 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007004
7005 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007006 Builder.AddTypedTextChunk("ifdef");
7007 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7008 Builder.AddPlaceholderChunk("macro");
7009 Results.AddResult(Builder.TakeString());
7010
Douglas Gregorf44e8542010-08-24 19:08:16 +00007011 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007012 Builder.AddTypedTextChunk("ifndef");
7013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7014 Builder.AddPlaceholderChunk("macro");
7015 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007016
7017 if (InConditional) {
7018 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00007019 Builder.AddTypedTextChunk("elif");
7020 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7021 Builder.AddPlaceholderChunk("condition");
7022 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007023
7024 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00007025 Builder.AddTypedTextChunk("else");
7026 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007027
7028 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00007029 Builder.AddTypedTextChunk("endif");
7030 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007031 }
7032
7033 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007034 Builder.AddTypedTextChunk("include");
7035 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7036 Builder.AddTextChunk("\"");
7037 Builder.AddPlaceholderChunk("header");
7038 Builder.AddTextChunk("\"");
7039 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007040
7041 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007042 Builder.AddTypedTextChunk("include");
7043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7044 Builder.AddTextChunk("<");
7045 Builder.AddPlaceholderChunk("header");
7046 Builder.AddTextChunk(">");
7047 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007048
7049 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007050 Builder.AddTypedTextChunk("define");
7051 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7052 Builder.AddPlaceholderChunk("macro");
7053 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007054
7055 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00007056 Builder.AddTypedTextChunk("define");
7057 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7058 Builder.AddPlaceholderChunk("macro");
7059 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7060 Builder.AddPlaceholderChunk("args");
7061 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7062 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007063
7064 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00007065 Builder.AddTypedTextChunk("undef");
7066 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7067 Builder.AddPlaceholderChunk("macro");
7068 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007069
7070 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00007071 Builder.AddTypedTextChunk("line");
7072 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7073 Builder.AddPlaceholderChunk("number");
7074 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007075
7076 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00007077 Builder.AddTypedTextChunk("line");
7078 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7079 Builder.AddPlaceholderChunk("number");
7080 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7081 Builder.AddTextChunk("\"");
7082 Builder.AddPlaceholderChunk("filename");
7083 Builder.AddTextChunk("\"");
7084 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007085
7086 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00007087 Builder.AddTypedTextChunk("error");
7088 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7089 Builder.AddPlaceholderChunk("message");
7090 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007091
7092 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00007093 Builder.AddTypedTextChunk("pragma");
7094 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7095 Builder.AddPlaceholderChunk("arguments");
7096 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007097
David Blaikie4e4d0842012-03-11 07:00:24 +00007098 if (getLangOpts().ObjC1) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00007099 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007100 Builder.AddTypedTextChunk("import");
7101 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7102 Builder.AddTextChunk("\"");
7103 Builder.AddPlaceholderChunk("header");
7104 Builder.AddTextChunk("\"");
7105 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007106
7107 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007108 Builder.AddTypedTextChunk("import");
7109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7110 Builder.AddTextChunk("<");
7111 Builder.AddPlaceholderChunk("header");
7112 Builder.AddTextChunk(">");
7113 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007114 }
7115
7116 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00007117 Builder.AddTypedTextChunk("include_next");
7118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7119 Builder.AddTextChunk("\"");
7120 Builder.AddPlaceholderChunk("header");
7121 Builder.AddTextChunk("\"");
7122 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007123
7124 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00007125 Builder.AddTypedTextChunk("include_next");
7126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7127 Builder.AddTextChunk("<");
7128 Builder.AddPlaceholderChunk("header");
7129 Builder.AddTextChunk(">");
7130 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007131
7132 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00007133 Builder.AddTypedTextChunk("warning");
7134 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7135 Builder.AddPlaceholderChunk("message");
7136 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00007137
7138 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7139 // completions for them. And __include_macros is a Clang-internal extension
7140 // that we don't want to encourage anyone to use.
7141
7142 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7143 Results.ExitScope();
7144
Douglas Gregorf44e8542010-08-24 19:08:16 +00007145 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00007146 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00007147 Results.data(), Results.size());
7148}
7149
7150void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00007151 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00007152 S->getFnParent()? Sema::PCC_RecoveryInFunction
7153 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00007154}
7155
Douglas Gregorf29c5232010-08-24 22:20:20 +00007156void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00007157 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007158 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007159 IsDefinition? CodeCompletionContext::CCC_MacroName
7160 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007161 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7162 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007163 CodeCompletionBuilder Builder(Results.getAllocator(),
7164 Results.getCodeCompletionTUInfo());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007165 Results.EnterNewScope();
7166 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7167 MEnd = PP.macro_end();
7168 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00007169 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00007170 M->first->getName()));
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00007171 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7172 CCP_CodePattern,
7173 CXCursor_MacroDefinition));
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007174 }
7175 Results.ExitScope();
7176 } else if (IsDefinition) {
7177 // FIXME: Can we detect when the user just wrote an include guard above?
7178 }
7179
Douglas Gregor52779fb2010-09-23 23:01:17 +00007180 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00007181 Results.data(), Results.size());
7182}
7183
Douglas Gregorf29c5232010-08-24 22:20:20 +00007184void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00007185 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007186 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00007187 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00007188
7189 if (!CodeCompleter || CodeCompleter->includeMacros())
7190 AddMacroResults(PP, Results);
7191
7192 // defined (<macro>)
7193 Results.EnterNewScope();
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007194 CodeCompletionBuilder Builder(Results.getAllocator(),
7195 Results.getCodeCompletionTUInfo());
Douglas Gregor218937c2011-02-01 19:23:04 +00007196 Builder.AddTypedTextChunk("defined");
7197 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7198 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7199 Builder.AddPlaceholderChunk("macro");
7200 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7201 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00007202 Results.ExitScope();
7203
7204 HandleCodeCompleteResults(this, CodeCompleter,
7205 CodeCompletionContext::CCC_PreprocessorExpression,
7206 Results.data(), Results.size());
7207}
7208
7209void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7210 IdentifierInfo *Macro,
7211 MacroInfo *MacroInfo,
7212 unsigned Argument) {
7213 // FIXME: In the future, we could provide "overload" results, much like we
7214 // do for function calls.
7215
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00007216 // Now just ignore this. There will be another code-completion callback
7217 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00007218}
7219
Douglas Gregor55817af2010-08-25 17:04:25 +00007220void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00007221 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00007222 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00007223 0, 0);
7224}
7225
Douglas Gregordae68752011-02-01 22:57:45 +00007226void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007227 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner5f9e2722011-07-23 10:55:15 +00007228 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00007229 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7230 CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00007231 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7232 CodeCompletionDeclConsumer Consumer(Builder,
7233 Context.getTranslationUnitDecl());
7234 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7235 Consumer);
7236 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00007237
7238 if (!CodeCompleter || CodeCompleter->includeMacros())
7239 AddMacroResults(PP, Builder);
7240
7241 Results.clear();
7242 Results.insert(Results.end(),
7243 Builder.data(), Builder.data() + Builder.size());
7244}