blob: d910c6f8ad1b2fd052d3c7fe039821b26248b4ec [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/AST/DeclObjC.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Jordan Rose4938f272013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Douglas Gregor07f43572012-01-29 18:15:03 +000018#include "clang/Lex/HeaderSearch.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/CodeCompleteConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/Overload.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/ScopeInfo.h"
Douglas Gregor1154e272010-09-16 16:06:31 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000027#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000028#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000029#include "llvm/ADT/SmallString.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000030#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000031#include "llvm/ADT/StringSwitch.h"
Douglas Gregor67c692c2010-08-26 15:07:07 +000032#include "llvm/ADT/Twine.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000033#include <list>
34#include <map>
35#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000036
37using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000038using namespace sema;
Douglas Gregor2436e712009-09-17 21:32:03 +000039
Douglas Gregor3545ff42009-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).
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000048 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +000049
John McCall276321a2010-08-25 06:19:51 +000050 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-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.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000059 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
Douglas Gregor3545ff42009-09-21 16:56:56 +000060
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000061 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000062
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 Lattner0e62c1c2011-07-23 10:55:15 +000067 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000068
69 /// \brief Contains either the solitary NamedDecl * or a vector
70 /// of (declaration, index) pairs.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000071 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000072
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
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000080 void Add(const NamedDecl *ND, unsigned Index) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000081 if (DeclOrVector.isNull()) {
82 // 0 - > 1 elements: just set the single element information.
83 DeclOrVector = ND;
84 SingleDeclIndex = Index;
85 return;
86 }
87
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000088 if (const NamedDecl *PrevND =
89 DeclOrVector.dyn_cast<const NamedDecl *>()) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000090 // 1 -> 2 elements: create the vector of results and push in the
91 // existing declaration.
92 DeclIndexPairVector *Vec = new DeclIndexPairVector;
93 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
94 DeclOrVector = Vec;
95 }
96
97 // Add the new element to the end of the vector.
98 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
99 DeclIndexPair(ND, Index));
100 }
101
102 void Destroy() {
103 if (DeclIndexPairVector *Vec
104 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
105 delete Vec;
Craig Topperc3ec1492014-05-26 06:22:03 +0000106 DeclOrVector = ((NamedDecl *)nullptr);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000107 }
108 }
109
110 // Iteration.
111 class iterator;
112 iterator begin() const;
113 iterator end() const;
114 };
115
Douglas Gregor3545ff42009-09-21 16:56:56 +0000116 /// \brief A mapping from declaration names to the declarations that have
117 /// this name within a particular scope and their index within the list of
118 /// results.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000119 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000120
121 /// \brief The semantic analysis object for which results are being
122 /// produced.
123 Sema &SemaRef;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000124
125 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000126 CodeCompletionAllocator &Allocator;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000127
128 CodeCompletionTUInfo &CCTUInfo;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000129
130 /// \brief If non-NULL, a filter function used to remove any code-completion
131 /// results that are not desirable.
132 LookupFilter Filter;
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000133
134 /// \brief Whether we should allow declarations as
135 /// nested-name-specifiers that would otherwise be filtered out.
136 bool AllowNestedNameSpecifiers;
137
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000138 /// \brief If set, the type that we would prefer our resulting value
139 /// declarations to have.
140 ///
141 /// Closely matching the preferred type gives a boost to a result's
142 /// priority.
143 CanQualType PreferredType;
144
Douglas Gregor3545ff42009-09-21 16:56:56 +0000145 /// \brief A list of shadow maps, which is used to model name hiding at
146 /// different levels of, e.g., the inheritance hierarchy.
147 std::list<ShadowMap> ShadowMaps;
148
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000149 /// \brief If we're potentially referring to a C++ member function, the set
150 /// of qualifiers applied to the object type.
151 Qualifiers ObjectTypeQualifiers;
152
153 /// \brief Whether the \p ObjectTypeQualifiers field is active.
154 bool HasObjectTypeQualifiers;
155
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000156 /// \brief The selector that we prefer.
157 Selector PreferredSelector;
158
Douglas Gregor05fcf842010-11-02 20:36:02 +0000159 /// \brief The completion context in which we are gathering results.
Douglas Gregor50832e02010-09-20 22:39:41 +0000160 CodeCompletionContext CompletionContext;
161
James Dennett596e4752012-06-14 03:11:41 +0000162 /// \brief If we are in an instance method definition, the \@implementation
Douglas Gregor05fcf842010-11-02 20:36:02 +0000163 /// object.
164 ObjCImplementationDecl *ObjCImplementation;
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000165
Douglas Gregor50832e02010-09-20 22:39:41 +0000166 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor95887f92010-07-08 23:20:03 +0000167
Douglas Gregor0212fd72010-09-21 16:06:22 +0000168 void MaybeAddConstructorResults(Result R);
169
Douglas Gregor3545ff42009-09-21 16:56:56 +0000170 public:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000171 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000172 CodeCompletionTUInfo &CCTUInfo,
Douglas Gregor0ac41382010-09-23 23:01:17 +0000173 const CodeCompletionContext &CompletionContext,
Craig Topperc3ec1492014-05-26 06:22:03 +0000174 LookupFilter Filter = nullptr)
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000175 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
176 Filter(Filter),
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000177 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregor05fcf842010-11-02 20:36:02 +0000178 CompletionContext(CompletionContext),
Craig Topperc3ec1492014-05-26 06:22:03 +0000179 ObjCImplementation(nullptr)
Douglas Gregor05fcf842010-11-02 20:36:02 +0000180 {
181 // If this is an Objective-C instance method definition, dig out the
182 // corresponding implementation.
183 switch (CompletionContext.getKind()) {
184 case CodeCompletionContext::CCC_Expression:
185 case CodeCompletionContext::CCC_ObjCMessageReceiver:
186 case CodeCompletionContext::CCC_ParenthesizedExpression:
187 case CodeCompletionContext::CCC_Statement:
188 case CodeCompletionContext::CCC_Recovery:
189 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
190 if (Method->isInstanceMethod())
191 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
192 ObjCImplementation = Interface->getImplementation();
193 break;
194
195 default:
196 break;
197 }
198 }
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000199
200 /// \brief Determine the priority for a reference to the given declaration.
201 unsigned getBasePriority(const NamedDecl *D);
202
Douglas Gregorf64acca2010-05-25 21:41:55 +0000203 /// \brief Whether we should include code patterns in the completion
204 /// results.
205 bool includeCodePatterns() const {
206 return SemaRef.CodeCompleter &&
Douglas Gregorac322ec2010-08-27 21:18:54 +0000207 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregorf64acca2010-05-25 21:41:55 +0000208 }
209
Douglas Gregor3545ff42009-09-21 16:56:56 +0000210 /// \brief Set the filter used for code-completion results.
211 void setFilter(LookupFilter Filter) {
212 this->Filter = Filter;
213 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000214
215 Result *data() { return Results.empty()? nullptr : &Results.front(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000216 unsigned size() const { return Results.size(); }
217 bool empty() const { return Results.empty(); }
218
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000219 /// \brief Specify the preferred type.
220 void setPreferredType(QualType T) {
221 PreferredType = SemaRef.Context.getCanonicalType(T);
222 }
223
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000224 /// \brief Set the cv-qualifiers on the object type, for us in filtering
225 /// calls to member functions.
226 ///
227 /// When there are qualifiers in this set, they will be used to filter
228 /// out member functions that aren't available (because there will be a
229 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
230 /// match.
231 void setObjectTypeQualifiers(Qualifiers Quals) {
232 ObjectTypeQualifiers = Quals;
233 HasObjectTypeQualifiers = true;
234 }
235
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000236 /// \brief Set the preferred selector.
237 ///
238 /// When an Objective-C method declaration result is added, and that
239 /// method's selector matches this preferred selector, we give that method
240 /// a slight priority boost.
241 void setPreferredSelector(Selector Sel) {
242 PreferredSelector = Sel;
243 }
Douglas Gregor05fcf842010-11-02 20:36:02 +0000244
Douglas Gregor50832e02010-09-20 22:39:41 +0000245 /// \brief Retrieve the code-completion context for which results are
246 /// being collected.
247 const CodeCompletionContext &getCompletionContext() const {
248 return CompletionContext;
249 }
250
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000251 /// \brief Specify whether nested-name-specifiers are allowed.
252 void allowNestedNameSpecifiers(bool Allow = true) {
253 AllowNestedNameSpecifiers = Allow;
254 }
255
Douglas Gregor74661272010-09-21 00:03:25 +0000256 /// \brief Return the semantic analysis object for which we are collecting
257 /// code completion results.
258 Sema &getSema() const { return SemaRef; }
259
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000260 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000261 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000262
263 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000264
Douglas Gregor7c208612010-01-14 00:20:49 +0000265 /// \brief Determine whether the given declaration is at all interesting
266 /// as a code-completion result.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000267 ///
268 /// \param ND the declaration that we are inspecting.
269 ///
270 /// \param AsNestedNameSpecifier will be set true if this declaration is
271 /// only interesting when it is a nested-name-specifier.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000272 bool isInterestingDecl(const NamedDecl *ND,
273 bool &AsNestedNameSpecifier) const;
Douglas Gregore0717ab2010-01-14 00:41:07 +0000274
275 /// \brief Check whether the result is hidden by the Hiding declaration.
276 ///
277 /// \returns true if the result is hidden and cannot be found, false if
278 /// the hidden result could still be found. When false, \p R may be
279 /// modified to describe how the result can be found (e.g., via extra
280 /// qualification).
281 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000282 const NamedDecl *Hiding);
Douglas Gregore0717ab2010-01-14 00:41:07 +0000283
Douglas Gregor3545ff42009-09-21 16:56:56 +0000284 /// \brief Add a new result to this result set (if it isn't already in one
285 /// of the shadow maps), or replace an existing result (for, e.g., a
286 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000287 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000288 /// \param R the result to add (if it is unique).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000289 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000290 /// \param CurContext the context in which this result will be named.
Craig Topperc3ec1492014-05-26 06:22:03 +0000291 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
292
Douglas Gregorc580c522010-01-14 01:09:38 +0000293 /// \brief Add a new result to this result set, where we already know
Yaron Keren8fbe43982014-11-14 18:33:42 +0000294 /// the hiding declaration (if any).
Douglas Gregorc580c522010-01-14 01:09:38 +0000295 ///
296 /// \param R the result to add (if it is unique).
297 ///
298 /// \param CurContext the context in which this result will be named.
299 ///
300 /// \param Hiding the declaration that hides the result.
Douglas Gregor09bbc652010-01-14 15:47:35 +0000301 ///
302 /// \param InBaseClass whether the result was found in a base
303 /// class of the searched context.
304 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
305 bool InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +0000306
Douglas Gregor78a21012010-01-14 16:01:26 +0000307 /// \brief Add a new non-declaration result to this result set.
308 void AddResult(Result R);
309
Douglas Gregor3545ff42009-09-21 16:56:56 +0000310 /// \brief Enter into a new scope.
311 void EnterNewScope();
312
313 /// \brief Exit from the current scope.
314 void ExitScope();
315
Douglas Gregorbaf69612009-11-18 04:19:12 +0000316 /// \brief Ignore this declaration, if it is seen again.
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +0000317 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
Douglas Gregorbaf69612009-11-18 04:19:12 +0000318
Douglas Gregor3545ff42009-09-21 16:56:56 +0000319 /// \name Name lookup predicates
320 ///
321 /// These predicates can be passed to the name lookup functions to filter the
322 /// results of name lookup. All of the predicates have the same type, so that
323 ///
324 //@{
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000325 bool IsOrdinaryName(const NamedDecl *ND) const;
326 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
327 bool IsIntegralConstantValue(const NamedDecl *ND) const;
328 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
329 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
330 bool IsEnum(const NamedDecl *ND) const;
331 bool IsClassOrStruct(const NamedDecl *ND) const;
332 bool IsUnion(const NamedDecl *ND) const;
333 bool IsNamespace(const NamedDecl *ND) const;
334 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
335 bool IsType(const NamedDecl *ND) const;
336 bool IsMember(const NamedDecl *ND) const;
337 bool IsObjCIvar(const NamedDecl *ND) const;
338 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
339 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
340 bool IsObjCCollection(const NamedDecl *ND) const;
341 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000342 //@}
343 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000344}
Douglas Gregor3545ff42009-09-21 16:56:56 +0000345
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000346class ResultBuilder::ShadowMapEntry::iterator {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000347 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000348 unsigned SingleDeclIndex;
349
350public:
351 typedef DeclIndexPair value_type;
352 typedef value_type reference;
353 typedef std::ptrdiff_t difference_type;
354 typedef std::input_iterator_tag iterator_category;
355
356 class pointer {
357 DeclIndexPair Value;
358
359 public:
360 pointer(const DeclIndexPair &Value) : Value(Value) { }
361
362 const DeclIndexPair *operator->() const {
363 return &Value;
364 }
365 };
Craig Topperc3ec1492014-05-26 06:22:03 +0000366
367 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000368
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000369 iterator(const NamedDecl *SingleDecl, unsigned Index)
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000370 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
371
372 iterator(const DeclIndexPair *Iterator)
373 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
374
375 iterator &operator++() {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000376 if (DeclOrIterator.is<const NamedDecl *>()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000377 DeclOrIterator = (NamedDecl *)nullptr;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000378 SingleDeclIndex = 0;
379 return *this;
380 }
381
382 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
383 ++I;
384 DeclOrIterator = I;
385 return *this;
386 }
387
Chris Lattner9795b392010-09-04 18:12:20 +0000388 /*iterator operator++(int) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000389 iterator tmp(*this);
390 ++(*this);
391 return tmp;
Chris Lattner9795b392010-09-04 18:12:20 +0000392 }*/
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000393
394 reference operator*() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000395 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000396 return reference(ND, SingleDeclIndex);
397
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000398 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000399 }
400
401 pointer operator->() const {
402 return pointer(**this);
403 }
404
405 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000406 return X.DeclOrIterator.getOpaqueValue()
407 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000408 X.SingleDeclIndex == Y.SingleDeclIndex;
409 }
410
411 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000412 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000413 }
414};
415
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000416ResultBuilder::ShadowMapEntry::iterator
417ResultBuilder::ShadowMapEntry::begin() const {
418 if (DeclOrVector.isNull())
419 return iterator();
420
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000421 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000422 return iterator(ND, SingleDeclIndex);
423
424 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
425}
426
427ResultBuilder::ShadowMapEntry::iterator
428ResultBuilder::ShadowMapEntry::end() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000429 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000430 return iterator();
431
432 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
433}
434
Douglas Gregor2af2f672009-09-21 20:12:40 +0000435/// \brief Compute the qualification required to get from the current context
436/// (\p CurContext) to the target context (\p TargetContext).
437///
438/// \param Context the AST context in which the qualification will be used.
439///
440/// \param CurContext the context where an entity is being named, which is
441/// typically based on the current scope.
442///
443/// \param TargetContext the context in which the named entity actually
444/// resides.
445///
446/// \returns a nested name specifier that refers into the target context, or
447/// NULL if no qualification is needed.
448static NestedNameSpecifier *
449getRequiredQualification(ASTContext &Context,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000450 const DeclContext *CurContext,
451 const DeclContext *TargetContext) {
452 SmallVector<const DeclContext *, 4> TargetParents;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000453
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000454 for (const DeclContext *CommonAncestor = TargetContext;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000455 CommonAncestor && !CommonAncestor->Encloses(CurContext);
456 CommonAncestor = CommonAncestor->getLookupParent()) {
457 if (CommonAncestor->isTransparentContext() ||
458 CommonAncestor->isFunctionOrMethod())
459 continue;
460
461 TargetParents.push_back(CommonAncestor);
462 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000463
464 NestedNameSpecifier *Result = nullptr;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000465 while (!TargetParents.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000466 const DeclContext *Parent = TargetParents.pop_back_val();
467
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000468 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
Douglas Gregor68762e72010-08-23 21:17:50 +0000469 if (!Namespace->getIdentifier())
470 continue;
471
Douglas Gregor2af2f672009-09-21 20:12:40 +0000472 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregor68762e72010-08-23 21:17:50 +0000473 }
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000474 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000475 Result = NestedNameSpecifier::Create(Context, Result,
476 false,
477 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000478 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000479 return Result;
480}
481
Alp Toker034bbd52014-06-30 01:33:53 +0000482/// Determine whether \p Id is a name reserved for the implementation (C99
483/// 7.1.3, C++ [lib.global.names]).
484static bool isReservedName(const IdentifierInfo *Id) {
485 if (Id->getLength() < 2)
486 return false;
487 const char *Name = Id->getNameStart();
488 return Name[0] == '_' &&
489 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z'));
490}
491
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000492bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000493 bool &AsNestedNameSpecifier) const {
494 AsNestedNameSpecifier = false;
495
Richard Smithf2005d32015-12-29 23:34:32 +0000496 auto *Named = ND;
Douglas Gregor7c208612010-01-14 00:20:49 +0000497 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000498
499 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000500 if (!ND->getDeclName())
501 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000502
503 // Friend declarations and declarations introduced due to friends are never
504 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000505 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000506 return false;
507
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000508 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000509 if (isa<ClassTemplateSpecializationDecl>(ND) ||
510 isa<ClassTemplatePartialSpecializationDecl>(ND))
511 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000512
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000513 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000514 if (isa<UsingDecl>(ND))
515 return false;
516
517 // Some declarations have reserved names that we don't want to ever show.
Alp Toker034bbd52014-06-30 01:33:53 +0000518 // Filter out names reserved for the implementation if they come from a
519 // system header.
520 // TODO: Add a predicate for this.
521 if (const IdentifierInfo *Id = ND->getIdentifier())
522 if (isReservedName(Id) &&
523 (ND->getLocation().isInvalid() ||
524 SemaRef.SourceMgr.isInSystemHeader(
525 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregor7c208612010-01-14 00:20:49 +0000526 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000527
Douglas Gregor59cab552010-08-16 23:05:20 +0000528 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
Richard Smithf2005d32015-12-29 23:34:32 +0000529 (isa<NamespaceDecl>(ND) &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000530 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000531 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000532 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000533 AsNestedNameSpecifier = true;
534
Douglas Gregor3545ff42009-09-21 16:56:56 +0000535 // Filter out any unwanted results.
Richard Smithf2005d32015-12-29 23:34:32 +0000536 if (Filter && !(this->*Filter)(Named)) {
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000537 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000538 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000539 IsNestedNameSpecifier(ND) &&
540 (Filter != &ResultBuilder::IsMember ||
541 (isa<CXXRecordDecl>(ND) &&
542 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
543 AsNestedNameSpecifier = true;
544 return true;
545 }
546
Douglas Gregor7c208612010-01-14 00:20:49 +0000547 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000548 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000549 // ... then it must be interesting!
550 return true;
551}
552
Douglas Gregore0717ab2010-01-14 00:41:07 +0000553bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000554 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000555 // In C, there is no way to refer to a hidden name.
556 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
557 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000558 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000559 return true;
560
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000561 const DeclContext *HiddenCtx =
562 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000563
564 // There is no way to qualify a name declared in a function or method.
565 if (HiddenCtx->isFunctionOrMethod())
566 return true;
567
Sebastian Redl50c68252010-08-31 00:36:30 +0000568 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000569 return true;
570
571 // We can refer to the result with the appropriate qualification. Do it.
572 R.Hidden = true;
573 R.QualifierIsInformative = false;
574
575 if (!R.Qualifier)
576 R.Qualifier = getRequiredQualification(SemaRef.Context,
577 CurContext,
578 R.Declaration->getDeclContext());
579 return false;
580}
581
Douglas Gregor95887f92010-07-08 23:20:03 +0000582/// \brief A simplified classification of types used to determine whether two
583/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000584SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000585 switch (T->getTypeClass()) {
586 case Type::Builtin:
587 switch (cast<BuiltinType>(T)->getKind()) {
588 case BuiltinType::Void:
589 return STC_Void;
590
591 case BuiltinType::NullPtr:
592 return STC_Pointer;
593
594 case BuiltinType::Overload:
595 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000596 return STC_Other;
597
598 case BuiltinType::ObjCId:
599 case BuiltinType::ObjCClass:
600 case BuiltinType::ObjCSel:
601 return STC_ObjectiveC;
602
603 default:
604 return STC_Arithmetic;
605 }
David Blaikie8a40f702012-01-17 06:56:22 +0000606
Douglas Gregor95887f92010-07-08 23:20:03 +0000607 case Type::Complex:
608 return STC_Arithmetic;
609
610 case Type::Pointer:
611 return STC_Pointer;
612
613 case Type::BlockPointer:
614 return STC_Block;
615
616 case Type::LValueReference:
617 case Type::RValueReference:
618 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return STC_Array;
625
626 case Type::DependentSizedExtVector:
627 case Type::Vector:
628 case Type::ExtVector:
629 return STC_Arithmetic;
630
631 case Type::FunctionProto:
632 case Type::FunctionNoProto:
633 return STC_Function;
634
635 case Type::Record:
636 return STC_Record;
637
638 case Type::Enum:
639 return STC_Arithmetic;
640
641 case Type::ObjCObject:
642 case Type::ObjCInterface:
643 case Type::ObjCObjectPointer:
644 return STC_ObjectiveC;
645
646 default:
647 return STC_Other;
648 }
649}
650
651/// \brief Get the type that a given expression will have if this declaration
652/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000653QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000654 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
655
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000656 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000657 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000658 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000659 return C.getObjCInterfaceType(Iface);
660
661 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000662 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000663 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000664 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000665 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000666 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000667 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000668 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000669 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000670 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000671 T = Value->getType();
672 else
673 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000674
675 // Dig through references, function pointers, and block pointers to
676 // get down to the likely type of an expression when the entity is
677 // used.
678 do {
679 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
680 T = Ref->getPointeeType();
681 continue;
682 }
683
684 if (const PointerType *Pointer = T->getAs<PointerType>()) {
685 if (Pointer->getPointeeType()->isFunctionType()) {
686 T = Pointer->getPointeeType();
687 continue;
688 }
689
690 break;
691 }
692
693 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
694 T = Block->getPointeeType();
695 continue;
696 }
697
698 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000699 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000700 continue;
701 }
702
703 break;
704 } while (true);
705
706 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000707}
708
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000709unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
710 if (!ND)
711 return CCP_Unlikely;
712
713 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000714 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
715 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000716 // _cmd is relatively rare
717 if (const ImplicitParamDecl *ImplicitParam =
718 dyn_cast<ImplicitParamDecl>(ND))
719 if (ImplicitParam->getIdentifier() &&
720 ImplicitParam->getIdentifier()->isStr("_cmd"))
721 return CCP_ObjC_cmd;
722
723 return CCP_LocalDeclaration;
724 }
Richard Smith541b38b2013-09-20 01:15:31 +0000725
726 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000727 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
728 return CCP_MemberDeclaration;
729
730 // Content-based decisions.
731 if (isa<EnumConstantDecl>(ND))
732 return CCP_Constant;
733
Douglas Gregor52e0de42013-01-31 05:03:46 +0000734 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
735 // message receiver, or parenthesized expression context. There, it's as
736 // likely that the user will want to write a type as other declarations.
737 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
738 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
739 CompletionContext.getKind()
740 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
741 CompletionContext.getKind()
742 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000743 return CCP_Type;
744
745 return CCP_Declaration;
746}
747
Douglas Gregor50832e02010-09-20 22:39:41 +0000748void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
749 // If this is an Objective-C method declaration whose selector matches our
750 // preferred selector, give it a priority boost.
751 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000752 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000753 if (PreferredSelector == Method->getSelector())
754 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000755
Douglas Gregor50832e02010-09-20 22:39:41 +0000756 // If we have a preferred type, adjust the priority for results with exactly-
757 // matching or nearly-matching types.
758 if (!PreferredType.isNull()) {
759 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
760 if (!T.isNull()) {
761 CanQualType TC = SemaRef.Context.getCanonicalType(T);
762 // Check for exactly-matching types (modulo qualifiers).
763 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
764 R.Priority /= CCF_ExactTypeMatch;
765 // Check for nearly-matching types, based on classification of each.
766 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000767 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000768 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
769 R.Priority /= CCF_SimilarTypeMatch;
770 }
771 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000772}
773
Douglas Gregor0212fd72010-09-21 16:06:22 +0000774void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000776 !CompletionContext.wantConstructorResults())
777 return;
778
779 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000780 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000782 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000783 Record = ClassTemplate->getTemplatedDecl();
784 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
785 // Skip specializations and partial specializations.
786 if (isa<ClassTemplateSpecializationDecl>(Record))
787 return;
788 } else {
789 // There are no constructors here.
790 return;
791 }
792
793 Record = Record->getDefinition();
794 if (!Record)
795 return;
796
797
798 QualType RecordTy = Context.getTypeDeclType(Record);
799 DeclarationName ConstructorName
800 = Context.DeclarationNames.getCXXConstructorName(
801 Context.getCanonicalType(RecordTy));
Richard Smithcf4bdde2015-02-21 02:45:19 +0000802 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
803 for (DeclContext::lookup_iterator I = Ctors.begin(),
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000804 E = Ctors.end();
805 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000806 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000807 R.CursorKind = getCursorKindForDecl(R.Declaration);
808 Results.push_back(R);
809 }
810}
811
Douglas Gregor7c208612010-01-14 00:20:49 +0000812void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
813 assert(!ShadowMaps.empty() && "Must enter into a results scope");
814
815 if (R.Kind != Result::RK_Declaration) {
816 // For non-declaration results, just add the result.
817 Results.push_back(R);
818 return;
819 }
820
821 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000822 if (const UsingShadowDecl *Using =
823 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000824 MaybeAddResult(Result(Using->getTargetDecl(),
825 getBasePriority(Using->getTargetDecl()),
826 R.Qualifier),
827 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000828 return;
829 }
830
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000831 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000832 unsigned IDNS = CanonDecl->getIdentifierNamespace();
833
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000834 bool AsNestedNameSpecifier = false;
835 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000836 return;
837
Douglas Gregor0212fd72010-09-21 16:06:22 +0000838 // C++ constructors are never found by name lookup.
839 if (isa<CXXConstructorDecl>(R.Declaration))
840 return;
841
Douglas Gregor3545ff42009-09-21 16:56:56 +0000842 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000843 ShadowMapEntry::iterator I, IEnd;
844 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
845 if (NamePos != SMap.end()) {
846 I = NamePos->second.begin();
847 IEnd = NamePos->second.end();
848 }
849
850 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000851 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000852 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000853 if (ND->getCanonicalDecl() == CanonDecl) {
854 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000855 Results[Index].Declaration = R.Declaration;
856
Douglas Gregor3545ff42009-09-21 16:56:56 +0000857 // We're done.
858 return;
859 }
860 }
861
862 // This is a new declaration in this scope. However, check whether this
863 // declaration name is hidden by a similarly-named declaration in an outer
864 // scope.
865 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
866 --SMEnd;
867 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000868 ShadowMapEntry::iterator I, IEnd;
869 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
870 if (NamePos != SM->end()) {
871 I = NamePos->second.begin();
872 IEnd = NamePos->second.end();
873 }
874 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000875 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000876 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000877 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
878 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000879 continue;
880
881 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000882 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000883 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000884 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000885 continue;
886
887 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000888 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000889 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000890
891 break;
892 }
893 }
894
895 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000896 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000897 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000898
Douglas Gregore412a5a2009-09-23 22:26:46 +0000899 // If the filter is for nested-name-specifiers, then this result starts a
900 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000901 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000902 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000903 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000904 } else
905 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000906
Douglas Gregor5bf52692009-09-22 23:15:58 +0000907 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000908 if (R.QualifierIsInformative && !R.Qualifier &&
909 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000910 const DeclContext *Ctx = R.Declaration->getDeclContext();
911 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
913 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000914 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000915 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
916 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000917 else
918 R.QualifierIsInformative = false;
919 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000920
Douglas Gregor3545ff42009-09-21 16:56:56 +0000921 // Insert this result into the set of results and into the current shadow
922 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000923 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000924 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000925
926 if (!AsNestedNameSpecifier)
927 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000928}
929
Douglas Gregorc580c522010-01-14 01:09:38 +0000930void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000931 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000932 if (R.Kind != Result::RK_Declaration) {
933 // For non-declaration results, just add the result.
934 Results.push_back(R);
935 return;
936 }
937
Douglas Gregorc580c522010-01-14 01:09:38 +0000938 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000939 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000940 AddResult(Result(Using->getTargetDecl(),
941 getBasePriority(Using->getTargetDecl()),
942 R.Qualifier),
943 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000944 return;
945 }
946
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000947 bool AsNestedNameSpecifier = false;
948 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000949 return;
950
Douglas Gregor0212fd72010-09-21 16:06:22 +0000951 // C++ constructors are never found by name lookup.
952 if (isa<CXXConstructorDecl>(R.Declaration))
953 return;
954
Douglas Gregorc580c522010-01-14 01:09:38 +0000955 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
956 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000957
Douglas Gregorc580c522010-01-14 01:09:38 +0000958 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000959 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000960 return;
961
962 // If the filter is for nested-name-specifiers, then this result starts a
963 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000964 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000965 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000966 R.Priority = CCP_NestedNameSpecifier;
967 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000968 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
969 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000970 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000971 R.QualifierIsInformative = true;
972
Douglas Gregorc580c522010-01-14 01:09:38 +0000973 // If this result is supposed to have an informative qualifier, add one.
974 if (R.QualifierIsInformative && !R.Qualifier &&
975 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000976 const DeclContext *Ctx = R.Declaration->getDeclContext();
977 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000978 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
979 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000980 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000981 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000982 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000983 else
984 R.QualifierIsInformative = false;
985 }
986
Douglas Gregora2db7932010-05-26 22:00:08 +0000987 // Adjust the priority if this result comes from a base class.
988 if (InBaseClass)
989 R.Priority += CCD_InBaseClass;
990
Douglas Gregor50832e02010-09-20 22:39:41 +0000991 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000992
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000993 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000994 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000995 if (Method->isInstance()) {
996 Qualifiers MethodQuals
997 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
998 if (ObjectTypeQualifiers == MethodQuals)
999 R.Priority += CCD_ObjectQualifierMatch;
1000 else if (ObjectTypeQualifiers - MethodQuals) {
1001 // The method cannot be invoked, because doing so would drop
1002 // qualifiers.
1003 return;
1004 }
1005 }
1006
Douglas Gregorc580c522010-01-14 01:09:38 +00001007 // Insert this result into the set of results.
1008 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001009
1010 if (!AsNestedNameSpecifier)
1011 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001012}
1013
Douglas Gregor78a21012010-01-14 16:01:26 +00001014void ResultBuilder::AddResult(Result R) {
1015 assert(R.Kind != Result::RK_Declaration &&
1016 "Declaration results need more context");
1017 Results.push_back(R);
1018}
1019
Douglas Gregor3545ff42009-09-21 16:56:56 +00001020/// \brief Enter into a new scope.
Benjamin Kramer3204b152015-05-29 19:42:19 +00001021void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001022
1023/// \brief Exit from the current scope.
1024void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001025 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1026 EEnd = ShadowMaps.back().end();
1027 E != EEnd;
1028 ++E)
1029 E->second.Destroy();
1030
Douglas Gregor3545ff42009-09-21 16:56:56 +00001031 ShadowMaps.pop_back();
1032}
1033
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001034/// \brief Determines whether this given declaration will be found by
1035/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001036bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001037 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1038
Richard Smith541b38b2013-09-20 01:15:31 +00001039 // If name lookup finds a local extern declaration, then we are in a
1040 // context where it behaves like an ordinary name.
1041 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001042 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001043 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001044 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001045 if (isa<ObjCIvarDecl>(ND))
1046 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001047 }
1048
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001049 return ND->getIdentifierNamespace() & IDNS;
1050}
1051
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001052/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001053/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001054bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001055 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1056 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1057 return false;
1058
Richard Smith541b38b2013-09-20 01:15:31 +00001059 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001061 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001062 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001063 if (isa<ObjCIvarDecl>(ND))
1064 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001065 }
1066
Douglas Gregor70febae2010-05-28 00:49:12 +00001067 return ND->getIdentifierNamespace() & IDNS;
1068}
1069
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001070bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001071 if (!IsOrdinaryNonTypeName(ND))
1072 return 0;
1073
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001074 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001075 if (VD->getType()->isIntegralOrEnumerationType())
1076 return true;
1077
1078 return false;
1079}
1080
Douglas Gregor70febae2010-05-28 00:49:12 +00001081/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001082/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001083bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001084 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1085
Richard Smith541b38b2013-09-20 01:15:31 +00001086 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001087 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001088 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001089
1090 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001091 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1092 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001093}
1094
Douglas Gregor3545ff42009-09-21 16:56:56 +00001095/// \brief Determines whether the given declaration is suitable as the
1096/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001097bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001098 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001099 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100 ND = ClassTemplate->getTemplatedDecl();
1101
1102 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1103}
1104
1105/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001106bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001107 return isa<EnumDecl>(ND);
1108}
1109
1110/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001111bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001112 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001113 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001114 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001115
1116 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001117 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001118 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001119 RD->getTagKind() == TTK_Struct ||
1120 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001121
1122 return false;
1123}
1124
1125/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001126bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001127 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001128 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001129 ND = ClassTemplate->getTemplatedDecl();
1130
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001131 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001132 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001133
1134 return false;
1135}
1136
1137/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001138bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001139 return isa<NamespaceDecl>(ND);
1140}
1141
1142/// \brief Determines whether the given declaration is a namespace or
1143/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001144bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001145 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001146}
1147
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001148/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001149bool ResultBuilder::IsType(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001150 ND = ND->getUnderlyingDecl();
Douglas Gregor99fa2642010-08-24 01:06:58 +00001151 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001152}
1153
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001154/// \brief Determines which members of a class should be visible via
1155/// "." or "->". Only value declarations, nested name specifiers, and
1156/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001157bool ResultBuilder::IsMember(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001158 ND = ND->getUnderlyingDecl();
Douglas Gregor70788392009-12-11 18:14:22 +00001159 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
Richard Smithf2005d32015-12-29 23:34:32 +00001160 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001161}
1162
Douglas Gregora817a192010-05-27 23:06:34 +00001163static bool isObjCReceiverType(ASTContext &C, QualType T) {
1164 T = C.getCanonicalType(T);
1165 switch (T->getTypeClass()) {
1166 case Type::ObjCObject:
1167 case Type::ObjCInterface:
1168 case Type::ObjCObjectPointer:
1169 return true;
1170
1171 case Type::Builtin:
1172 switch (cast<BuiltinType>(T)->getKind()) {
1173 case BuiltinType::ObjCId:
1174 case BuiltinType::ObjCClass:
1175 case BuiltinType::ObjCSel:
1176 return true;
1177
1178 default:
1179 break;
1180 }
1181 return false;
1182
1183 default:
1184 break;
1185 }
1186
David Blaikiebbafb8a2012-03-11 07:00:24 +00001187 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001188 return false;
1189
1190 // FIXME: We could perform more analysis here to determine whether a
1191 // particular class type has any conversions to Objective-C types. For now,
1192 // just accept all class types.
1193 return T->isDependentType() || T->isRecordType();
1194}
1195
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001196bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001197 QualType T = getDeclUsageType(SemaRef.Context, ND);
1198 if (T.isNull())
1199 return false;
1200
1201 T = SemaRef.Context.getBaseElementType(T);
1202 return isObjCReceiverType(SemaRef.Context, T);
1203}
1204
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001205bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001206 if (IsObjCMessageReceiver(ND))
1207 return true;
1208
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001209 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001210 if (!Var)
1211 return false;
1212
1213 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1214}
1215
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001216bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001217 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1218 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001219 return false;
1220
1221 QualType T = getDeclUsageType(SemaRef.Context, ND);
1222 if (T.isNull())
1223 return false;
1224
1225 T = SemaRef.Context.getBaseElementType(T);
1226 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1227 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001229}
Douglas Gregora817a192010-05-27 23:06:34 +00001230
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001231bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001232 return false;
1233}
1234
James Dennettf1243872012-06-17 05:33:25 +00001235/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001236/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001237bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001238 return isa<ObjCIvarDecl>(ND);
1239}
1240
Douglas Gregorc580c522010-01-14 01:09:38 +00001241namespace {
1242 /// \brief Visible declaration consumer that adds a code-completion result
1243 /// for each visible declaration.
1244 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1245 ResultBuilder &Results;
1246 DeclContext *CurContext;
1247
1248 public:
1249 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1250 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001251
1252 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1253 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001254 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001255 if (Ctx)
1256 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001257
1258 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1259 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001260 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001261 }
1262 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001263}
Douglas Gregorc580c522010-01-14 01:09:38 +00001264
Douglas Gregor3545ff42009-09-21 16:56:56 +00001265/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001266static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001267 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001268 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001269 Results.AddResult(Result("short", CCP_Type));
1270 Results.AddResult(Result("long", CCP_Type));
1271 Results.AddResult(Result("signed", CCP_Type));
1272 Results.AddResult(Result("unsigned", CCP_Type));
1273 Results.AddResult(Result("void", CCP_Type));
1274 Results.AddResult(Result("char", CCP_Type));
1275 Results.AddResult(Result("int", CCP_Type));
1276 Results.AddResult(Result("float", CCP_Type));
1277 Results.AddResult(Result("double", CCP_Type));
1278 Results.AddResult(Result("enum", CCP_Type));
1279 Results.AddResult(Result("struct", CCP_Type));
1280 Results.AddResult(Result("union", CCP_Type));
1281 Results.AddResult(Result("const", CCP_Type));
1282 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001283
Douglas Gregor3545ff42009-09-21 16:56:56 +00001284 if (LangOpts.C99) {
1285 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001286 Results.AddResult(Result("_Complex", CCP_Type));
1287 Results.AddResult(Result("_Imaginary", CCP_Type));
1288 Results.AddResult(Result("_Bool", CCP_Type));
1289 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001290 }
1291
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001292 CodeCompletionBuilder Builder(Results.getAllocator(),
1293 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001294 if (LangOpts.CPlusPlus) {
1295 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001296 Results.AddResult(Result("bool", CCP_Type +
1297 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001298 Results.AddResult(Result("class", CCP_Type));
1299 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001300
Douglas Gregorf4c33342010-05-28 00:22:41 +00001301 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001302 Builder.AddTypedTextChunk("typename");
1303 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1304 Builder.AddPlaceholderChunk("qualifier");
1305 Builder.AddTextChunk("::");
1306 Builder.AddPlaceholderChunk("name");
1307 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001308
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001309 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001310 Results.AddResult(Result("auto", CCP_Type));
1311 Results.AddResult(Result("char16_t", CCP_Type));
1312 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001313
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001314 Builder.AddTypedTextChunk("decltype");
1315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1316 Builder.AddPlaceholderChunk("expression");
1317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1318 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001319 }
1320 }
1321
1322 // GNU extensions
1323 if (LangOpts.GNUMode) {
1324 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001325 // Results.AddResult(Result("_Decimal32"));
1326 // Results.AddResult(Result("_Decimal64"));
1327 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001328
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001329 Builder.AddTypedTextChunk("typeof");
1330 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1331 Builder.AddPlaceholderChunk("expression");
1332 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001333
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001334 Builder.AddTypedTextChunk("typeof");
1335 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1336 Builder.AddPlaceholderChunk("type");
1337 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1338 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001339 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001340
1341 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001342 Results.AddResult(Result("_Nonnull", CCP_Type));
1343 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1344 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001345}
1346
John McCallfaf5fb42010-08-26 23:41:50 +00001347static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001348 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001349 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001350 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001351 // Note: we don't suggest either "auto" or "register", because both
1352 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1353 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001354 Results.AddResult(Result("extern"));
1355 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001356}
1357
John McCallfaf5fb42010-08-26 23:41:50 +00001358static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001359 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001361 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001362 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001363 case Sema::PCC_Class:
1364 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001365 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001366 Results.AddResult(Result("explicit"));
1367 Results.AddResult(Result("friend"));
1368 Results.AddResult(Result("mutable"));
1369 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001370 }
1371 // Fall through
1372
John McCallfaf5fb42010-08-26 23:41:50 +00001373 case Sema::PCC_ObjCInterface:
1374 case Sema::PCC_ObjCImplementation:
1375 case Sema::PCC_Namespace:
1376 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001377 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001378 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001379 break;
1380
John McCallfaf5fb42010-08-26 23:41:50 +00001381 case Sema::PCC_ObjCInstanceVariableList:
1382 case Sema::PCC_Expression:
1383 case Sema::PCC_Statement:
1384 case Sema::PCC_ForInit:
1385 case Sema::PCC_Condition:
1386 case Sema::PCC_RecoveryInFunction:
1387 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001388 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001389 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001390 break;
1391 }
1392}
1393
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001394static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1395static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1396static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001397 ResultBuilder &Results,
1398 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001399static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001400 ResultBuilder &Results,
1401 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001402static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001403 ResultBuilder &Results,
1404 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001405static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001406
Douglas Gregorf4c33342010-05-28 00:22:41 +00001407static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001408 CodeCompletionBuilder Builder(Results.getAllocator(),
1409 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001410 Builder.AddTypedTextChunk("typedef");
1411 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1412 Builder.AddPlaceholderChunk("type");
1413 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1414 Builder.AddPlaceholderChunk("name");
1415 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001416}
1417
John McCallfaf5fb42010-08-26 23:41:50 +00001418static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001419 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001420 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001421 case Sema::PCC_Namespace:
1422 case Sema::PCC_Class:
1423 case Sema::PCC_ObjCInstanceVariableList:
1424 case Sema::PCC_Template:
1425 case Sema::PCC_MemberTemplate:
1426 case Sema::PCC_Statement:
1427 case Sema::PCC_RecoveryInFunction:
1428 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001429 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001430 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001431 return true;
1432
John McCallfaf5fb42010-08-26 23:41:50 +00001433 case Sema::PCC_Expression:
1434 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001435 return LangOpts.CPlusPlus;
1436
1437 case Sema::PCC_ObjCInterface:
1438 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001439 return false;
1440
John McCallfaf5fb42010-08-26 23:41:50 +00001441 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001442 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001443 }
David Blaikie8a40f702012-01-17 06:56:22 +00001444
1445 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001446}
1447
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001448static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1449 const Preprocessor &PP) {
1450 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001451 Policy.AnonymousTagLocations = false;
1452 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001453 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001454 return Policy;
1455}
1456
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001457/// \brief Retrieve a printing policy suitable for code completion.
1458static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1459 return getCompletionPrintingPolicy(S.Context, S.PP);
1460}
1461
Douglas Gregore5c79d52011-10-18 21:20:17 +00001462/// \brief Retrieve the string representation of the given type as a string
1463/// that has the appropriate lifetime for code completion.
1464///
1465/// This routine provides a fast path where we provide constant strings for
1466/// common type names.
1467static const char *GetCompletionTypeString(QualType T,
1468 ASTContext &Context,
1469 const PrintingPolicy &Policy,
1470 CodeCompletionAllocator &Allocator) {
1471 if (!T.getLocalQualifiers()) {
1472 // Built-in type names are constant strings.
1473 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001474 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001475
1476 // Anonymous tag types are constant strings.
1477 if (const TagType *TagT = dyn_cast<TagType>(T))
1478 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001479 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001480 switch (Tag->getTagKind()) {
1481 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001482 case TTK_Interface: return "__interface <anonymous>";
1483 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001484 case TTK_Union: return "union <anonymous>";
1485 case TTK_Enum: return "enum <anonymous>";
1486 }
1487 }
1488 }
1489
1490 // Slow path: format the type as a string.
1491 std::string Result;
1492 T.getAsStringInternal(Result, Policy);
1493 return Allocator.CopyString(Result);
1494}
1495
Douglas Gregord8c61782012-02-15 15:34:24 +00001496/// \brief Add a completion for "this", if we're in a member function.
1497static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1498 QualType ThisTy = S.getCurrentThisType();
1499 if (ThisTy.isNull())
1500 return;
1501
1502 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001503 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001504 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1505 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1506 S.Context,
1507 Policy,
1508 Allocator));
1509 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001510 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001511}
1512
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001513/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001514static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001515 Scope *S,
1516 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001517 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001518 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001519 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001520
John McCall276321a2010-08-25 06:19:51 +00001521 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001522 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001523 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001524 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001525 if (Results.includeCodePatterns()) {
1526 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001527 Builder.AddTypedTextChunk("namespace");
1528 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1529 Builder.AddPlaceholderChunk("identifier");
1530 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1531 Builder.AddPlaceholderChunk("declarations");
1532 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1533 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1534 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001535 }
1536
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001537 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("namespace");
1539 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1540 Builder.AddPlaceholderChunk("name");
1541 Builder.AddChunk(CodeCompletionString::CK_Equal);
1542 Builder.AddPlaceholderChunk("namespace");
1543 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001544
1545 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001546 Builder.AddTypedTextChunk("using");
1547 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1548 Builder.AddTextChunk("namespace");
1549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1550 Builder.AddPlaceholderChunk("identifier");
1551 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001552
1553 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001554 Builder.AddTypedTextChunk("asm");
1555 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1556 Builder.AddPlaceholderChunk("string-literal");
1557 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1558 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001559
Douglas Gregorf4c33342010-05-28 00:22:41 +00001560 if (Results.includeCodePatterns()) {
1561 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001562 Builder.AddTypedTextChunk("template");
1563 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1564 Builder.AddPlaceholderChunk("declaration");
1565 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001566 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001567 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001568
David Blaikiebbafb8a2012-03-11 07:00:24 +00001569 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001570 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001571
Douglas Gregorf4c33342010-05-28 00:22:41 +00001572 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001573 // Fall through
1574
John McCallfaf5fb42010-08-26 23:41:50 +00001575 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001577 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001578 Builder.AddTypedTextChunk("using");
1579 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1580 Builder.AddPlaceholderChunk("qualifier");
1581 Builder.AddTextChunk("::");
1582 Builder.AddPlaceholderChunk("name");
1583 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001584
Douglas Gregorf4c33342010-05-28 00:22:41 +00001585 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001586 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001587 Builder.AddTypedTextChunk("using");
1588 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1589 Builder.AddTextChunk("typename");
1590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1591 Builder.AddPlaceholderChunk("qualifier");
1592 Builder.AddTextChunk("::");
1593 Builder.AddPlaceholderChunk("name");
1594 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001595 }
1596
John McCallfaf5fb42010-08-26 23:41:50 +00001597 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001598 AddTypedefResult(Results);
1599
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001600 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001601 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001602 if (Results.includeCodePatterns())
1603 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001604 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001605
1606 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001607 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001608 if (Results.includeCodePatterns())
1609 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001610 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001611
1612 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001613 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001614 if (Results.includeCodePatterns())
1615 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001616 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001617 }
1618 }
1619 // Fall through
1620
John McCallfaf5fb42010-08-26 23:41:50 +00001621 case Sema::PCC_Template:
1622 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001623 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001624 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001625 Builder.AddTypedTextChunk("template");
1626 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1627 Builder.AddPlaceholderChunk("parameters");
1628 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1629 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001630 }
1631
David Blaikiebbafb8a2012-03-11 07:00:24 +00001632 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1633 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001634 break;
1635
John McCallfaf5fb42010-08-26 23:41:50 +00001636 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001637 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1638 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1639 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001640 break;
1641
John McCallfaf5fb42010-08-26 23:41:50 +00001642 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001643 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1644 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1645 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001646 break;
1647
John McCallfaf5fb42010-08-26 23:41:50 +00001648 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001649 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001650 break;
1651
John McCallfaf5fb42010-08-26 23:41:50 +00001652 case Sema::PCC_RecoveryInFunction:
1653 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001654 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001655
David Blaikiebbafb8a2012-03-11 07:00:24 +00001656 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1657 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("try");
1659 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1660 Builder.AddPlaceholderChunk("statements");
1661 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1662 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1663 Builder.AddTextChunk("catch");
1664 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1665 Builder.AddPlaceholderChunk("declaration");
1666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1667 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1668 Builder.AddPlaceholderChunk("statements");
1669 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1670 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1671 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001672 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001674 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001675
Douglas Gregorf64acca2010-05-25 21:41:55 +00001676 if (Results.includeCodePatterns()) {
1677 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001678 Builder.AddTypedTextChunk("if");
1679 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001680 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001681 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001682 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddPlaceholderChunk("expression");
1684 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1685 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1686 Builder.AddPlaceholderChunk("statements");
1687 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1688 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1689 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001690
Douglas Gregorf64acca2010-05-25 21:41:55 +00001691 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001692 Builder.AddTypedTextChunk("switch");
1693 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001694 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001695 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001696 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001697 Builder.AddPlaceholderChunk("expression");
1698 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1699 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1700 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1701 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1702 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001703 }
1704
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001705 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001706 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001707 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001708 Builder.AddTypedTextChunk("case");
1709 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1710 Builder.AddPlaceholderChunk("expression");
1711 Builder.AddChunk(CodeCompletionString::CK_Colon);
1712 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001713
1714 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001715 Builder.AddTypedTextChunk("default");
1716 Builder.AddChunk(CodeCompletionString::CK_Colon);
1717 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001718 }
1719
Douglas Gregorf64acca2010-05-25 21:41:55 +00001720 if (Results.includeCodePatterns()) {
1721 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001722 Builder.AddTypedTextChunk("while");
1723 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001724 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001725 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001726 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001727 Builder.AddPlaceholderChunk("expression");
1728 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1729 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1730 Builder.AddPlaceholderChunk("statements");
1731 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1732 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1733 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001734
1735 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001736 Builder.AddTypedTextChunk("do");
1737 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1738 Builder.AddPlaceholderChunk("statements");
1739 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1740 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1741 Builder.AddTextChunk("while");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1743 Builder.AddPlaceholderChunk("expression");
1744 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1745 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001746
Douglas Gregorf64acca2010-05-25 21:41:55 +00001747 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001748 Builder.AddTypedTextChunk("for");
1749 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001750 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001751 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001752 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddPlaceholderChunk("init-expression");
1754 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1755 Builder.AddPlaceholderChunk("condition");
1756 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1757 Builder.AddPlaceholderChunk("inc-expression");
1758 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1759 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1760 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1761 Builder.AddPlaceholderChunk("statements");
1762 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1763 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1764 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001765 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001766
1767 if (S->getContinueParent()) {
1768 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001769 Builder.AddTypedTextChunk("continue");
1770 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001771 }
1772
1773 if (S->getBreakParent()) {
1774 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001775 Builder.AddTypedTextChunk("break");
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001777 }
1778
1779 // "return expression ;" or "return ;", depending on whether we
1780 // know the function is void or not.
1781 bool isVoid = false;
1782 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001783 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001784 else if (ObjCMethodDecl *Method
1785 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001786 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001787 else if (SemaRef.getCurBlock() &&
1788 !SemaRef.getCurBlock()->ReturnType.isNull())
1789 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001790 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001791 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1793 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001794 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001795 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001796
Douglas Gregorf4c33342010-05-28 00:22:41 +00001797 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001798 Builder.AddTypedTextChunk("goto");
1799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1800 Builder.AddPlaceholderChunk("label");
1801 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001802
Douglas Gregorf4c33342010-05-28 00:22:41 +00001803 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001804 Builder.AddTypedTextChunk("using");
1805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1806 Builder.AddTextChunk("namespace");
1807 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1808 Builder.AddPlaceholderChunk("identifier");
1809 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001810 }
1811
1812 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001813 case Sema::PCC_ForInit:
1814 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001815 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001816 // Fall through: conditions and statements can have expressions.
1817
Douglas Gregor5e35d592010-09-14 23:59:36 +00001818 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001819 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001820 CCC == Sema::PCC_ParenthesizedExpression) {
1821 // (__bridge <type>)<expression>
1822 Builder.AddTypedTextChunk("__bridge");
1823 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1824 Builder.AddPlaceholderChunk("type");
1825 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1826 Builder.AddPlaceholderChunk("expression");
1827 Results.AddResult(Result(Builder.TakeString()));
1828
1829 // (__bridge_transfer <Objective-C type>)<expression>
1830 Builder.AddTypedTextChunk("__bridge_transfer");
1831 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1832 Builder.AddPlaceholderChunk("Objective-C type");
1833 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1834 Builder.AddPlaceholderChunk("expression");
1835 Results.AddResult(Result(Builder.TakeString()));
1836
1837 // (__bridge_retained <CF type>)<expression>
1838 Builder.AddTypedTextChunk("__bridge_retained");
1839 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1840 Builder.AddPlaceholderChunk("CF type");
1841 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1842 Builder.AddPlaceholderChunk("expression");
1843 Results.AddResult(Result(Builder.TakeString()));
1844 }
1845 // Fall through
1846
John McCallfaf5fb42010-08-26 23:41:50 +00001847 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001848 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001849 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001850 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001851
Douglas Gregore5c79d52011-10-18 21:20:17 +00001852 // true
1853 Builder.AddResultTypeChunk("bool");
1854 Builder.AddTypedTextChunk("true");
1855 Results.AddResult(Result(Builder.TakeString()));
1856
1857 // false
1858 Builder.AddResultTypeChunk("bool");
1859 Builder.AddTypedTextChunk("false");
1860 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001861
David Blaikiebbafb8a2012-03-11 07:00:24 +00001862 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001863 // dynamic_cast < type-id > ( expression )
1864 Builder.AddTypedTextChunk("dynamic_cast");
1865 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1866 Builder.AddPlaceholderChunk("type");
1867 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1868 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1869 Builder.AddPlaceholderChunk("expression");
1870 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1871 Results.AddResult(Result(Builder.TakeString()));
1872 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001873
1874 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001875 Builder.AddTypedTextChunk("static_cast");
1876 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1877 Builder.AddPlaceholderChunk("type");
1878 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1879 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1880 Builder.AddPlaceholderChunk("expression");
1881 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1882 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001883
Douglas Gregorf4c33342010-05-28 00:22:41 +00001884 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001885 Builder.AddTypedTextChunk("reinterpret_cast");
1886 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1887 Builder.AddPlaceholderChunk("type");
1888 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1889 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1890 Builder.AddPlaceholderChunk("expression");
1891 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1892 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001893
Douglas Gregorf4c33342010-05-28 00:22:41 +00001894 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001895 Builder.AddTypedTextChunk("const_cast");
1896 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1897 Builder.AddPlaceholderChunk("type");
1898 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1899 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1900 Builder.AddPlaceholderChunk("expression");
1901 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1902 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001903
David Blaikiebbafb8a2012-03-11 07:00:24 +00001904 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001905 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001906 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001907 Builder.AddTypedTextChunk("typeid");
1908 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1909 Builder.AddPlaceholderChunk("expression-or-type");
1910 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1911 Results.AddResult(Result(Builder.TakeString()));
1912 }
1913
Douglas Gregorf4c33342010-05-28 00:22:41 +00001914 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001915 Builder.AddTypedTextChunk("new");
1916 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1917 Builder.AddPlaceholderChunk("type");
1918 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1919 Builder.AddPlaceholderChunk("expressions");
1920 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1921 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001922
Douglas Gregorf4c33342010-05-28 00:22:41 +00001923 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001924 Builder.AddTypedTextChunk("new");
1925 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1926 Builder.AddPlaceholderChunk("type");
1927 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1928 Builder.AddPlaceholderChunk("size");
1929 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1930 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1931 Builder.AddPlaceholderChunk("expressions");
1932 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1933 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001934
Douglas Gregorf4c33342010-05-28 00:22:41 +00001935 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001936 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001937 Builder.AddTypedTextChunk("delete");
1938 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1939 Builder.AddPlaceholderChunk("expression");
1940 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001941
Douglas Gregorf4c33342010-05-28 00:22:41 +00001942 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001943 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001944 Builder.AddTypedTextChunk("delete");
1945 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1946 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1947 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1948 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1949 Builder.AddPlaceholderChunk("expression");
1950 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001951
David Blaikiebbafb8a2012-03-11 07:00:24 +00001952 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001953 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001954 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001955 Builder.AddTypedTextChunk("throw");
1956 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1957 Builder.AddPlaceholderChunk("expression");
1958 Results.AddResult(Result(Builder.TakeString()));
1959 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001960
Douglas Gregora2db7932010-05-26 22:00:08 +00001961 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001962
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001963 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001964 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001965 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001966 Builder.AddTypedTextChunk("nullptr");
1967 Results.AddResult(Result(Builder.TakeString()));
1968
1969 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001970 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001971 Builder.AddTypedTextChunk("alignof");
1972 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1973 Builder.AddPlaceholderChunk("type");
1974 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1975 Results.AddResult(Result(Builder.TakeString()));
1976
1977 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001978 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001979 Builder.AddTypedTextChunk("noexcept");
1980 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1981 Builder.AddPlaceholderChunk("expression");
1982 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1983 Results.AddResult(Result(Builder.TakeString()));
1984
1985 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001986 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001987 Builder.AddTypedTextChunk("sizeof...");
1988 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1989 Builder.AddPlaceholderChunk("parameter-pack");
1990 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1991 Results.AddResult(Result(Builder.TakeString()));
1992 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001993 }
1994
David Blaikiebbafb8a2012-03-11 07:00:24 +00001995 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001996 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001997 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1998 // The interface can be NULL.
1999 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002000 if (ID->getSuperClass()) {
2001 std::string SuperType;
2002 SuperType = ID->getSuperClass()->getNameAsString();
2003 if (Method->isInstanceMethod())
2004 SuperType += " *";
2005
2006 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2007 Builder.AddTypedTextChunk("super");
2008 Results.AddResult(Result(Builder.TakeString()));
2009 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002010 }
2011
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002012 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002013 }
2014
Jordan Rose58d54722012-06-30 21:33:57 +00002015 if (SemaRef.getLangOpts().C11) {
2016 // _Alignof
2017 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002018 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002019 Builder.AddTypedTextChunk("alignof");
2020 else
2021 Builder.AddTypedTextChunk("_Alignof");
2022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2023 Builder.AddPlaceholderChunk("type");
2024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2025 Results.AddResult(Result(Builder.TakeString()));
2026 }
2027
Douglas Gregorf4c33342010-05-28 00:22:41 +00002028 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002029 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002030 Builder.AddTypedTextChunk("sizeof");
2031 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2032 Builder.AddPlaceholderChunk("expression-or-type");
2033 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2034 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002035 break;
2036 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002037
John McCallfaf5fb42010-08-26 23:41:50 +00002038 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002039 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002040 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002041 }
2042
David Blaikiebbafb8a2012-03-11 07:00:24 +00002043 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2044 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002045
David Blaikiebbafb8a2012-03-11 07:00:24 +00002046 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002047 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002048}
2049
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002050/// \brief If the given declaration has an associated type, add it as a result
2051/// type chunk.
2052static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002053 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002054 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002055 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002056 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002057 if (!ND)
2058 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002059
2060 // Skip constructors and conversion functions, which have their return types
2061 // built into their names.
2062 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2063 return;
2064
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002065 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002066 QualType T;
2067 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002068 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002069 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2070 if (!BaseType.isNull())
2071 T = Method->getSendResultType(BaseType);
2072 else
2073 T = Method->getReturnType();
2074 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002075 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2076 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2077 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002078 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2079 if (!BaseType.isNull())
2080 T = Ivar->getUsageType(BaseType);
2081 else
2082 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002083 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002084 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002085 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2086 if (!BaseType.isNull())
2087 T = Property->getUsageType(BaseType);
2088 else
2089 T = Property->getType();
2090 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002091
2092 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2093 return;
2094
Douglas Gregor75acd922011-09-27 23:30:47 +00002095 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002096 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002097}
2098
Richard Smith20e883e2015-04-29 23:20:19 +00002099static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002100 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002101 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002102 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2103 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002104 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002105 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002106 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002107 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002108 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002109 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002110 }
2111}
2112
Douglas Gregor86b42682015-06-19 18:27:52 +00002113static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2114 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002115 std::string Result;
2116 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002117 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002118 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002119 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002120 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002121 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002122 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002123 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002124 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002125 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002126 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002127 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002128 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2129 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2130 switch (*nullability) {
2131 case NullabilityKind::NonNull:
2132 Result += "nonnull ";
2133 break;
2134
2135 case NullabilityKind::Nullable:
2136 Result += "nullable ";
2137 break;
2138
2139 case NullabilityKind::Unspecified:
2140 Result += "null_unspecified ";
2141 break;
2142 }
2143 }
2144 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002145 return Result;
2146}
2147
Richard Smith20e883e2015-04-29 23:20:19 +00002148static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002149 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002150 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002151 bool SuppressBlock = false,
2152 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002153 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2154 if (Param->getType()->isDependentType() ||
2155 !Param->getType()->isBlockPointerType()) {
2156 // The argument for a dependent or non-block parameter is a placeholder
2157 // containing that parameter's type.
2158 std::string Result;
2159
Douglas Gregor981a0c42010-08-29 19:47:46 +00002160 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002161 Result = Param->getIdentifier()->getName();
2162
Douglas Gregor86b42682015-06-19 18:27:52 +00002163 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002164 if (ObjCSubsts)
2165 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2166 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002167 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002168 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2169 Type);
2170 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002171 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002172 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002173 } else {
2174 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002175 }
2176 return Result;
2177 }
2178
2179 // The argument for a block pointer parameter is a block literal with
2180 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002181 FunctionTypeLoc Block;
2182 FunctionProtoTypeLoc BlockProto;
Douglas Gregore90dd002010-08-24 16:15:59 +00002183 TypeLoc TL;
2184 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2185 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2186 while (true) {
2187 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002188 if (!SuppressBlock) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002189 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2190 if (TypeSourceInfo *InnerTSInfo =
2191 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002192 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2193 continue;
2194 }
2195 }
2196
2197 // Look through qualified types
David Blaikie6adc78e2013-02-18 22:06:02 +00002198 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2199 TL = QualifiedTL.getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002200 continue;
2201 }
Douglas Gregor4c850f32015-07-07 06:20:22 +00002202
2203 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2204 TL = AttrTL.getModifiedLoc();
2205 continue;
2206 }
Douglas Gregore90dd002010-08-24 16:15:59 +00002207 }
2208
Douglas Gregore90dd002010-08-24 16:15:59 +00002209 // Try to get the function prototype behind the block pointer type,
2210 // then we're done.
David Blaikie6adc78e2013-02-18 22:06:02 +00002211 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2212 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2213 Block = TL.getAs<FunctionTypeLoc>();
2214 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregore90dd002010-08-24 16:15:59 +00002215 }
2216 break;
2217 }
2218 }
2219
2220 if (!Block) {
2221 // We were unable to find a FunctionProtoTypeLoc with parameter names
2222 // for the block; just use the parameter type as a placeholder.
2223 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002224 if (!ObjCMethodParam && Param->getIdentifier())
2225 Result = Param->getIdentifier()->getName();
2226
Douglas Gregor86b42682015-06-19 18:27:52 +00002227 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002228
2229 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002230 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2231 Type);
2232 Result += Type.getAsString(Policy) + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002233 if (Param->getIdentifier())
2234 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002235 } else {
2236 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002237 }
2238
2239 return Result;
2240 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002241
Douglas Gregore90dd002010-08-24 16:15:59 +00002242 // We have the function prototype behind the block pointer type, as it was
2243 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002244 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002245 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002246 if (ObjCSubsts)
2247 ResultType = ResultType.substObjCTypeArgs(Param->getASTContext(),
2248 *ObjCSubsts,
2249 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002250 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002251 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002252
2253 // Format the parameter list.
2254 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002255 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002256 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002257 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002258 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002259 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002260 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002261 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002262 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002263 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002264 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002265 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002266 /*SuppressName=*/false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002267 /*SuppressBlock=*/true,
2268 ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002269
David Blaikie6adc78e2013-02-18 22:06:02 +00002270 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002271 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002272 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002273 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002274 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002275
Douglas Gregord793e7c2011-10-18 04:23:19 +00002276 if (SuppressBlock) {
2277 // Format as a parameter.
2278 Result = Result + " (^";
2279 if (Param->getIdentifier())
2280 Result += Param->getIdentifier()->getName();
2281 Result += ")";
2282 Result += Params;
2283 } else {
2284 // Format as a block literal argument.
2285 Result = '^' + Result;
2286 Result += Params;
2287
2288 if (Param->getIdentifier())
2289 Result += Param->getIdentifier()->getName();
2290 }
2291
Douglas Gregore90dd002010-08-24 16:15:59 +00002292 return Result;
2293}
2294
Douglas Gregor3545ff42009-09-21 16:56:56 +00002295/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002296static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002297 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002298 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002299 CodeCompletionBuilder &Result,
2300 unsigned Start = 0,
2301 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002302 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002303
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002304 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002305 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002306
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002307 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002308 // When we see an optional default argument, put that argument and
2309 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002310 CodeCompletionBuilder Opt(Result.getAllocator(),
2311 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002312 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002313 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002314 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002315 Result.AddOptionalChunk(Opt.TakeString());
2316 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002317 }
2318
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002319 if (FirstParameter)
2320 FirstParameter = false;
2321 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002322 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002323
2324 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002325
2326 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002327 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2328
Douglas Gregor400f5972010-08-31 05:13:43 +00002329 if (Function->isVariadic() && P == N - 1)
2330 PlaceholderStr += ", ...";
2331
Douglas Gregor3545ff42009-09-21 16:56:56 +00002332 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002333 Result.AddPlaceholderChunk(
2334 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002335 }
Douglas Gregorba449032009-09-22 21:42:17 +00002336
2337 if (const FunctionProtoType *Proto
2338 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002339 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002340 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002341 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002342
Richard Smith20e883e2015-04-29 23:20:19 +00002343 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002344 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002345}
2346
2347/// \brief Add template parameter chunks to the given code completion string.
2348static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002349 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002350 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002351 CodeCompletionBuilder &Result,
2352 unsigned MaxParameters = 0,
2353 unsigned Start = 0,
2354 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002355 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002356
2357 // Prefer to take the template parameter names from the first declaration of
2358 // the template.
2359 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2360
Douglas Gregor3545ff42009-09-21 16:56:56 +00002361 TemplateParameterList *Params = Template->getTemplateParameters();
2362 TemplateParameterList::iterator PEnd = Params->end();
2363 if (MaxParameters)
2364 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002365 for (TemplateParameterList::iterator P = Params->begin() + Start;
2366 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002367 bool HasDefaultArg = false;
2368 std::string PlaceholderStr;
2369 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2370 if (TTP->wasDeclaredWithTypename())
2371 PlaceholderStr = "typename";
2372 else
2373 PlaceholderStr = "class";
2374
2375 if (TTP->getIdentifier()) {
2376 PlaceholderStr += ' ';
2377 PlaceholderStr += TTP->getIdentifier()->getName();
2378 }
2379
2380 HasDefaultArg = TTP->hasDefaultArgument();
2381 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002382 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002383 if (NTTP->getIdentifier())
2384 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002385 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002386 HasDefaultArg = NTTP->hasDefaultArgument();
2387 } else {
2388 assert(isa<TemplateTemplateParmDecl>(*P));
2389 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2390
2391 // Since putting the template argument list into the placeholder would
2392 // be very, very long, we just use an abbreviation.
2393 PlaceholderStr = "template<...> class";
2394 if (TTP->getIdentifier()) {
2395 PlaceholderStr += ' ';
2396 PlaceholderStr += TTP->getIdentifier()->getName();
2397 }
2398
2399 HasDefaultArg = TTP->hasDefaultArgument();
2400 }
2401
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002402 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002403 // When we see an optional default argument, put that argument and
2404 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002405 CodeCompletionBuilder Opt(Result.getAllocator(),
2406 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002407 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002408 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002409 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002410 P - Params->begin(), true);
2411 Result.AddOptionalChunk(Opt.TakeString());
2412 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002413 }
2414
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002415 InDefaultArg = false;
2416
Douglas Gregor3545ff42009-09-21 16:56:56 +00002417 if (FirstParameter)
2418 FirstParameter = false;
2419 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002420 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002421
2422 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002423 Result.AddPlaceholderChunk(
2424 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002425 }
2426}
2427
Douglas Gregorf2510672009-09-21 19:57:38 +00002428/// \brief Add a qualifier to the given code-completion string, if the
2429/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002430static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002431AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002432 NestedNameSpecifier *Qualifier,
2433 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002434 ASTContext &Context,
2435 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002436 if (!Qualifier)
2437 return;
2438
2439 std::string PrintedNNS;
2440 {
2441 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002442 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002443 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002444 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002445 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002446 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002447 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002448}
2449
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002450static void
2451AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002452 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002453 const FunctionProtoType *Proto
2454 = Function->getType()->getAs<FunctionProtoType>();
2455 if (!Proto || !Proto->getTypeQuals())
2456 return;
2457
Douglas Gregor304f9b02011-02-01 21:15:40 +00002458 // FIXME: Add ref-qualifier!
2459
2460 // Handle single qualifiers without copying
2461 if (Proto->getTypeQuals() == Qualifiers::Const) {
2462 Result.AddInformativeChunk(" const");
2463 return;
2464 }
2465
2466 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2467 Result.AddInformativeChunk(" volatile");
2468 return;
2469 }
2470
2471 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2472 Result.AddInformativeChunk(" restrict");
2473 return;
2474 }
2475
2476 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002477 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002478 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002479 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002480 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002481 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002482 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002483 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002484 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002485}
2486
Douglas Gregor0212fd72010-09-21 16:06:22 +00002487/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002488static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002489 const NamedDecl *ND,
2490 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002491 DeclarationName Name = ND->getDeclName();
2492 if (!Name)
2493 return;
2494
2495 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002496 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002497 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002498 switch (Name.getCXXOverloadedOperator()) {
2499 case OO_None:
2500 case OO_Conditional:
2501 case NUM_OVERLOADED_OPERATORS:
2502 OperatorName = "operator";
2503 break;
2504
2505#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2506 case OO_##Name: OperatorName = "operator" Spelling; break;
2507#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2508#include "clang/Basic/OperatorKinds.def"
2509
2510 case OO_New: OperatorName = "operator new"; break;
2511 case OO_Delete: OperatorName = "operator delete"; break;
2512 case OO_Array_New: OperatorName = "operator new[]"; break;
2513 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2514 case OO_Call: OperatorName = "operator()"; break;
2515 case OO_Subscript: OperatorName = "operator[]"; break;
2516 }
2517 Result.AddTypedTextChunk(OperatorName);
2518 break;
2519 }
2520
Douglas Gregor0212fd72010-09-21 16:06:22 +00002521 case DeclarationName::Identifier:
2522 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002523 case DeclarationName::CXXDestructorName:
2524 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002525 Result.AddTypedTextChunk(
2526 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002527 break;
2528
2529 case DeclarationName::CXXUsingDirective:
2530 case DeclarationName::ObjCZeroArgSelector:
2531 case DeclarationName::ObjCOneArgSelector:
2532 case DeclarationName::ObjCMultiArgSelector:
2533 break;
2534
2535 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002536 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002537 QualType Ty = Name.getCXXNameType();
2538 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2539 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2540 else if (const InjectedClassNameType *InjectedTy
2541 = Ty->getAs<InjectedClassNameType>())
2542 Record = InjectedTy->getDecl();
2543 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002544 Result.AddTypedTextChunk(
2545 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002546 break;
2547 }
2548
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002549 Result.AddTypedTextChunk(
2550 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002551 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002552 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002553 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002554 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002555 }
2556 break;
2557 }
2558 }
2559}
2560
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002561CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002562 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002563 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002564 CodeCompletionTUInfo &CCTUInfo,
2565 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002566 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2567 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002568}
2569
Douglas Gregor3545ff42009-09-21 16:56:56 +00002570/// \brief If possible, create a new code completion string for the given
2571/// result.
2572///
2573/// \returns Either a new, heap-allocated code completion string describing
2574/// how to use this result, or NULL to indicate that the string or name of the
2575/// result is all that is needed.
2576CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002577CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2578 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002579 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002580 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002581 CodeCompletionTUInfo &CCTUInfo,
2582 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002583 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002584
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002585 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002586 if (Kind == RK_Pattern) {
2587 Pattern->Priority = Priority;
2588 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002589
2590 if (Declaration) {
2591 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002592 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002593 // Provide code completion comment for self.GetterName where
2594 // GetterName is the getter method for a property with name
2595 // different from the property name (declared via a property
2596 // getter attribute.
2597 const NamedDecl *ND = Declaration;
2598 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2599 if (M->isPropertyAccessor())
2600 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2601 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002602 PDecl->getIdentifier() != M->getIdentifier()) {
2603 if (const RawComment *RC =
2604 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002605 Result.addBriefComment(RC->getBriefText(Ctx));
2606 Pattern->BriefComment = Result.getBriefComment();
2607 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002608 else if (const RawComment *RC =
2609 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2610 Result.addBriefComment(RC->getBriefText(Ctx));
2611 Pattern->BriefComment = Result.getBriefComment();
2612 }
2613 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002614 }
2615
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002616 return Pattern;
2617 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002618
Douglas Gregorf09935f2009-12-01 05:55:20 +00002619 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002620 Result.AddTypedTextChunk(Keyword);
2621 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002622 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002623
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002624 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002625 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002626 Result.AddTypedTextChunk(
2627 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002628
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002629 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002630 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002631
2632 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002633 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002634 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002635
2636 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2637 if (MI->isC99Varargs()) {
2638 --AEnd;
2639
2640 if (A == AEnd) {
2641 Result.AddPlaceholderChunk("...");
2642 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002643 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002644
Douglas Gregor0c505312011-07-30 08:17:44 +00002645 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002646 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002647 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002648
2649 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002650 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002651 if (MI->isC99Varargs())
2652 Arg += ", ...";
2653 else
2654 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002655 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002656 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002657 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002658
2659 // Non-variadic macros are simple.
2660 Result.AddPlaceholderChunk(
2661 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002662 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002663 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002664 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002665 }
2666
Douglas Gregorf64acca2010-05-25 21:41:55 +00002667 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002668 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002669 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002670
2671 if (IncludeBriefComments) {
2672 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002673 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002674 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002675 }
2676 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2677 if (OMD->isPropertyAccessor())
2678 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2679 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2680 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002681 }
2682
Douglas Gregor9eb77012009-11-07 00:00:49 +00002683 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002684 Result.AddTypedTextChunk(
2685 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002686 Result.AddTextChunk("::");
2687 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002688 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002689
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002690 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2691 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002692
Douglas Gregorc3425b12015-07-07 06:20:19 +00002693 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002694
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002695 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002696 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002697 Ctx, Policy);
2698 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002699 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002700 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002701 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002702 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002703 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002704 }
2705
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002706 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002707 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002708 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002709 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002710 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002711
Douglas Gregor3545ff42009-09-21 16:56:56 +00002712 // Figure out which template parameters are deduced (or have default
2713 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002714 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002715 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002716 unsigned LastDeducibleArgument;
2717 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2718 --LastDeducibleArgument) {
2719 if (!Deduced[LastDeducibleArgument - 1]) {
2720 // C++0x: Figure out if the template argument has a default. If so,
2721 // the user doesn't need to type this argument.
2722 // FIXME: We need to abstract template parameters better!
2723 bool HasDefaultArg = false;
2724 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002725 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002726 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2727 HasDefaultArg = TTP->hasDefaultArgument();
2728 else if (NonTypeTemplateParmDecl *NTTP
2729 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2730 HasDefaultArg = NTTP->hasDefaultArgument();
2731 else {
2732 assert(isa<TemplateTemplateParmDecl>(Param));
2733 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002734 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002735 }
2736
2737 if (!HasDefaultArg)
2738 break;
2739 }
2740 }
2741
2742 if (LastDeducibleArgument) {
2743 // Some of the function template arguments cannot be deduced from a
2744 // function call, so we introduce an explicit template argument list
2745 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002746 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002747 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002748 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002749 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002750 }
2751
2752 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002753 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002754 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002755 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002756 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002757 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002758 }
2759
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002760 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002761 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002762 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002763 Result.AddTypedTextChunk(
2764 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002765 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002766 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002767 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002768 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002769 }
2770
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002771 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002772 Selector Sel = Method->getSelector();
2773 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002774 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002775 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002776 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002777 }
2778
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002779 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002780 SelName += ':';
2781 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002782 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002783 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002784 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002785
2786 // If there is only one parameter, and we're past it, add an empty
2787 // typed-text chunk since there is nothing to type.
2788 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002789 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002790 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002791 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002792 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2793 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002794 P != PEnd; (void)++P, ++Idx) {
2795 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002796 std::string Keyword;
2797 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002798 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002799 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002800 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002801 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002802 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002803 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002804 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002805 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002806 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002807
2808 // If we're before the starting parameter, skip the placeholder.
2809 if (Idx < StartParameter)
2810 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002811
2812 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002813 QualType ParamType = (*P)->getType();
2814 Optional<ArrayRef<QualType>> ObjCSubsts;
2815 if (!CCContext.getBaseType().isNull())
2816 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2817
2818 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2819 Arg = FormatFunctionParameter(Policy, *P, true,
2820 /*SuppressBlock=*/false,
2821 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002822 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002823 if (ObjCSubsts)
2824 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2825 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002826 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002827 ParamType);
2828 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002829 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002830 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002831 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002832 }
2833
Douglas Gregor400f5972010-08-31 05:13:43 +00002834 if (Method->isVariadic() && (P + 1) == PEnd)
2835 Arg += ", ...";
2836
Douglas Gregor95887f92010-07-08 23:20:03 +00002837 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002838 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002839 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002840 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002841 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002842 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002843 }
2844
Douglas Gregor04c5f972009-12-23 00:21:46 +00002845 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002846 if (Method->param_size() == 0) {
2847 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002848 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002849 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002850 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002851 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002852 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002853 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002854
Richard Smith20e883e2015-04-29 23:20:19 +00002855 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002856 }
2857
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002858 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002859 }
2860
Douglas Gregorf09935f2009-12-01 05:55:20 +00002861 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002862 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002863 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002864
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002865 Result.AddTypedTextChunk(
2866 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002867 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002868}
2869
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002870/// \brief Add function overload parameter chunks to the given code completion
2871/// string.
2872static void AddOverloadParameterChunks(ASTContext &Context,
2873 const PrintingPolicy &Policy,
2874 const FunctionDecl *Function,
2875 const FunctionProtoType *Prototype,
2876 CodeCompletionBuilder &Result,
2877 unsigned CurrentArg,
2878 unsigned Start = 0,
2879 bool InOptional = false) {
2880 bool FirstParameter = true;
2881 unsigned NumParams = Function ? Function->getNumParams()
2882 : Prototype->getNumParams();
2883
2884 for (unsigned P = Start; P != NumParams; ++P) {
2885 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2886 // When we see an optional default argument, put that argument and
2887 // the remaining default arguments into a new, optional string.
2888 CodeCompletionBuilder Opt(Result.getAllocator(),
2889 Result.getCodeCompletionTUInfo());
2890 if (!FirstParameter)
2891 Opt.AddChunk(CodeCompletionString::CK_Comma);
2892 // Optional sections are nested.
2893 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2894 CurrentArg, P, /*InOptional=*/true);
2895 Result.AddOptionalChunk(Opt.TakeString());
2896 return;
2897 }
2898
2899 if (FirstParameter)
2900 FirstParameter = false;
2901 else
2902 Result.AddChunk(CodeCompletionString::CK_Comma);
2903
2904 InOptional = false;
2905
2906 // Format the placeholder string.
2907 std::string Placeholder;
2908 if (Function)
Richard Smith20e883e2015-04-29 23:20:19 +00002909 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002910 else
2911 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2912
2913 if (P == CurrentArg)
2914 Result.AddCurrentParameterChunk(
2915 Result.getAllocator().CopyString(Placeholder));
2916 else
2917 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2918 }
2919
2920 if (Prototype && Prototype->isVariadic()) {
2921 CodeCompletionBuilder Opt(Result.getAllocator(),
2922 Result.getCodeCompletionTUInfo());
2923 if (!FirstParameter)
2924 Opt.AddChunk(CodeCompletionString::CK_Comma);
2925
2926 if (CurrentArg < NumParams)
2927 Opt.AddPlaceholderChunk("...");
2928 else
2929 Opt.AddCurrentParameterChunk("...");
2930
2931 Result.AddOptionalChunk(Opt.TakeString());
2932 }
2933}
2934
Douglas Gregorf0f51982009-09-23 00:34:09 +00002935CodeCompletionString *
2936CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002937 unsigned CurrentArg, Sema &S,
2938 CodeCompletionAllocator &Allocator,
2939 CodeCompletionTUInfo &CCTUInfo,
2940 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002941 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002942
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002943 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002944 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002945 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002946 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00002947 = dyn_cast<FunctionProtoType>(getFunctionType());
2948 if (!FDecl && !Proto) {
2949 // Function without a prototype. Just give the return type and a
2950 // highlighted ellipsis.
2951 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002952 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
2953 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002954 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2955 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2956 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002957 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002958 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002959
2960 if (FDecl) {
2961 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
2962 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
2963 FDecl->getParamDecl(CurrentArg)))
2964 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00002965 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002966 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002967 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2968 } else {
2969 Result.AddResultTypeChunk(
2970 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00002971 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002972 }
Alp Toker314cc812014-01-25 16:55:45 +00002973
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002974 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002975 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
2976 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002977 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002978
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002979 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002980}
2981
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002982unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002983 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002984 bool PreferredTypeIsPointer) {
2985 unsigned Priority = CCP_Macro;
2986
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002987 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2988 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2989 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002990 Priority = CCP_Constant;
2991 if (PreferredTypeIsPointer)
2992 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002993 }
2994 // Treat "YES", "NO", "true", and "false" as constants.
2995 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2996 MacroName.equals("true") || MacroName.equals("false"))
2997 Priority = CCP_Constant;
2998 // Treat "bool" as a type.
2999 else if (MacroName.equals("bool"))
3000 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3001
Douglas Gregor6e240332010-08-16 16:18:59 +00003002
3003 return Priority;
3004}
3005
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003006CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003007 if (!D)
3008 return CXCursor_UnexposedDecl;
3009
3010 switch (D->getKind()) {
3011 case Decl::Enum: return CXCursor_EnumDecl;
3012 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3013 case Decl::Field: return CXCursor_FieldDecl;
3014 case Decl::Function:
3015 return CXCursor_FunctionDecl;
3016 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3017 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003018 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003019
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003020 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003021 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3022 case Decl::ObjCMethod:
3023 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3024 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3025 case Decl::CXXMethod: return CXCursor_CXXMethod;
3026 case Decl::CXXConstructor: return CXCursor_Constructor;
3027 case Decl::CXXDestructor: return CXCursor_Destructor;
3028 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3029 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003030 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003031 case Decl::ParmVar: return CXCursor_ParmDecl;
3032 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003033 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003034 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003035 case Decl::Var: return CXCursor_VarDecl;
3036 case Decl::Namespace: return CXCursor_Namespace;
3037 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3038 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3039 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3040 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3041 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3042 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003043 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003044 case Decl::ClassTemplatePartialSpecialization:
3045 return CXCursor_ClassTemplatePartialSpecialization;
3046 case Decl::UsingDirective: return CXCursor_UsingDirective;
Olivier Goffart81978012016-06-09 16:15:55 +00003047 case Decl::StaticAssert: return CXCursor_StaticAssert;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003048 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003049
3050 case Decl::Using:
3051 case Decl::UnresolvedUsingValue:
3052 case Decl::UnresolvedUsingTypename:
3053 return CXCursor_UsingDeclaration;
3054
Douglas Gregor4cd65962011-06-03 23:08:58 +00003055 case Decl::ObjCPropertyImpl:
3056 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3057 case ObjCPropertyImplDecl::Dynamic:
3058 return CXCursor_ObjCDynamicDecl;
3059
3060 case ObjCPropertyImplDecl::Synthesize:
3061 return CXCursor_ObjCSynthesizeDecl;
3062 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003063
3064 case Decl::Import:
3065 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003066
3067 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3068
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003069 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003070 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003071 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003072 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003073 case TTK_Struct: return CXCursor_StructDecl;
3074 case TTK_Class: return CXCursor_ClassDecl;
3075 case TTK_Union: return CXCursor_UnionDecl;
3076 case TTK_Enum: return CXCursor_EnumDecl;
3077 }
3078 }
3079 }
3080
3081 return CXCursor_UnexposedDecl;
3082}
3083
Douglas Gregor55b037b2010-07-08 20:55:51 +00003084static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003085 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003086 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003087 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003088
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003089 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003090
Douglas Gregor9eb77012009-11-07 00:00:49 +00003091 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3092 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003093 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003094 auto MD = PP.getMacroDefinition(M->first);
3095 if (IncludeUndefined || MD) {
3096 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003097 if (MI->isUsedForHeaderGuard())
3098 continue;
3099
Douglas Gregor8cb17462012-10-09 16:01:50 +00003100 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003101 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003102 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003103 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003104 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003105 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003106
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003107 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003108
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003109}
3110
Douglas Gregorce0e8562010-08-23 21:54:33 +00003111static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3112 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003113 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003114
3115 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003116
Douglas Gregorce0e8562010-08-23 21:54:33 +00003117 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3118 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003119 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003120 Results.AddResult(Result("__func__", CCP_Constant));
3121 Results.ExitScope();
3122}
3123
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003124static void HandleCodeCompleteResults(Sema *S,
3125 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003126 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003127 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003128 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003129 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003130 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003131}
3132
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003133static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3134 Sema::ParserCompletionContext PCC) {
3135 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003136 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003137 return CodeCompletionContext::CCC_TopLevel;
3138
John McCallfaf5fb42010-08-26 23:41:50 +00003139 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003140 return CodeCompletionContext::CCC_ClassStructUnion;
3141
John McCallfaf5fb42010-08-26 23:41:50 +00003142 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003143 return CodeCompletionContext::CCC_ObjCInterface;
3144
John McCallfaf5fb42010-08-26 23:41:50 +00003145 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003146 return CodeCompletionContext::CCC_ObjCImplementation;
3147
John McCallfaf5fb42010-08-26 23:41:50 +00003148 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003149 return CodeCompletionContext::CCC_ObjCIvarList;
3150
John McCallfaf5fb42010-08-26 23:41:50 +00003151 case Sema::PCC_Template:
3152 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003153 if (S.CurContext->isFileContext())
3154 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003155 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003156 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003157 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003158
John McCallfaf5fb42010-08-26 23:41:50 +00003159 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003160 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003161
John McCallfaf5fb42010-08-26 23:41:50 +00003162 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003163 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3164 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003165 return CodeCompletionContext::CCC_ParenthesizedExpression;
3166 else
3167 return CodeCompletionContext::CCC_Expression;
3168
3169 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003170 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003171 return CodeCompletionContext::CCC_Expression;
3172
John McCallfaf5fb42010-08-26 23:41:50 +00003173 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003174 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003175
John McCallfaf5fb42010-08-26 23:41:50 +00003176 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003177 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003178
3179 case Sema::PCC_ParenthesizedExpression:
3180 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003181
3182 case Sema::PCC_LocalDeclarationSpecifiers:
3183 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003184 }
David Blaikie8a40f702012-01-17 06:56:22 +00003185
3186 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003187}
3188
Douglas Gregorac322ec2010-08-27 21:18:54 +00003189/// \brief If we're in a C++ virtual member function, add completion results
3190/// that invoke the functions we override, since it's common to invoke the
3191/// overridden function as well as adding new functionality.
3192///
3193/// \param S The semantic analysis object for which we are generating results.
3194///
3195/// \param InContext This context in which the nested-name-specifier preceding
3196/// the code-completion point
3197static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3198 ResultBuilder &Results) {
3199 // Look through blocks.
3200 DeclContext *CurContext = S.CurContext;
3201 while (isa<BlockDecl>(CurContext))
3202 CurContext = CurContext->getParent();
3203
3204
3205 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3206 if (!Method || !Method->isVirtual())
3207 return;
3208
3209 // We need to have names for all of the parameters, if we're going to
3210 // generate a forwarding call.
David Majnemer59f77922016-06-24 04:05:48 +00003211 for (auto P : Method->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003212 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003213 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003214
Douglas Gregor75acd922011-09-27 23:30:47 +00003215 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003216 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3217 MEnd = Method->end_overridden_methods();
3218 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003219 CodeCompletionBuilder Builder(Results.getAllocator(),
3220 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003221 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003222 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3223 continue;
3224
3225 // If we need a nested-name-specifier, add one now.
3226 if (!InContext) {
3227 NestedNameSpecifier *NNS
3228 = getRequiredQualification(S.Context, CurContext,
3229 Overridden->getDeclContext());
3230 if (NNS) {
3231 std::string Str;
3232 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003233 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003234 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003235 }
3236 } else if (!InContext->Equals(Overridden->getDeclContext()))
3237 continue;
3238
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003239 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003240 Overridden->getNameAsString()));
3241 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003242 bool FirstParam = true;
David Majnemer59f77922016-06-24 04:05:48 +00003243 for (auto P : Method->parameters()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003244 if (FirstParam)
3245 FirstParam = false;
3246 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003247 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003248
Aaron Ballman43b68be2014-03-07 17:50:17 +00003249 Builder.AddPlaceholderChunk(
3250 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003251 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3253 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003254 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003255 CXCursor_CXXMethod,
3256 CXAvailability_Available,
3257 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003258 Results.Ignore(Overridden);
3259 }
3260}
3261
Douglas Gregor07f43572012-01-29 18:15:03 +00003262void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3263 ModuleIdPath Path) {
3264 typedef CodeCompletionResult Result;
3265 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003266 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003267 CodeCompletionContext::CCC_Other);
3268 Results.EnterNewScope();
3269
3270 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003271 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003272 typedef CodeCompletionResult Result;
3273 if (Path.empty()) {
3274 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003275 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003276 PP.getHeaderSearchInfo().collectAllModules(Modules);
3277 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3278 Builder.AddTypedTextChunk(
3279 Builder.getAllocator().CopyString(Modules[I]->Name));
3280 Results.AddResult(Result(Builder.TakeString(),
3281 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003282 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003283 Modules[I]->isAvailable()
3284 ? CXAvailability_Available
3285 : CXAvailability_NotAvailable));
3286 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003287 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003288 // Load the named module.
3289 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3290 Module::AllVisible,
3291 /*IsInclusionDirective=*/false);
3292 // Enumerate submodules.
3293 if (Mod) {
3294 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3295 SubEnd = Mod->submodule_end();
3296 Sub != SubEnd; ++Sub) {
3297
3298 Builder.AddTypedTextChunk(
3299 Builder.getAllocator().CopyString((*Sub)->Name));
3300 Results.AddResult(Result(Builder.TakeString(),
3301 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003302 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003303 (*Sub)->isAvailable()
3304 ? CXAvailability_Available
3305 : CXAvailability_NotAvailable));
3306 }
3307 }
3308 }
3309 Results.ExitScope();
3310 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3311 Results.data(),Results.size());
3312}
3313
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003314void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003315 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003316 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003317 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003318 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003319 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003320
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003321 // Determine how to filter results, e.g., so that the names of
3322 // values (functions, enumerators, function templates, etc.) are
3323 // only allowed where we can have an expression.
3324 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003325 case PCC_Namespace:
3326 case PCC_Class:
3327 case PCC_ObjCInterface:
3328 case PCC_ObjCImplementation:
3329 case PCC_ObjCInstanceVariableList:
3330 case PCC_Template:
3331 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003332 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003333 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003334 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3335 break;
3336
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003337 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003338 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003339 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003340 case PCC_ForInit:
3341 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003342 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003343 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3344 else
3345 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003346
David Blaikiebbafb8a2012-03-11 07:00:24 +00003347 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003349 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003350
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003351 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003352 // Unfiltered
3353 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003354 }
3355
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003356 // If we are in a C++ non-static member function, check the qualifiers on
3357 // the member function to filter/prioritize the results list.
3358 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3359 if (CurMethod->isInstance())
3360 Results.setObjectTypeQualifiers(
3361 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3362
Douglas Gregorc580c522010-01-14 01:09:38 +00003363 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003364 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3365 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003366
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003367 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003368 Results.ExitScope();
3369
Douglas Gregorce0e8562010-08-23 21:54:33 +00003370 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003371 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003372 case PCC_Expression:
3373 case PCC_Statement:
3374 case PCC_RecoveryInFunction:
3375 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003376 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003377 break;
3378
3379 case PCC_Namespace:
3380 case PCC_Class:
3381 case PCC_ObjCInterface:
3382 case PCC_ObjCImplementation:
3383 case PCC_ObjCInstanceVariableList:
3384 case PCC_Template:
3385 case PCC_MemberTemplate:
3386 case PCC_ForInit:
3387 case PCC_Condition:
3388 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003389 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003390 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003391 }
3392
Douglas Gregor9eb77012009-11-07 00:00:49 +00003393 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003394 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003395
Douglas Gregor50832e02010-09-20 22:39:41 +00003396 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003397 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003398}
3399
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003400static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3401 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003402 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003403 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003404 bool IsSuper,
3405 ResultBuilder &Results);
3406
3407void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3408 bool AllowNonIdentifiers,
3409 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003410 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003411 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003412 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003413 AllowNestedNameSpecifiers
3414 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3415 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003416 Results.EnterNewScope();
3417
3418 // Type qualifiers can come after names.
3419 Results.AddResult(Result("const"));
3420 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003421 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003422 Results.AddResult(Result("restrict"));
3423
David Blaikiebbafb8a2012-03-11 07:00:24 +00003424 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003425 if (AllowNonIdentifiers) {
3426 Results.AddResult(Result("operator"));
3427 }
3428
3429 // Add nested-name-specifiers.
3430 if (AllowNestedNameSpecifiers) {
3431 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003432 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003433 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3434 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3435 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003436 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003437 }
3438 }
3439 Results.ExitScope();
3440
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003441 // If we're in a context where we might have an expression (rather than a
3442 // declaration), and what we've seen so far is an Objective-C type that could
3443 // be a receiver of a class message, this may be a class message send with
3444 // the initial opening bracket '[' missing. Add appropriate completions.
3445 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003446 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003447 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003448 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3449 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003450 !DS.isTypeAltiVecVector() &&
3451 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003452 (S->getFlags() & Scope::DeclScope) != 0 &&
3453 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3454 Scope::FunctionPrototypeScope |
3455 Scope::AtCatchScope)) == 0) {
3456 ParsedType T = DS.getRepAsType();
3457 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003458 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003459 }
3460
Douglas Gregor56ccce02010-08-24 04:59:56 +00003461 // Note that we intentionally suppress macro results here, since we do not
3462 // encourage using macros to produce the names of entities.
3463
Douglas Gregor0ac41382010-09-23 23:01:17 +00003464 HandleCodeCompleteResults(this, CodeCompleter,
3465 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003466 Results.data(), Results.size());
3467}
3468
Douglas Gregor68762e72010-08-23 21:17:50 +00003469struct Sema::CodeCompleteExpressionData {
3470 CodeCompleteExpressionData(QualType PreferredType = QualType())
3471 : PreferredType(PreferredType), IntegralConstantExpression(false),
3472 ObjCCollection(false) { }
3473
3474 QualType PreferredType;
3475 bool IntegralConstantExpression;
3476 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003477 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003478};
3479
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003480/// \brief Perform code-completion in an expression context when we know what
3481/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003482void Sema::CodeCompleteExpression(Scope *S,
3483 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003484 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003485 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003486 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003487 if (Data.ObjCCollection)
3488 Results.setFilter(&ResultBuilder::IsObjCCollection);
3489 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003490 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003491 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003492 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3493 else
3494 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003495
3496 if (!Data.PreferredType.isNull())
3497 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3498
3499 // Ignore any declarations that we were told that we don't care about.
3500 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3501 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003502
3503 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003504 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3505 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003506
3507 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003508 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003509 Results.ExitScope();
3510
Douglas Gregor55b037b2010-07-08 20:55:51 +00003511 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003512 if (!Data.PreferredType.isNull())
3513 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3514 || Data.PreferredType->isMemberPointerType()
3515 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003516
Douglas Gregorce0e8562010-08-23 21:54:33 +00003517 if (S->getFnParent() &&
3518 !Data.ObjCCollection &&
3519 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003520 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003521
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003522 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003523 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003524 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003525 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3526 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003527 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003528}
3529
Douglas Gregoreda7e542010-09-18 01:28:11 +00003530void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3531 if (E.isInvalid())
3532 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003533 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003534 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003535}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003536
Douglas Gregorb888acf2010-12-09 23:01:55 +00003537/// \brief The set of properties that have already been added, referenced by
3538/// property name.
3539typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3540
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003541/// \brief Retrieve the container definition, if any?
3542static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3543 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3544 if (Interface->hasDefinition())
3545 return Interface->getDefinition();
3546
3547 return Interface;
3548 }
3549
3550 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3551 if (Protocol->hasDefinition())
3552 return Protocol->getDefinition();
3553
3554 return Protocol;
3555 }
3556 return Container;
3557}
3558
Douglas Gregorc3425b12015-07-07 06:20:19 +00003559static void AddObjCProperties(const CodeCompletionContext &CCContext,
3560 ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003561 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003562 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003563 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003564 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003565 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003566 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003567
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003568 // Retrieve the definition.
3569 Container = getContainerDef(Container);
3570
Douglas Gregor9291bad2009-11-18 01:29:26 +00003571 // Add properties in this container.
Manman Rena7a8b1f2016-01-26 18:05:23 +00003572 for (const auto *P : Container->instance_properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003573 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003574 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003575 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003576
Douglas Gregor95147142011-05-05 15:50:42 +00003577 // Add nullary methods
3578 if (AllowNullaryMethods) {
3579 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003580 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003581 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003582 if (M->getSelector().isUnarySelector())
3583 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003584 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003585 CodeCompletionBuilder Builder(Results.getAllocator(),
3586 Results.getCodeCompletionTUInfo());
Douglas Gregorc3425b12015-07-07 06:20:19 +00003587 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3588 Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003589 Builder.AddTypedTextChunk(
3590 Results.getAllocator().CopyString(Name->getName()));
3591
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003592 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003593 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003594 CurContext);
3595 }
3596 }
3597 }
3598
3599
Douglas Gregor9291bad2009-11-18 01:29:26 +00003600 // Add properties in referenced protocols.
3601 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003602 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003603 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3604 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003605 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003606 if (AllowCategories) {
3607 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003608 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003609 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3610 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003611 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003612
Douglas Gregor9291bad2009-11-18 01:29:26 +00003613 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003614 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003615 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3616 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003617
3618 // Look in the superclass.
3619 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003620 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003621 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003622 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003623 } else if (const ObjCCategoryDecl *Category
3624 = dyn_cast<ObjCCategoryDecl>(Container)) {
3625 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003626 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003627 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3628 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003629 }
3630}
3631
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003632void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003633 SourceLocation OpLoc,
3634 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003635 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003636 return;
3637
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003638 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3639 if (ConvertedBase.isInvalid())
3640 return;
3641 Base = ConvertedBase.get();
3642
John McCall276321a2010-08-25 06:19:51 +00003643 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003644
Douglas Gregor2436e712009-09-17 21:32:03 +00003645 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003646
3647 if (IsArrow) {
3648 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3649 BaseType = Ptr->getPointeeType();
3650 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003651 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003652 else
3653 return;
3654 }
3655
Douglas Gregor21325842011-07-07 16:03:39 +00003656 enum CodeCompletionContext::Kind contextKind;
3657
3658 if (IsArrow) {
3659 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3660 }
3661 else {
3662 if (BaseType->isObjCObjectPointerType() ||
3663 BaseType->isObjCObjectOrInterfaceType()) {
3664 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3665 }
3666 else {
3667 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3668 }
3669 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003670
3671 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003672 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003673 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003674 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003675 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003676 Results.EnterNewScope();
3677 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003678 // Indicate that we are performing a member access, and the cv-qualifiers
3679 // for the base object type.
3680 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3681
Douglas Gregor9291bad2009-11-18 01:29:26 +00003682 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003683 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003684 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003685 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3686 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003687
David Blaikiebbafb8a2012-03-11 07:00:24 +00003688 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003689 if (!Results.empty()) {
3690 // The "template" keyword can follow "->" or "." in the grammar.
3691 // However, we only want to suggest the template keyword if something
3692 // is dependent.
3693 bool IsDependent = BaseType->isDependentType();
3694 if (!IsDependent) {
3695 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003696 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003697 IsDependent = Ctx->isDependentContext();
3698 break;
3699 }
3700 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003701
Douglas Gregor9291bad2009-11-18 01:29:26 +00003702 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003703 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003704 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003705 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003706 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3707 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003708 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003709
3710 // Add property results based on our interface.
3711 const ObjCObjectPointerType *ObjCPtr
3712 = BaseType->getAsObjCInterfacePointerType();
3713 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregorc3425b12015-07-07 06:20:19 +00003714 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
Douglas Gregor95147142011-05-05 15:50:42 +00003715 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003716 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003717
3718 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003719 for (auto *I : ObjCPtr->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003720 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3721 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003722 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003723 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003724 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003725 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003726 if (const ObjCObjectPointerType *ObjCPtr
3727 = BaseType->getAs<ObjCObjectPointerType>())
3728 Class = ObjCPtr->getInterfaceDecl();
3729 else
John McCall8b07ec22010-05-15 11:32:37 +00003730 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003731
3732 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003733 if (Class) {
3734 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3735 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003736 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3737 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003738 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003739 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003740
3741 // FIXME: How do we cope with isa?
3742
3743 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003744
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003745 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003746 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003747 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003748 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003749}
3750
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003751void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3752 if (!CodeCompleter)
3753 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003754
3755 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003756 enum CodeCompletionContext::Kind ContextKind
3757 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003758 switch ((DeclSpec::TST)TagSpec) {
3759 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003760 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003761 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003762 break;
3763
3764 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003765 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003766 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003767 break;
3768
3769 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003770 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003771 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003772 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003773 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003774 break;
3775
3776 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003777 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003778 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003779
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003780 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3781 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003782 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003783
3784 // First pass: look for tags.
3785 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003786 LookupVisibleDecls(S, LookupTagName, Consumer,
3787 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003788
Douglas Gregor39982192010-08-15 06:18:01 +00003789 if (CodeCompleter->includeGlobals()) {
3790 // Second pass: look for nested name specifiers.
3791 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3792 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3793 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003794
Douglas Gregor0ac41382010-09-23 23:01:17 +00003795 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003796 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003797}
3798
Douglas Gregor28c78432010-08-27 17:35:51 +00003799void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003800 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003801 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003802 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003803 Results.EnterNewScope();
3804 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3805 Results.AddResult("const");
3806 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3807 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003808 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003809 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3810 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003811 if (getLangOpts().C11 &&
3812 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3813 Results.AddResult("_Atomic");
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003814 if (getLangOpts().MSVCCompat &&
3815 !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
3816 Results.AddResult("__unaligned");
Douglas Gregor28c78432010-08-27 17:35:51 +00003817 Results.ExitScope();
3818 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003819 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003820 Results.data(), Results.size());
3821}
3822
Benjamin Kramer72dae622016-02-18 15:30:24 +00003823void Sema::CodeCompleteBracketDeclarator(Scope *S) {
3824 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
3825}
3826
Douglas Gregord328d572009-09-21 18:10:23 +00003827void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003828 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003829 return;
John McCall5939b162011-08-06 07:30:58 +00003830
John McCallaab3e412010-08-25 08:40:02 +00003831 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003832 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3833 if (!type->isEnumeralType()) {
3834 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003835 Data.IntegralConstantExpression = true;
3836 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003837 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003838 }
Douglas Gregord328d572009-09-21 18:10:23 +00003839
3840 // Code-complete the cases of a switch statement over an enumeration type
3841 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003842 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003843 if (EnumDecl *Def = Enum->getDefinition())
3844 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003845
3846 // Determine which enumerators we have already seen in the switch statement.
3847 // FIXME: Ideally, we would also be able to look *past* the code-completion
3848 // token, in case we are code-completing in the middle of the switch and not
3849 // at the end. However, we aren't able to do so at the moment.
3850 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003851 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003852 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3853 SC = SC->getNextSwitchCase()) {
3854 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3855 if (!Case)
3856 continue;
3857
3858 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3859 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3860 if (EnumConstantDecl *Enumerator
3861 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3862 // We look into the AST of the case statement to determine which
3863 // enumerator was named. Alternatively, we could compute the value of
3864 // the integral constant expression, then compare it against the
3865 // values of each enumerator. However, value-based approach would not
3866 // work as well with C++ templates where enumerators declared within a
3867 // template are type- and value-dependent.
3868 EnumeratorsSeen.insert(Enumerator);
3869
Douglas Gregorf2510672009-09-21 19:57:38 +00003870 // If this is a qualified-id, keep track of the nested-name-specifier
3871 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003872 //
3873 // switch (TagD.getKind()) {
3874 // case TagDecl::TK_enum:
3875 // break;
3876 // case XXX
3877 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003878 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003879 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3880 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003881 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003882 }
3883 }
3884
David Blaikiebbafb8a2012-03-11 07:00:24 +00003885 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003886 // If there are no prior enumerators in C++, check whether we have to
3887 // qualify the names of the enumerators that we suggest, because they
3888 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003889 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003890 }
3891
Douglas Gregord328d572009-09-21 18:10:23 +00003892 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003893 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003894 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003895 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003896 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003897 for (auto *E : Enum->enumerators()) {
3898 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003899 continue;
3900
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003901 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003902 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003903 }
3904 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003905
Douglas Gregor21325842011-07-07 16:03:39 +00003906 //We need to make sure we're setting the right context,
3907 //so only say we include macros if the code completer says we do
3908 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3909 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003910 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003911 kind = CodeCompletionContext::CCC_OtherWithMacros;
3912 }
3913
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003914 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003915 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003916 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003917}
3918
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003919static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003920 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003921 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003922
3923 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003924 if (!Args[I])
3925 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003926
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003927 return false;
3928}
3929
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003930typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3931
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003932static void mergeCandidatesWithResults(Sema &SemaRef,
3933 SmallVectorImpl<ResultCandidate> &Results,
3934 OverloadCandidateSet &CandidateSet,
3935 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003936 if (!CandidateSet.empty()) {
3937 // Sort the overload candidate set by placing the best overloads first.
3938 std::stable_sort(
3939 CandidateSet.begin(), CandidateSet.end(),
3940 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3941 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3942 });
3943
3944 // Add the remaining viable overload candidates as code-completion results.
3945 for (auto &Candidate : CandidateSet)
3946 if (Candidate.Viable)
3947 Results.push_back(ResultCandidate(Candidate.Function));
3948 }
3949}
3950
3951/// \brief Get the type of the Nth parameter from a given set of overload
3952/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003953static QualType getParamType(Sema &SemaRef,
3954 ArrayRef<ResultCandidate> Candidates,
3955 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003956
3957 // Given the overloads 'Candidates' for a function call matching all arguments
3958 // up to N, return the type of the Nth parameter if it is the same for all
3959 // overload candidates.
3960 QualType ParamType;
3961 for (auto &Candidate : Candidates) {
3962 if (auto FType = Candidate.getFunctionType())
3963 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3964 if (N < Proto->getNumParams()) {
3965 if (ParamType.isNull())
3966 ParamType = Proto->getParamType(N);
3967 else if (!SemaRef.Context.hasSameUnqualifiedType(
3968 ParamType.getNonReferenceType(),
3969 Proto->getParamType(N).getNonReferenceType()))
3970 // Otherwise return a default-constructed QualType.
3971 return QualType();
3972 }
3973 }
3974
3975 return ParamType;
3976}
3977
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003978static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3979 MutableArrayRef<ResultCandidate> Candidates,
3980 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003981 bool CompleteExpressionWithCurrentArg = true) {
3982 QualType ParamType;
3983 if (CompleteExpressionWithCurrentArg)
3984 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3985
3986 if (ParamType.isNull())
3987 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3988 else
3989 SemaRef.CodeCompleteExpression(S, ParamType);
3990
3991 if (!Candidates.empty())
3992 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3993 Candidates.data(),
3994 Candidates.size());
3995}
3996
3997void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003998 if (!CodeCompleter)
3999 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004000
4001 // When we're code-completing for a call, we fall back to ordinary
4002 // name code-completion whenever we can't produce specific
4003 // results. We may want to revisit this strategy in the future,
4004 // e.g., by merging the two kinds of results.
4005
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004006 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004007
Douglas Gregorcabea402009-09-22 15:41:20 +00004008 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004009 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4010 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004011 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004012 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004013 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004014
John McCall57500772009-12-16 12:17:52 +00004015 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004016 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004017 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004018
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004019 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004020
John McCall57500772009-12-16 12:17:52 +00004021 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004022 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004023 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004024 /*PartialOverloading=*/true);
4025 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4026 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4027 if (UME->hasExplicitTemplateArgs()) {
4028 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4029 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004030 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004031 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4032 ArgExprs.append(Args.begin(), Args.end());
4033 UnresolvedSet<8> Decls;
4034 Decls.append(UME->decls_begin(), UME->decls_end());
4035 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4036 /*SuppressUsedConversions=*/false,
4037 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004038 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004039 FunctionDecl *FD = nullptr;
4040 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4041 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4042 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4043 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004044 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004045 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004046 !FD->getType()->getAs<FunctionProtoType>())
4047 Results.push_back(ResultCandidate(FD));
4048 else
4049 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4050 Args, CandidateSet,
4051 /*SuppressUsedConversions=*/false,
4052 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004053
4054 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4055 // If expression's type is CXXRecordDecl, it may overload the function
4056 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004057 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004058 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004059 DeclarationName OpName = Context.DeclarationNames
4060 .getCXXOperatorName(OO_Call);
4061 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4062 LookupQualifiedName(R, DC);
4063 R.suppressDiagnostics();
4064 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4065 ArgExprs.append(Args.begin(), Args.end());
4066 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4067 /*ExplicitArgs=*/nullptr,
4068 /*SuppressUsedConversions=*/false,
4069 /*PartialOverloading=*/true);
4070 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004071 } else {
4072 // Lastly we check whether expression's type is function pointer or
4073 // function.
4074 QualType T = NakedFn->getType();
4075 if (!T->getPointeeType().isNull())
4076 T = T->getPointeeType();
4077
4078 if (auto FP = T->getAs<FunctionProtoType>()) {
4079 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004080 /*PartialOverloading=*/true) ||
4081 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004082 Results.push_back(ResultCandidate(FP));
4083 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004084 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004085 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004086 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004087 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004088
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004089 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4090 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4091 !CandidateSet.empty());
4092}
4093
4094void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4095 ArrayRef<Expr *> Args) {
4096 if (!CodeCompleter)
4097 return;
4098
4099 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004100 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004101 return;
4102
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004103 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4104 if (!RD) {
4105 CodeCompleteExpression(S, Type);
4106 return;
4107 }
4108
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004109 // FIXME: Provide support for member initializers.
4110 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004111
4112 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4113
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004114 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004115 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4116 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4117 Args, CandidateSet,
4118 /*SuppressUsedConversions=*/false,
4119 /*PartialOverloading=*/true);
4120 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4121 AddTemplateOverloadCandidate(FTD,
4122 DeclAccessPair::make(FTD, C->getAccess()),
4123 /*ExplicitTemplateArgs=*/nullptr,
4124 Args, CandidateSet,
4125 /*SuppressUsedConversions=*/false,
4126 /*PartialOverloading=*/true);
4127 }
4128 }
4129
4130 SmallVector<ResultCandidate, 8> Results;
4131 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4132 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004133}
4134
John McCall48871652010-08-21 09:40:31 +00004135void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4136 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004137 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004138 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004139 return;
4140 }
4141
4142 CodeCompleteExpression(S, VD->getType());
4143}
4144
4145void Sema::CodeCompleteReturn(Scope *S) {
4146 QualType ResultType;
4147 if (isa<BlockDecl>(CurContext)) {
4148 if (BlockScopeInfo *BSI = getCurBlock())
4149 ResultType = BSI->ReturnType;
4150 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004151 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004152 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004153 ResultType = Method->getReturnType();
4154
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004155 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004156 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004157 else
4158 CodeCompleteExpression(S, ResultType);
4159}
4160
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004161void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004162 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004163 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004164 mapCodeCompletionContext(*this, PCC_Statement));
4165 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4166 Results.EnterNewScope();
4167
4168 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4169 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4170 CodeCompleter->includeGlobals());
4171
4172 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4173
4174 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004175 CodeCompletionBuilder Builder(Results.getAllocator(),
4176 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004177 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004178 if (Results.includeCodePatterns()) {
4179 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4180 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4181 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4182 Builder.AddPlaceholderChunk("statements");
4183 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4184 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4185 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004186 Results.AddResult(Builder.TakeString());
4187
4188 // "else if" block
4189 Builder.AddTypedTextChunk("else");
4190 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4191 Builder.AddTextChunk("if");
4192 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4193 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004194 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004195 Builder.AddPlaceholderChunk("condition");
4196 else
4197 Builder.AddPlaceholderChunk("expression");
4198 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004199 if (Results.includeCodePatterns()) {
4200 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4201 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4202 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4203 Builder.AddPlaceholderChunk("statements");
4204 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4205 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4206 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004207 Results.AddResult(Builder.TakeString());
4208
4209 Results.ExitScope();
4210
4211 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004212 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004213
4214 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004215 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004216
4217 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4218 Results.data(),Results.size());
4219}
4220
Richard Trieu2bd04012011-09-09 02:00:50 +00004221void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004222 if (LHS)
4223 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4224 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004225 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004226}
4227
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004228void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004229 bool EnteringContext) {
4230 if (!SS.getScopeRep() || !CodeCompleter)
4231 return;
4232
Douglas Gregor3545ff42009-09-21 16:56:56 +00004233 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4234 if (!Ctx)
4235 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004236
4237 // Try to instantiate any non-dependent declaration contexts before
4238 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004239 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004240 return;
4241
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004242 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004243 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004244 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004245 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004246
Douglas Gregor3545ff42009-09-21 16:56:56 +00004247 // The "template" keyword can follow "::" in the grammar, but only
4248 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004249 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004250 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004251 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004252
4253 // Add calls to overridden virtual functions, if there are any.
4254 //
4255 // FIXME: This isn't wonderful, because we don't know whether we're actually
4256 // in a context that permits expressions. This is a general issue with
4257 // qualified-id completions.
4258 if (!EnteringContext)
4259 MaybeAddOverrideCalls(*this, Ctx, Results);
4260 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004261
Douglas Gregorac322ec2010-08-27 21:18:54 +00004262 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4263 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4264
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004265 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004266 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004267 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004268}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004269
4270void Sema::CodeCompleteUsing(Scope *S) {
4271 if (!CodeCompleter)
4272 return;
4273
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004274 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004275 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004276 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4277 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004278 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004279
4280 // If we aren't in class scope, we could see the "namespace" keyword.
4281 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004282 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004283
4284 // After "using", we can see anything that would start a
4285 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004286 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004287 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4288 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004289 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004290
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004291 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004292 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004293 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004294}
4295
4296void Sema::CodeCompleteUsingDirective(Scope *S) {
4297 if (!CodeCompleter)
4298 return;
4299
Douglas Gregor3545ff42009-09-21 16:56:56 +00004300 // After "using namespace", we expect to see a namespace name or namespace
4301 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004302 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004303 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004304 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004305 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004306 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004307 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004308 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4309 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004310 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004311 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004312 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004313 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004314}
4315
4316void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4317 if (!CodeCompleter)
4318 return;
4319
Ted Kremenekc37877d2013-10-08 17:08:03 +00004320 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004321 if (!S->getParent())
4322 Ctx = Context.getTranslationUnitDecl();
4323
Douglas Gregor0ac41382010-09-23 23:01:17 +00004324 bool SuppressedGlobalResults
4325 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4326
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004327 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004328 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004329 SuppressedGlobalResults
4330 ? CodeCompletionContext::CCC_Namespace
4331 : CodeCompletionContext::CCC_Other,
4332 &ResultBuilder::IsNamespace);
4333
4334 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004335 // We only want to see those namespaces that have already been defined
4336 // within this scope, because its likely that the user is creating an
4337 // extended namespace declaration. Keep track of the most recent
4338 // definition of each namespace.
4339 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4340 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4341 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4342 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004343 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004344
4345 // Add the most recent definition (or extended definition) of each
4346 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004347 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004348 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004349 NS = OrigToLatest.begin(),
4350 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004351 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004352 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004353 NS->second, Results.getBasePriority(NS->second),
4354 nullptr),
4355 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004356 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004357 }
4358
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004359 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004360 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004361 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004362}
4363
4364void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4365 if (!CodeCompleter)
4366 return;
4367
Douglas Gregor3545ff42009-09-21 16:56:56 +00004368 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004369 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004370 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004371 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004372 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004373 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004374 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4375 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004376 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004377 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004378 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004379}
4380
Douglas Gregorc811ede2009-09-18 20:05:18 +00004381void Sema::CodeCompleteOperatorName(Scope *S) {
4382 if (!CodeCompleter)
4383 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004384
John McCall276321a2010-08-25 06:19:51 +00004385 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004386 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004387 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004388 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004389 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004390 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004391
Douglas Gregor3545ff42009-09-21 16:56:56 +00004392 // Add the names of overloadable operators.
4393#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4394 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004395 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004396#include "clang/Basic/OperatorKinds.def"
4397
4398 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004399 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004400 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004401 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4402 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004403
4404 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004405 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004406 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004407
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004408 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004409 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004410 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004411}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004412
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004413void Sema::CodeCompleteConstructorInitializer(
4414 Decl *ConstructorD,
4415 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004416 if (!ConstructorD)
4417 return;
4418
4419 AdjustDeclIfTemplate(ConstructorD);
4420
4421 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004422 if (!Constructor)
4423 return;
4424
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004425 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004426 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004427 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004428 Results.EnterNewScope();
4429
4430 // Fill in any already-initialized fields or base classes.
4431 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4432 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004433 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004434 if (Initializers[I]->isBaseInitializer())
4435 InitializedBases.insert(
4436 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4437 else
Francois Pichetd583da02010-12-04 09:14:42 +00004438 InitializedFields.insert(cast<FieldDecl>(
4439 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004440 }
4441
4442 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004443 CodeCompletionBuilder Builder(Results.getAllocator(),
4444 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004445 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004446 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004447 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004448 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004449 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4450 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004451 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004452 = !Initializers.empty() &&
4453 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004454 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004455 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004456 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004457 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004458
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004459 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004460 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004461 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004462 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4463 Builder.AddPlaceholderChunk("args");
4464 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4465 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004466 SawLastInitializer? CCP_NextInitializer
4467 : CCP_MemberDeclaration));
4468 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004469 }
4470
4471 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004472 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004473 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4474 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004475 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004476 = !Initializers.empty() &&
4477 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004478 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004479 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004480 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004481 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004482
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004483 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004484 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004485 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004486 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4487 Builder.AddPlaceholderChunk("args");
4488 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4489 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004490 SawLastInitializer? CCP_NextInitializer
4491 : CCP_MemberDeclaration));
4492 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004493 }
4494
4495 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004496 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004497 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4498 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004499 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004500 = !Initializers.empty() &&
4501 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004502 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004503 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004504 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004505
4506 if (!Field->getDeclName())
4507 continue;
4508
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004509 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004510 Field->getIdentifier()->getName()));
4511 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4512 Builder.AddPlaceholderChunk("args");
4513 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4514 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004515 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004516 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004517 CXCursor_MemberRef,
4518 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004519 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004520 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004521 }
4522 Results.ExitScope();
4523
Douglas Gregor0ac41382010-09-23 23:01:17 +00004524 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004525 Results.data(), Results.size());
4526}
4527
Douglas Gregord8c61782012-02-15 15:34:24 +00004528/// \brief Determine whether this scope denotes a namespace.
4529static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004530 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004531 if (!DC)
4532 return false;
4533
4534 return DC->isFileContext();
4535}
4536
4537void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4538 bool AfterAmpersand) {
4539 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004540 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004541 CodeCompletionContext::CCC_Other);
4542 Results.EnterNewScope();
4543
4544 // Note what has already been captured.
4545 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4546 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004547 for (const auto &C : Intro.Captures) {
4548 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004549 IncludedThis = true;
4550 continue;
4551 }
4552
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004553 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004554 }
4555
4556 // Look for other capturable variables.
4557 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004558 for (const auto *D : S->decls()) {
4559 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004560 if (!Var ||
4561 !Var->hasLocalStorage() ||
4562 Var->hasAttr<BlocksAttr>())
4563 continue;
4564
David Blaikie82e95a32014-11-19 07:49:47 +00004565 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004566 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004568 }
4569 }
4570
4571 // Add 'this', if it would be valid.
4572 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4573 addThisCompletion(*this, Results);
4574
4575 Results.ExitScope();
4576
4577 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4578 Results.data(), Results.size());
4579}
4580
James Dennett596e4752012-06-14 03:11:41 +00004581/// Macro that optionally prepends an "@" to the string literal passed in via
4582/// Keyword, depending on whether NeedAt is true or false.
4583#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4584
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004585static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004586 ResultBuilder &Results,
4587 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004588 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004589 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004590 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004591
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004592 CodeCompletionBuilder Builder(Results.getAllocator(),
4593 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004594 if (LangOpts.ObjC2) {
4595 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004596 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4598 Builder.AddPlaceholderChunk("property");
4599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004600
4601 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004602 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004603 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4604 Builder.AddPlaceholderChunk("property");
4605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004606 }
4607}
4608
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004609static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004610 ResultBuilder &Results,
4611 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004612 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004613
4614 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004615 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004616
4617 if (LangOpts.ObjC2) {
4618 // @property
James Dennett596e4752012-06-14 03:11:41 +00004619 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004620
4621 // @required
James Dennett596e4752012-06-14 03:11:41 +00004622 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004623
4624 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004625 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004626 }
4627}
4628
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004629static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004630 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004631 CodeCompletionBuilder Builder(Results.getAllocator(),
4632 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004633
4634 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004635 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4637 Builder.AddPlaceholderChunk("name");
4638 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004639
Douglas Gregorf4c33342010-05-28 00:22:41 +00004640 if (Results.includeCodePatterns()) {
4641 // @interface name
4642 // FIXME: Could introduce the whole pattern, including superclasses and
4643 // such.
James Dennett596e4752012-06-14 03:11:41 +00004644 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004645 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4646 Builder.AddPlaceholderChunk("class");
4647 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004648
Douglas Gregorf4c33342010-05-28 00:22:41 +00004649 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004650 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004651 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4652 Builder.AddPlaceholderChunk("protocol");
4653 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004654
4655 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004656 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004657 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4658 Builder.AddPlaceholderChunk("class");
4659 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004660 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004661
4662 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004663 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004664 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4665 Builder.AddPlaceholderChunk("alias");
4666 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4667 Builder.AddPlaceholderChunk("class");
4668 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004669
4670 if (Results.getSema().getLangOpts().Modules) {
4671 // @import name
4672 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4673 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4674 Builder.AddPlaceholderChunk("module");
4675 Results.AddResult(Result(Builder.TakeString()));
4676 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004677}
4678
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004679void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004680 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004681 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004682 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004683 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004684 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004685 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004686 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004687 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004688 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004689 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004690 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004691 HandleCodeCompleteResults(this, CodeCompleter,
4692 CodeCompletionContext::CCC_Other,
4693 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004694}
4695
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004696static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004697 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004698 CodeCompletionBuilder Builder(Results.getAllocator(),
4699 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004700
4701 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004702 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004703 if (Results.getSema().getLangOpts().CPlusPlus ||
4704 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004705 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004706 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004707 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004708 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4709 Builder.AddPlaceholderChunk("type-name");
4710 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4711 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004712
4713 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004714 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004715 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004716 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4717 Builder.AddPlaceholderChunk("protocol-name");
4718 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4719 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004720
4721 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004722 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004723 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004724 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4725 Builder.AddPlaceholderChunk("selector");
4726 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4727 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004728
4729 // @"string"
4730 Builder.AddResultTypeChunk("NSString *");
4731 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4732 Builder.AddPlaceholderChunk("string");
4733 Builder.AddTextChunk("\"");
4734 Results.AddResult(Result(Builder.TakeString()));
4735
Douglas Gregor951de302012-07-17 23:24:47 +00004736 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004737 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004738 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004739 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004740 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4741 Results.AddResult(Result(Builder.TakeString()));
4742
Douglas Gregor951de302012-07-17 23:24:47 +00004743 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004744 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004745 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004746 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004747 Builder.AddChunk(CodeCompletionString::CK_Colon);
4748 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4749 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004750 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4751 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004752
Douglas Gregor951de302012-07-17 23:24:47 +00004753 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004754 Builder.AddResultTypeChunk("id");
4755 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004756 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4758 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004759}
4760
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004761static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004762 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004763 CodeCompletionBuilder Builder(Results.getAllocator(),
4764 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004765
Douglas Gregorf4c33342010-05-28 00:22:41 +00004766 if (Results.includeCodePatterns()) {
4767 // @try { statements } @catch ( declaration ) { statements } @finally
4768 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004769 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004770 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4771 Builder.AddPlaceholderChunk("statements");
4772 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4773 Builder.AddTextChunk("@catch");
4774 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4775 Builder.AddPlaceholderChunk("parameter");
4776 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4777 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4778 Builder.AddPlaceholderChunk("statements");
4779 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4780 Builder.AddTextChunk("@finally");
4781 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4782 Builder.AddPlaceholderChunk("statements");
4783 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4784 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004785 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004786
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004787 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004788 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004789 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4790 Builder.AddPlaceholderChunk("expression");
4791 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004792
Douglas Gregorf4c33342010-05-28 00:22:41 +00004793 if (Results.includeCodePatterns()) {
4794 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004795 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004796 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4797 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4798 Builder.AddPlaceholderChunk("expression");
4799 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4800 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4801 Builder.AddPlaceholderChunk("statements");
4802 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004804 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004805}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004806
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004807static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004808 ResultBuilder &Results,
4809 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004810 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004811 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4812 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4813 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004814 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004815 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004816}
4817
4818void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004819 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004820 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004821 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004822 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004823 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004824 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004825 HandleCodeCompleteResults(this, CodeCompleter,
4826 CodeCompletionContext::CCC_Other,
4827 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004828}
4829
4830void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004831 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004832 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004833 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004834 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004835 AddObjCStatementResults(Results, false);
4836 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004837 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004838 HandleCodeCompleteResults(this, CodeCompleter,
4839 CodeCompletionContext::CCC_Other,
4840 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004841}
4842
4843void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004844 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004845 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004846 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004847 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004848 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004849 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004850 HandleCodeCompleteResults(this, CodeCompleter,
4851 CodeCompletionContext::CCC_Other,
4852 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004853}
4854
Douglas Gregore6078da2009-11-19 00:14:45 +00004855/// \brief Determine whether the addition of the given flag to an Objective-C
4856/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004857static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004858 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004859 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004860 return true;
4861
Bill Wendling44426052012-12-20 19:22:21 +00004862 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004863
4864 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004865 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4866 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004867 return true;
4868
Jordan Rose53cb2f32012-08-20 20:01:13 +00004869 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004870 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004871 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004872 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004873 ObjCDeclSpec::DQ_PR_retain |
4874 ObjCDeclSpec::DQ_PR_strong |
4875 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004876 if (AssignCopyRetMask &&
4877 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004878 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004879 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004880 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004881 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4882 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004883 return true;
4884
4885 return false;
4886}
4887
Douglas Gregor36029f42009-11-18 23:08:07 +00004888void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004889 if (!CodeCompleter)
4890 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004891
Bill Wendling44426052012-12-20 19:22:21 +00004892 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004893
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004894 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004895 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004896 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004897 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004898 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004899 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004900 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004901 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004902 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004903 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4904 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004905 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004906 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004907 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004908 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004909 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004910 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004911 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004912 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004913 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004914 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004915 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004916 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004917
4918 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00004919 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004920 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004921 Results.AddResult(CodeCompletionResult("weak"));
4922
Bill Wendling44426052012-12-20 19:22:21 +00004923 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004924 CodeCompletionBuilder Setter(Results.getAllocator(),
4925 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004926 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004927 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004928 Setter.AddPlaceholderChunk("method");
4929 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004930 }
Bill Wendling44426052012-12-20 19:22:21 +00004931 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004932 CodeCompletionBuilder Getter(Results.getAllocator(),
4933 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004934 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004935 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004936 Getter.AddPlaceholderChunk("method");
4937 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004938 }
Douglas Gregor86b42682015-06-19 18:27:52 +00004939 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4940 Results.AddResult(CodeCompletionResult("nonnull"));
4941 Results.AddResult(CodeCompletionResult("nullable"));
4942 Results.AddResult(CodeCompletionResult("null_unspecified"));
4943 Results.AddResult(CodeCompletionResult("null_resettable"));
4944 }
Steve Naroff936354c2009-10-08 21:55:05 +00004945 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004946 HandleCodeCompleteResults(this, CodeCompleter,
4947 CodeCompletionContext::CCC_Other,
4948 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004949}
Steve Naroffeae65032009-11-07 02:08:14 +00004950
James Dennettf1243872012-06-17 05:33:25 +00004951/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004952/// via code completion.
4953enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004954 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4955 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4956 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004957};
4958
Douglas Gregor67c692c2010-08-26 15:07:07 +00004959static bool isAcceptableObjCSelector(Selector Sel,
4960 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004961 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004962 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004963 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004964 if (NumSelIdents > Sel.getNumArgs())
4965 return false;
4966
4967 switch (WantKind) {
4968 case MK_Any: break;
4969 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4970 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4971 }
4972
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004973 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4974 return false;
4975
Douglas Gregor67c692c2010-08-26 15:07:07 +00004976 for (unsigned I = 0; I != NumSelIdents; ++I)
4977 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4978 return false;
4979
4980 return true;
4981}
4982
Douglas Gregorc8537c52009-11-19 07:41:15 +00004983static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4984 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004985 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004986 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004987 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004988 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004989}
Douglas Gregor1154e272010-09-16 16:06:31 +00004990
4991namespace {
4992 /// \brief A set of selectors, which is used to avoid introducing multiple
4993 /// completions with the same selector into the result set.
4994 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4995}
4996
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004997/// \brief Add all of the Objective-C methods in the given Objective-C
4998/// container to the set of results.
4999///
5000/// The container will be a class, protocol, category, or implementation of
5001/// any of the above. This mether will recurse to include methods from
5002/// the superclasses of classes along with their categories, protocols, and
5003/// implementations.
5004///
5005/// \param Container the container in which we'll look to find methods.
5006///
James Dennett596e4752012-06-14 03:11:41 +00005007/// \param WantInstanceMethods Whether to add instance methods (only); if
5008/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005009///
5010/// \param CurContext the context in which we're performing the lookup that
5011/// finds methods.
5012///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005013/// \param AllowSameLength Whether we allow a method to be added to the list
5014/// when it has the same number of parameters as we have selector identifiers.
5015///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005016/// \param Results the structure into which we'll add results.
5017static void AddObjCMethods(ObjCContainerDecl *Container,
5018 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00005019 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005020 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005021 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00005022 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005023 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00005024 ResultBuilder &Results,
5025 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00005026 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005027 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005028 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5029 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005030 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005031 // The instance methods on the root class can be messaged via the
5032 // metaclass.
5033 if (M->isInstanceMethod() == WantInstanceMethods ||
5034 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005035 // Check whether the selector identifiers we've been given are a
5036 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005037 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005038 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005039
David Blaikie82e95a32014-11-19 07:49:47 +00005040 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005041 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005042
5043 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005044 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005045 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005046 if (!InOriginalClass)
5047 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005048 Results.MaybeAddResult(R, CurContext);
5049 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005050 }
5051
Douglas Gregorf37c9492010-09-16 15:34:59 +00005052 // Visit the protocols of protocols.
5053 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005054 if (Protocol->hasDefinition()) {
5055 const ObjCList<ObjCProtocolDecl> &Protocols
5056 = Protocol->getReferencedProtocols();
5057 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5058 E = Protocols.end();
5059 I != E; ++I)
5060 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005061 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005062 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005063 }
5064
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005065 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005066 return;
5067
5068 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005069 for (auto *I : IFace->protocols())
5070 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005071 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005072
5073 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005074 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005075 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005076 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005077 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005078
5079 // Add a categories protocol methods.
5080 const ObjCList<ObjCProtocolDecl> &Protocols
5081 = CatDecl->getReferencedProtocols();
5082 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5083 E = Protocols.end();
5084 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005085 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005086 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005087 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005088
5089 // Add methods in category implementations.
5090 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005091 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005092 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005093 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005094 }
5095
5096 // Add methods in superclass.
5097 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005098 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005099 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005100 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005101
5102 // Add methods in our implementation, if any.
5103 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005104 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005105 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005106 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005107}
5108
5109
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005110void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005111 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005112 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005113 if (!Class) {
5114 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005115 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005116 Class = Category->getClassInterface();
5117
5118 if (!Class)
5119 return;
5120 }
5121
5122 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005123 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005124 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005125 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005126 Results.EnterNewScope();
5127
Douglas Gregor1154e272010-09-16 16:06:31 +00005128 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005129 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005130 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005131 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005132 HandleCodeCompleteResults(this, CodeCompleter,
5133 CodeCompletionContext::CCC_Other,
5134 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005135}
5136
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005137void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005138 // Try to find the interface where setters might live.
5139 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005140 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005141 if (!Class) {
5142 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005143 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005144 Class = Category->getClassInterface();
5145
5146 if (!Class)
5147 return;
5148 }
5149
5150 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005151 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005152 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005153 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005154 Results.EnterNewScope();
5155
Douglas Gregor1154e272010-09-16 16:06:31 +00005156 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005157 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005158 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005159
5160 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005161 HandleCodeCompleteResults(this, CodeCompleter,
5162 CodeCompletionContext::CCC_Other,
5163 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005164}
5165
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005166void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5167 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005168 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005169 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005170 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005171 Results.EnterNewScope();
5172
5173 // Add context-sensitive, Objective-C parameter-passing keywords.
5174 bool AddedInOut = false;
5175 if ((DS.getObjCDeclQualifier() &
5176 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5177 Results.AddResult("in");
5178 Results.AddResult("inout");
5179 AddedInOut = true;
5180 }
5181 if ((DS.getObjCDeclQualifier() &
5182 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5183 Results.AddResult("out");
5184 if (!AddedInOut)
5185 Results.AddResult("inout");
5186 }
5187 if ((DS.getObjCDeclQualifier() &
5188 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5189 ObjCDeclSpec::DQ_Oneway)) == 0) {
5190 Results.AddResult("bycopy");
5191 Results.AddResult("byref");
5192 Results.AddResult("oneway");
5193 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005194 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5195 Results.AddResult("nonnull");
5196 Results.AddResult("nullable");
5197 Results.AddResult("null_unspecified");
5198 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005199
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005200 // If we're completing the return type of an Objective-C method and the
5201 // identifier IBAction refers to a macro, provide a completion item for
5202 // an action, e.g.,
5203 // IBAction)<#selector#>:(id)sender
5204 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005205 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005206 CodeCompletionBuilder Builder(Results.getAllocator(),
5207 Results.getCodeCompletionTUInfo(),
5208 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005209 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005210 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005211 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005212 Builder.AddChunk(CodeCompletionString::CK_Colon);
5213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005214 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005216 Builder.AddTextChunk("sender");
5217 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5218 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005219
5220 // If we're completing the return type, provide 'instancetype'.
5221 if (!IsParameter) {
5222 Results.AddResult(CodeCompletionResult("instancetype"));
5223 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005224
Douglas Gregor99fa2642010-08-24 01:06:58 +00005225 // Add various builtin type names and specifiers.
5226 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5227 Results.ExitScope();
5228
5229 // Add the various type names
5230 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5231 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5232 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5233 CodeCompleter->includeGlobals());
5234
5235 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005236 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005237
5238 HandleCodeCompleteResults(this, CodeCompleter,
5239 CodeCompletionContext::CCC_Type,
5240 Results.data(), Results.size());
5241}
5242
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005243/// \brief When we have an expression with type "id", we may assume
5244/// that it has some more-specific class type based on knowledge of
5245/// common uses of Objective-C. This routine returns that class type,
5246/// or NULL if no better result could be determined.
5247static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005248 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005249 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005250 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005251
5252 Selector Sel = Msg->getSelector();
5253 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005254 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005255
5256 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5257 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005258 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005259
5260 ObjCMethodDecl *Method = Msg->getMethodDecl();
5261 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005262 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005263
5264 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005265 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005266 switch (Msg->getReceiverKind()) {
5267 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005268 if (const ObjCObjectType *ObjType
5269 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5270 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005271 break;
5272
5273 case ObjCMessageExpr::Instance: {
5274 QualType T = Msg->getInstanceReceiver()->getType();
5275 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5276 IFace = Ptr->getInterfaceDecl();
5277 break;
5278 }
5279
5280 case ObjCMessageExpr::SuperInstance:
5281 case ObjCMessageExpr::SuperClass:
5282 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005283 }
5284
5285 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005286 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005287
5288 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5289 if (Method->isInstanceMethod())
5290 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5291 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005292 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005293 .Case("autorelease", IFace)
5294 .Case("copy", IFace)
5295 .Case("copyWithZone", IFace)
5296 .Case("mutableCopy", IFace)
5297 .Case("mutableCopyWithZone", IFace)
5298 .Case("awakeFromCoder", IFace)
5299 .Case("replacementObjectFromCoder", IFace)
5300 .Case("class", IFace)
5301 .Case("classForCoder", IFace)
5302 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005303 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005304
5305 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5306 .Case("new", IFace)
5307 .Case("alloc", IFace)
5308 .Case("allocWithZone", IFace)
5309 .Case("class", IFace)
5310 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005311 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005312}
5313
Douglas Gregor6fc04132010-08-27 15:10:57 +00005314// Add a special completion for a message send to "super", which fills in the
5315// most likely case of forwarding all of our arguments to the superclass
5316// function.
5317///
5318/// \param S The semantic analysis object.
5319///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005320/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005321/// the "super" keyword. Otherwise, we just need to provide the arguments.
5322///
5323/// \param SelIdents The identifiers in the selector that have already been
5324/// provided as arguments for a send to "super".
5325///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005326/// \param Results The set of results to augment.
5327///
5328/// \returns the Objective-C method declaration that would be invoked by
5329/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005330static ObjCMethodDecl *AddSuperSendCompletion(
5331 Sema &S, bool NeedSuperKeyword,
5332 ArrayRef<IdentifierInfo *> SelIdents,
5333 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005334 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5335 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005336 return nullptr;
5337
Douglas Gregor6fc04132010-08-27 15:10:57 +00005338 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5339 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005340 return nullptr;
5341
Douglas Gregor6fc04132010-08-27 15:10:57 +00005342 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005343 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005344 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5345 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005346 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5347 CurMethod->isInstanceMethod());
5348
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005349 // Check in categories or class extensions.
5350 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005351 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005352 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005353 CurMethod->isInstanceMethod())))
5354 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005355 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005356 }
5357 }
5358
Douglas Gregor6fc04132010-08-27 15:10:57 +00005359 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005360 return nullptr;
5361
Douglas Gregor6fc04132010-08-27 15:10:57 +00005362 // Check whether the superclass method has the same signature.
5363 if (CurMethod->param_size() != SuperMethod->param_size() ||
5364 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005365 return nullptr;
5366
Douglas Gregor6fc04132010-08-27 15:10:57 +00005367 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5368 CurPEnd = CurMethod->param_end(),
5369 SuperP = SuperMethod->param_begin();
5370 CurP != CurPEnd; ++CurP, ++SuperP) {
5371 // Make sure the parameter types are compatible.
5372 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5373 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005374 return nullptr;
5375
Douglas Gregor6fc04132010-08-27 15:10:57 +00005376 // Make sure we have a parameter name to forward!
5377 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005378 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005379 }
5380
5381 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005382 CodeCompletionBuilder Builder(Results.getAllocator(),
5383 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005384
5385 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005386 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5387 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005388 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005389
5390 // If we need the "super" keyword, add it (plus some spacing).
5391 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005392 Builder.AddTypedTextChunk("super");
5393 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005394 }
5395
5396 Selector Sel = CurMethod->getSelector();
5397 if (Sel.isUnarySelector()) {
5398 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005399 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005400 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005401 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005402 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005403 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005404 } else {
5405 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5406 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005407 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005408 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005409
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005410 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005411 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005412 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005413 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005414 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005415 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005416 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005417 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005418 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005419 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005420 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005421 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005422 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005423 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005424 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005425 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005426 }
5427 }
5428 }
5429
Douglas Gregor78254c82012-03-27 23:34:16 +00005430 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5431 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005432 return SuperMethod;
5433}
5434
Douglas Gregora817a192010-05-27 23:06:34 +00005435void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005436 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005437 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005438 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005439 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005440 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005441 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5442 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005443
Douglas Gregora817a192010-05-27 23:06:34 +00005444 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5445 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005446 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5447 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005448
5449 // If we are in an Objective-C method inside a class that has a superclass,
5450 // add "super" as an option.
5451 if (ObjCMethodDecl *Method = getCurMethodDecl())
5452 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005453 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005454 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005455
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005456 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005457 }
Douglas Gregora817a192010-05-27 23:06:34 +00005458
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005459 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005460 addThisCompletion(*this, Results);
5461
Douglas Gregora817a192010-05-27 23:06:34 +00005462 Results.ExitScope();
5463
5464 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005465 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005466 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005467 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005468
5469}
5470
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005471void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005472 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005473 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005474 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005475 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5476 // Figure out which interface we're in.
5477 CDecl = CurMethod->getClassInterface();
5478 if (!CDecl)
5479 return;
5480
5481 // Find the superclass of this class.
5482 CDecl = CDecl->getSuperClass();
5483 if (!CDecl)
5484 return;
5485
5486 if (CurMethod->isInstanceMethod()) {
5487 // We are inside an instance method, which means that the message
5488 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005489 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005490 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005491 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005492 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005493 }
5494
5495 // Fall through to send to the superclass in CDecl.
5496 } else {
5497 // "super" may be the name of a type or variable. Figure out which
5498 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005499 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005500 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5501 LookupOrdinaryName);
5502 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5503 // "super" names an interface. Use it.
5504 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005505 if (const ObjCObjectType *Iface
5506 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5507 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005508 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5509 // "super" names an unresolved type; we can't be more specific.
5510 } else {
5511 // Assume that "super" names some kind of value and parse that way.
5512 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005513 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005514 UnqualifiedId id;
5515 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005516 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5517 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005518 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005519 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005520 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005521 }
5522
5523 // Fall through
5524 }
5525
John McCallba7bf592010-08-24 05:47:05 +00005526 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005527 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005528 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005529 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005530 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005531 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005532}
5533
Douglas Gregor74661272010-09-21 00:03:25 +00005534/// \brief Given a set of code-completion results for the argument of a message
5535/// send, determine the preferred type (if any) for that argument expression.
5536static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5537 unsigned NumSelIdents) {
5538 typedef CodeCompletionResult Result;
5539 ASTContext &Context = Results.getSema().Context;
5540
5541 QualType PreferredType;
5542 unsigned BestPriority = CCP_Unlikely * 2;
5543 Result *ResultsData = Results.data();
5544 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5545 Result &R = ResultsData[I];
5546 if (R.Kind == Result::RK_Declaration &&
5547 isa<ObjCMethodDecl>(R.Declaration)) {
5548 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005549 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005550 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005551 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005552 ->getType();
5553 if (R.Priority < BestPriority || PreferredType.isNull()) {
5554 BestPriority = R.Priority;
5555 PreferredType = MyPreferredType;
5556 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5557 MyPreferredType)) {
5558 PreferredType = QualType();
5559 }
5560 }
5561 }
5562 }
5563 }
5564
5565 return PreferredType;
5566}
5567
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005568static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5569 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005570 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005571 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005572 bool IsSuper,
5573 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005574 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005575 ObjCInterfaceDecl *CDecl = nullptr;
5576
Douglas Gregor8ce33212009-11-17 17:59:40 +00005577 // If the given name refers to an interface type, retrieve the
5578 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005579 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005580 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005581 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005582 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5583 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005584 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005585
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005586 // Add all of the factory methods in this Objective-C class, its protocols,
5587 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005588 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005589
Douglas Gregor6fc04132010-08-27 15:10:57 +00005590 // If this is a send-to-super, try to add the special "super" send
5591 // completion.
5592 if (IsSuper) {
5593 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005594 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005595 Results.Ignore(SuperMethod);
5596 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005597
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005598 // If we're inside an Objective-C method definition, prefer its selector to
5599 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005600 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005601 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005602
Douglas Gregor1154e272010-09-16 16:06:31 +00005603 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005604 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005605 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005606 SemaRef.CurContext, Selectors, AtArgumentExpression,
5607 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005608 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005609 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005610
Douglas Gregord720daf2010-04-06 17:30:22 +00005611 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005612 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005613 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005614 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005615 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005616 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005617 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005618 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005619 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005620
5621 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005622 }
5623 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005624
5625 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5626 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005627 M != MEnd; ++M) {
5628 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005629 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005630 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005631 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005632 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005633
Nico Weber2e0c8f72014-12-27 03:58:08 +00005634 Result R(MethList->getMethod(),
5635 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005636 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005637 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005638 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005639 }
5640 }
5641 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005642
5643 Results.ExitScope();
5644}
Douglas Gregor6285f752010-04-06 16:40:00 +00005645
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005646void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005647 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005648 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005649 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005650
5651 QualType T = this->GetTypeFromParser(Receiver);
5652
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005653 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005654 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005655 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005656 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005657
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005658 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005659 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005660
5661 // If we're actually at the argument expression (rather than prior to the
5662 // selector), we're actually performing code completion for an expression.
5663 // Determine whether we have a single, best method. If so, we can
5664 // code-complete the expression using the corresponding parameter type as
5665 // our preferred type, improving completion results.
5666 if (AtArgumentExpression) {
5667 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005668 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005669 if (PreferredType.isNull())
5670 CodeCompleteOrdinaryName(S, PCC_Expression);
5671 else
5672 CodeCompleteExpression(S, PreferredType);
5673 return;
5674 }
5675
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005676 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005677 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005678 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005679}
5680
Richard Trieu2bd04012011-09-09 02:00:50 +00005681void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005682 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005683 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005684 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005685 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005686
5687 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005688
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005689 // If necessary, apply function/array conversion to the receiver.
5690 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005691 if (RecExpr) {
5692 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5693 if (Conv.isInvalid()) // conversion failed. bail.
5694 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005695 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005696 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005697 QualType ReceiverType = RecExpr? RecExpr->getType()
5698 : Super? Context.getObjCObjectPointerType(
5699 Context.getObjCInterfaceType(Super))
5700 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005701
Douglas Gregordc520b02010-11-08 21:12:30 +00005702 // If we're messaging an expression with type "id" or "Class", check
5703 // whether we know something special about the receiver that allows
5704 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005705 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005706 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5707 if (ReceiverType->isObjCClassType())
5708 return CodeCompleteObjCClassMessage(S,
5709 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005710 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005711 AtArgumentExpression, Super);
5712
5713 ReceiverType = Context.getObjCObjectPointerType(
5714 Context.getObjCInterfaceType(IFace));
5715 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005716 } else if (RecExpr && getLangOpts().CPlusPlus) {
5717 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5718 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005719 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005720 ReceiverType = RecExpr->getType();
5721 }
5722 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005723
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005724 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005725 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005726 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005727 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005728 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005729
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005730 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005731
Douglas Gregor6fc04132010-08-27 15:10:57 +00005732 // If this is a send-to-super, try to add the special "super" send
5733 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005734 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005735 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005736 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005737 Results.Ignore(SuperMethod);
5738 }
5739
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005740 // If we're inside an Objective-C method definition, prefer its selector to
5741 // others.
5742 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5743 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005744
Douglas Gregor1154e272010-09-16 16:06:31 +00005745 // Keep track of the selectors we've already added.
5746 VisitedSelectorSet Selectors;
5747
Douglas Gregora3329fa2009-11-18 00:06:18 +00005748 // Handle messages to Class. This really isn't a message to an instance
5749 // method, so we treat it the same way we would treat a message send to a
5750 // class method.
5751 if (ReceiverType->isObjCClassType() ||
5752 ReceiverType->isObjCQualifiedClassType()) {
5753 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5754 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005755 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005756 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005757 }
5758 }
5759 // Handle messages to a qualified ID ("id<foo>").
5760 else if (const ObjCObjectPointerType *QualID
5761 = ReceiverType->getAsObjCQualifiedIdType()) {
5762 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005763 for (auto *I : QualID->quals())
5764 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005765 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005766 }
5767 // Handle messages to a pointer to interface type.
5768 else if (const ObjCObjectPointerType *IFacePtr
5769 = ReceiverType->getAsObjCInterfacePointerType()) {
5770 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005771 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005772 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005773 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005774
5775 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005776 for (auto *I : IFacePtr->quals())
5777 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005778 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005779 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005780 // Handle messages to "id".
5781 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005782 // We're messaging "id", so provide all instance methods we know
5783 // about as code-completion results.
5784
5785 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005786 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005787 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005788 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5789 I != N; ++I) {
5790 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005791 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005792 continue;
5793
Sebastian Redl75d8a322010-08-02 23:18:59 +00005794 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005795 }
5796 }
5797
Sebastian Redl75d8a322010-08-02 23:18:59 +00005798 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5799 MEnd = MethodPool.end();
5800 M != MEnd; ++M) {
5801 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005802 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005803 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005804 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005805 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005806
Nico Weber2e0c8f72014-12-27 03:58:08 +00005807 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005808 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005809
Nico Weber2e0c8f72014-12-27 03:58:08 +00005810 Result R(MethList->getMethod(),
5811 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005812 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005813 R.AllParametersAreInformative = false;
5814 Results.MaybeAddResult(R, CurContext);
5815 }
5816 }
5817 }
Steve Naroffeae65032009-11-07 02:08:14 +00005818 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005819
5820
5821 // If we're actually at the argument expression (rather than prior to the
5822 // selector), we're actually performing code completion for an expression.
5823 // Determine whether we have a single, best method. If so, we can
5824 // code-complete the expression using the corresponding parameter type as
5825 // our preferred type, improving completion results.
5826 if (AtArgumentExpression) {
5827 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005828 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005829 if (PreferredType.isNull())
5830 CodeCompleteOrdinaryName(S, PCC_Expression);
5831 else
5832 CodeCompleteExpression(S, PreferredType);
5833 return;
5834 }
5835
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005836 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005837 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005838 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005839}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005840
Douglas Gregor68762e72010-08-23 21:17:50 +00005841void Sema::CodeCompleteObjCForCollection(Scope *S,
5842 DeclGroupPtrTy IterationVar) {
5843 CodeCompleteExpressionData Data;
5844 Data.ObjCCollection = true;
5845
5846 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005847 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005848 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5849 if (*I)
5850 Data.IgnoreDecls.push_back(*I);
5851 }
5852 }
5853
5854 CodeCompleteExpression(S, Data);
5855}
5856
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005857void Sema::CodeCompleteObjCSelector(Scope *S,
5858 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005859 // If we have an external source, load the entire class method
5860 // pool from the AST file.
5861 if (ExternalSource) {
5862 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5863 I != N; ++I) {
5864 Selector Sel = ExternalSource->GetExternalSelector(I);
5865 if (Sel.isNull() || MethodPool.count(Sel))
5866 continue;
5867
5868 ReadMethodPool(Sel);
5869 }
5870 }
5871
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005872 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005873 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005874 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005875 Results.EnterNewScope();
5876 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5877 MEnd = MethodPool.end();
5878 M != MEnd; ++M) {
5879
5880 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005881 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005882 continue;
5883
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005884 CodeCompletionBuilder Builder(Results.getAllocator(),
5885 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005886 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005887 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005888 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005889 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005890 continue;
5891 }
5892
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005893 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005894 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005895 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005896 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005897 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005898 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005899 Accumulator.clear();
5900 }
5901 }
5902
Benjamin Kramer632500c2011-07-26 16:59:25 +00005903 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005904 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005905 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005906 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005907 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005908 }
5909 Results.ExitScope();
5910
5911 HandleCodeCompleteResults(this, CodeCompleter,
5912 CodeCompletionContext::CCC_SelectorName,
5913 Results.data(), Results.size());
5914}
5915
Douglas Gregorbaf69612009-11-18 04:19:12 +00005916/// \brief Add all of the protocol declarations that we find in the given
5917/// (translation unit) context.
5918static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005919 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005920 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005921 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005922
Aaron Ballman629afae2014-03-07 19:56:05 +00005923 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005924 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005925 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005926 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005927 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5928 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005929 }
5930}
5931
Craig Topper883dd332015-12-24 23:58:11 +00005932void Sema::CodeCompleteObjCProtocolReferences(
5933 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005934 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005935 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005936 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005937
Douglas Gregora3b23b02010-12-09 21:44:02 +00005938 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5939 Results.EnterNewScope();
5940
5941 // Tell the result set to ignore all of the protocols we have
5942 // already seen.
5943 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00005944 for (const IdentifierLocPair &Pair : Protocols)
5945 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
5946 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00005947 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005948
Douglas Gregora3b23b02010-12-09 21:44:02 +00005949 // Add all protocols.
5950 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5951 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005952
Douglas Gregora3b23b02010-12-09 21:44:02 +00005953 Results.ExitScope();
5954 }
5955
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005956 HandleCodeCompleteResults(this, CodeCompleter,
5957 CodeCompletionContext::CCC_ObjCProtocolName,
5958 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005959}
5960
5961void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005962 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005963 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005964 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005965
Douglas Gregora3b23b02010-12-09 21:44:02 +00005966 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5967 Results.EnterNewScope();
5968
5969 // Add all protocols.
5970 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5971 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005972
Douglas Gregora3b23b02010-12-09 21:44:02 +00005973 Results.ExitScope();
5974 }
5975
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005976 HandleCodeCompleteResults(this, CodeCompleter,
5977 CodeCompletionContext::CCC_ObjCProtocolName,
5978 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005979}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005980
5981/// \brief Add all of the Objective-C interface declarations that we find in
5982/// the given (translation unit) context.
5983static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5984 bool OnlyForwardDeclarations,
5985 bool OnlyUnimplemented,
5986 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005987 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005988
Aaron Ballman629afae2014-03-07 19:56:05 +00005989 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005990 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005991 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005992 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005993 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005994 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5995 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005996 }
5997}
5998
5999void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006000 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006001 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006002 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006003 Results.EnterNewScope();
6004
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006005 if (CodeCompleter->includeGlobals()) {
6006 // Add all classes.
6007 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6008 false, Results);
6009 }
6010
Douglas Gregor49c22a72009-11-18 16:26:39 +00006011 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006012
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006013 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006014 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006015 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006016}
6017
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006018void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6019 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006020 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006021 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006022 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006023 Results.EnterNewScope();
6024
6025 // Make sure that we ignore the class we're currently defining.
6026 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006027 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006028 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006029 Results.Ignore(CurClass);
6030
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006031 if (CodeCompleter->includeGlobals()) {
6032 // Add all classes.
6033 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6034 false, Results);
6035 }
6036
Douglas Gregor49c22a72009-11-18 16:26:39 +00006037 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006038
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006039 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006040 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006041 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006042}
6043
6044void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006045 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006046 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006047 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006048 Results.EnterNewScope();
6049
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006050 if (CodeCompleter->includeGlobals()) {
6051 // Add all unimplemented classes.
6052 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6053 true, Results);
6054 }
6055
Douglas Gregor49c22a72009-11-18 16:26:39 +00006056 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006057
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006058 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006059 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006060 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006061}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006062
6063void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006064 IdentifierInfo *ClassName,
6065 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006066 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006067
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006068 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006069 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006070 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006071
6072 // Ignore any categories we find that have already been implemented by this
6073 // interface.
6074 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6075 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006076 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006077 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006078 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006079 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006080 }
6081
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006082 // Add all of the categories we know about.
6083 Results.EnterNewScope();
6084 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006085 for (const auto *D : TU->decls())
6086 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006087 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006088 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6089 nullptr),
6090 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006091 Results.ExitScope();
6092
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006093 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006094 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006095 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006096}
6097
6098void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006099 IdentifierInfo *ClassName,
6100 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006101 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006102
6103 // Find the corresponding interface. If we couldn't find the interface, the
6104 // program itself is ill-formed. However, we'll try to be helpful still by
6105 // providing the list of all of the categories we know about.
6106 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006107 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006108 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6109 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006110 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006111
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006112 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006113 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006114 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006115
6116 // Add all of the categories that have have corresponding interface
6117 // declarations in this class and any of its superclasses, except for
6118 // already-implemented categories in the class itself.
6119 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6120 Results.EnterNewScope();
6121 bool IgnoreImplemented = true;
6122 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006123 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006124 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006125 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006126 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6127 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006128 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006129
6130 Class = Class->getSuperClass();
6131 IgnoreImplemented = false;
6132 }
6133 Results.ExitScope();
6134
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006135 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006136 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006137 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006138}
Douglas Gregor5d649882009-11-18 22:32:06 +00006139
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006140void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006141 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006142 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006143 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006144 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006145
6146 // Figure out where this @synthesize lives.
6147 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006148 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006149 if (!Container ||
6150 (!isa<ObjCImplementationDecl>(Container) &&
6151 !isa<ObjCCategoryImplDecl>(Container)))
6152 return;
6153
6154 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006155 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006156 for (const auto *D : Container->decls())
6157 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006158 Results.Ignore(PropertyImpl->getPropertyDecl());
6159
6160 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006161 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006162 Results.EnterNewScope();
6163 if (ObjCImplementationDecl *ClassImpl
6164 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006165 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006166 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006167 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006168 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006169 AddObjCProperties(CCContext,
6170 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006171 false, /*AllowNullaryMethods=*/false, CurContext,
6172 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006173 Results.ExitScope();
6174
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006175 HandleCodeCompleteResults(this, CodeCompleter,
6176 CodeCompletionContext::CCC_Other,
6177 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006178}
6179
6180void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006181 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006182 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006183 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006184 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006185 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006186
6187 // Figure out where this @synthesize lives.
6188 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006189 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006190 if (!Container ||
6191 (!isa<ObjCImplementationDecl>(Container) &&
6192 !isa<ObjCCategoryImplDecl>(Container)))
6193 return;
6194
6195 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006196 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006197 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006198 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006199 Class = ClassImpl->getClassInterface();
6200 else
6201 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6202 ->getClassInterface();
6203
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006204 // Determine the type of the property we're synthesizing.
6205 QualType PropertyType = Context.getObjCIdType();
6206 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006207 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6208 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006209 PropertyType
6210 = Property->getType().getNonReferenceType().getUnqualifiedType();
6211
6212 // Give preference to ivars
6213 Results.setPreferredType(PropertyType);
6214 }
6215 }
6216
Douglas Gregor5d649882009-11-18 22:32:06 +00006217 // Add all of the instance variables in this class and its superclasses.
6218 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006219 bool SawSimilarlyNamedIvar = false;
6220 std::string NameWithPrefix;
6221 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006222 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006223 std::string NameWithSuffix = PropertyName->getName().str();
6224 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006225 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006226 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6227 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006228 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6229 CurContext, nullptr, false);
6230
Douglas Gregor331faa02011-04-18 14:13:53 +00006231 // Determine whether we've seen an ivar with a name similar to the
6232 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006233 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006234 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006235 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006236 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006237
6238 // Reduce the priority of this result by one, to give it a slight
6239 // advantage over other results whose names don't match so closely.
6240 if (Results.size() &&
6241 Results.data()[Results.size() - 1].Kind
6242 == CodeCompletionResult::RK_Declaration &&
6243 Results.data()[Results.size() - 1].Declaration == Ivar)
6244 Results.data()[Results.size() - 1].Priority--;
6245 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006246 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006247 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006248
6249 if (!SawSimilarlyNamedIvar) {
6250 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006251 // an ivar of the appropriate type.
6252 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006253 typedef CodeCompletionResult Result;
6254 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006255 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6256 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006257
Douglas Gregor75acd922011-09-27 23:30:47 +00006258 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006259 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006260 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006261 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6262 Results.AddResult(Result(Builder.TakeString(), Priority,
6263 CXCursor_ObjCIvarDecl));
6264 }
6265
Douglas Gregor5d649882009-11-18 22:32:06 +00006266 Results.ExitScope();
6267
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006268 HandleCodeCompleteResults(this, CodeCompleter,
6269 CodeCompletionContext::CCC_Other,
6270 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006271}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006272
Douglas Gregor416b5752010-08-25 01:08:01 +00006273// Mapping from selectors to the methods that implement that selector, along
6274// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006275typedef llvm::DenseMap<
6276 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006277
6278/// \brief Find all of the methods that reside in the given container
6279/// (and its superclasses, protocols, etc.) that meet the given
6280/// criteria. Insert those methods into the map of known methods,
6281/// indexed by selector so they can be easily found.
6282static void FindImplementableMethods(ASTContext &Context,
6283 ObjCContainerDecl *Container,
6284 bool WantInstanceMethods,
6285 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006286 KnownMethodsMap &KnownMethods,
6287 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006288 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006289 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006290 if (!IFace->hasDefinition())
6291 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006292
6293 IFace = IFace->getDefinition();
6294 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006295
Douglas Gregor636a61e2010-04-07 00:21:17 +00006296 const ObjCList<ObjCProtocolDecl> &Protocols
6297 = IFace->getReferencedProtocols();
6298 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006299 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006300 I != E; ++I)
6301 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006302 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006303
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006304 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006305 for (auto *Cat : IFace->visible_categories()) {
6306 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006307 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006308 }
6309
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006310 // Visit the superclass.
6311 if (IFace->getSuperClass())
6312 FindImplementableMethods(Context, IFace->getSuperClass(),
6313 WantInstanceMethods, ReturnType,
6314 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006315 }
6316
6317 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6318 // Recurse into protocols.
6319 const ObjCList<ObjCProtocolDecl> &Protocols
6320 = Category->getReferencedProtocols();
6321 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006322 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006323 I != E; ++I)
6324 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006325 KnownMethods, InOriginalClass);
6326
6327 // If this category is the original class, jump to the interface.
6328 if (InOriginalClass && Category->getClassInterface())
6329 FindImplementableMethods(Context, Category->getClassInterface(),
6330 WantInstanceMethods, ReturnType, KnownMethods,
6331 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006332 }
6333
6334 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006335 // Make sure we have a definition; that's what we'll walk.
6336 if (!Protocol->hasDefinition())
6337 return;
6338 Protocol = Protocol->getDefinition();
6339 Container = Protocol;
6340
6341 // Recurse into protocols.
6342 const ObjCList<ObjCProtocolDecl> &Protocols
6343 = Protocol->getReferencedProtocols();
6344 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6345 E = Protocols.end();
6346 I != E; ++I)
6347 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6348 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006349 }
6350
6351 // Add methods in this container. This operation occurs last because
6352 // we want the methods from this container to override any methods
6353 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006354 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006355 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006356 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006357 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006358 continue;
6359
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006360 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006361 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006362 }
6363 }
6364}
6365
Douglas Gregor669a25a2011-02-17 00:22:45 +00006366/// \brief Add the parenthesized return or parameter type chunk to a code
6367/// completion string.
6368static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006369 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006370 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006371 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006372 CodeCompletionBuilder &Builder) {
6373 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006374 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006375 if (!Quals.empty())
6376 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006377 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006378 Builder.getAllocator()));
6379 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6380}
6381
6382/// \brief Determine whether the given class is or inherits from a class by
6383/// the given name.
6384static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006385 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006386 if (!Class)
6387 return false;
6388
6389 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6390 return true;
6391
6392 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6393}
6394
6395/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6396/// Key-Value Observing (KVO).
6397static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6398 bool IsInstanceMethod,
6399 QualType ReturnType,
6400 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006401 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006402 ResultBuilder &Results) {
6403 IdentifierInfo *PropName = Property->getIdentifier();
6404 if (!PropName || PropName->getLength() == 0)
6405 return;
6406
Douglas Gregor75acd922011-09-27 23:30:47 +00006407 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6408
Douglas Gregor669a25a2011-02-17 00:22:45 +00006409 // Builder that will create each code completion.
6410 typedef CodeCompletionResult Result;
6411 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006412 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006413
6414 // The selector table.
6415 SelectorTable &Selectors = Context.Selectors;
6416
6417 // The property name, copied into the code completion allocation region
6418 // on demand.
6419 struct KeyHolder {
6420 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006421 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006422 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006423
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006424 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006425 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6426
Douglas Gregor669a25a2011-02-17 00:22:45 +00006427 operator const char *() {
6428 if (CopiedKey)
6429 return CopiedKey;
6430
6431 return CopiedKey = Allocator.CopyString(Key);
6432 }
6433 } Key(Allocator, PropName->getName());
6434
6435 // The uppercased name of the property name.
6436 std::string UpperKey = PropName->getName();
6437 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006438 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006439
6440 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6441 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6442 Property->getType());
6443 bool ReturnTypeMatchesVoid
6444 = ReturnType.isNull() || ReturnType->isVoidType();
6445
6446 // Add the normal accessor -(type)key.
6447 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006448 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006449 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6450 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006451 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6452 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006453
6454 Builder.AddTypedTextChunk(Key);
6455 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6456 CXCursor_ObjCInstanceMethodDecl));
6457 }
6458
6459 // If we have an integral or boolean property (or the user has provided
6460 // an integral or boolean return type), add the accessor -(type)isKey.
6461 if (IsInstanceMethod &&
6462 ((!ReturnType.isNull() &&
6463 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6464 (ReturnType.isNull() &&
6465 (Property->getType()->isIntegerType() ||
6466 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006467 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006468 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006469 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6470 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006471 if (ReturnType.isNull()) {
6472 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6473 Builder.AddTextChunk("BOOL");
6474 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6475 }
6476
6477 Builder.AddTypedTextChunk(
6478 Allocator.CopyString(SelectorId->getName()));
6479 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6480 CXCursor_ObjCInstanceMethodDecl));
6481 }
6482 }
6483
6484 // Add the normal mutator.
6485 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6486 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006487 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006488 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006489 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006490 if (ReturnType.isNull()) {
6491 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6492 Builder.AddTextChunk("void");
6493 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6494 }
6495
6496 Builder.AddTypedTextChunk(
6497 Allocator.CopyString(SelectorId->getName()));
6498 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006499 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6500 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006501 Builder.AddTextChunk(Key);
6502 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6503 CXCursor_ObjCInstanceMethodDecl));
6504 }
6505 }
6506
6507 // Indexed and unordered accessors
6508 unsigned IndexedGetterPriority = CCP_CodePattern;
6509 unsigned IndexedSetterPriority = CCP_CodePattern;
6510 unsigned UnorderedGetterPriority = CCP_CodePattern;
6511 unsigned UnorderedSetterPriority = CCP_CodePattern;
6512 if (const ObjCObjectPointerType *ObjCPointer
6513 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6514 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6515 // If this interface type is not provably derived from a known
6516 // collection, penalize the corresponding completions.
6517 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6518 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6519 if (!InheritsFromClassNamed(IFace, "NSArray"))
6520 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6521 }
6522
6523 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6524 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6525 if (!InheritsFromClassNamed(IFace, "NSSet"))
6526 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6527 }
6528 }
6529 } else {
6530 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6531 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6532 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6533 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6534 }
6535
6536 // Add -(NSUInteger)countOf<key>
6537 if (IsInstanceMethod &&
6538 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006539 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006540 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006541 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6542 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006543 if (ReturnType.isNull()) {
6544 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6545 Builder.AddTextChunk("NSUInteger");
6546 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6547 }
6548
6549 Builder.AddTypedTextChunk(
6550 Allocator.CopyString(SelectorId->getName()));
6551 Results.AddResult(Result(Builder.TakeString(),
6552 std::min(IndexedGetterPriority,
6553 UnorderedGetterPriority),
6554 CXCursor_ObjCInstanceMethodDecl));
6555 }
6556 }
6557
6558 // Indexed getters
6559 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6560 if (IsInstanceMethod &&
6561 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006562 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006563 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006564 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006565 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006566 if (ReturnType.isNull()) {
6567 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6568 Builder.AddTextChunk("id");
6569 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6570 }
6571
6572 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6573 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6574 Builder.AddTextChunk("NSUInteger");
6575 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6576 Builder.AddTextChunk("index");
6577 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6578 CXCursor_ObjCInstanceMethodDecl));
6579 }
6580 }
6581
6582 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6583 if (IsInstanceMethod &&
6584 (ReturnType.isNull() ||
6585 (ReturnType->isObjCObjectPointerType() &&
6586 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6587 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6588 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006589 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006590 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006591 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006592 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006593 if (ReturnType.isNull()) {
6594 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6595 Builder.AddTextChunk("NSArray *");
6596 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6597 }
6598
6599 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6600 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6601 Builder.AddTextChunk("NSIndexSet *");
6602 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6603 Builder.AddTextChunk("indexes");
6604 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6605 CXCursor_ObjCInstanceMethodDecl));
6606 }
6607 }
6608
6609 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6610 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006611 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006612 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006613 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006614 &Context.Idents.get("range")
6615 };
6616
David Blaikie82e95a32014-11-19 07:49:47 +00006617 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006618 if (ReturnType.isNull()) {
6619 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6620 Builder.AddTextChunk("void");
6621 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6622 }
6623
6624 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6625 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6626 Builder.AddPlaceholderChunk("object-type");
6627 Builder.AddTextChunk(" **");
6628 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6629 Builder.AddTextChunk("buffer");
6630 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6631 Builder.AddTypedTextChunk("range:");
6632 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6633 Builder.AddTextChunk("NSRange");
6634 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6635 Builder.AddTextChunk("inRange");
6636 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6637 CXCursor_ObjCInstanceMethodDecl));
6638 }
6639 }
6640
6641 // Mutable indexed accessors
6642
6643 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6644 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006645 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006646 IdentifierInfo *SelectorIds[2] = {
6647 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006648 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006649 };
6650
David Blaikie82e95a32014-11-19 07:49:47 +00006651 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006652 if (ReturnType.isNull()) {
6653 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6654 Builder.AddTextChunk("void");
6655 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6656 }
6657
6658 Builder.AddTypedTextChunk("insertObject:");
6659 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6660 Builder.AddPlaceholderChunk("object-type");
6661 Builder.AddTextChunk(" *");
6662 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6663 Builder.AddTextChunk("object");
6664 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6665 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6667 Builder.AddPlaceholderChunk("NSUInteger");
6668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6669 Builder.AddTextChunk("index");
6670 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6671 CXCursor_ObjCInstanceMethodDecl));
6672 }
6673 }
6674
6675 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6676 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006677 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006678 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006679 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006680 &Context.Idents.get("atIndexes")
6681 };
6682
David Blaikie82e95a32014-11-19 07:49:47 +00006683 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006684 if (ReturnType.isNull()) {
6685 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6686 Builder.AddTextChunk("void");
6687 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6688 }
6689
6690 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6691 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6692 Builder.AddTextChunk("NSArray *");
6693 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6694 Builder.AddTextChunk("array");
6695 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6696 Builder.AddTypedTextChunk("atIndexes:");
6697 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6698 Builder.AddPlaceholderChunk("NSIndexSet *");
6699 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6700 Builder.AddTextChunk("indexes");
6701 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6702 CXCursor_ObjCInstanceMethodDecl));
6703 }
6704 }
6705
6706 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6707 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006708 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006709 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006710 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006711 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006712 if (ReturnType.isNull()) {
6713 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6714 Builder.AddTextChunk("void");
6715 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6716 }
6717
6718 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6719 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6720 Builder.AddTextChunk("NSUInteger");
6721 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6722 Builder.AddTextChunk("index");
6723 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6724 CXCursor_ObjCInstanceMethodDecl));
6725 }
6726 }
6727
6728 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6729 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006730 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006731 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006732 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006733 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006734 if (ReturnType.isNull()) {
6735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6736 Builder.AddTextChunk("void");
6737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6738 }
6739
6740 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6741 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6742 Builder.AddTextChunk("NSIndexSet *");
6743 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6744 Builder.AddTextChunk("indexes");
6745 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6746 CXCursor_ObjCInstanceMethodDecl));
6747 }
6748 }
6749
6750 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6751 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006752 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006753 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006754 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006755 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006756 &Context.Idents.get("withObject")
6757 };
6758
David Blaikie82e95a32014-11-19 07:49:47 +00006759 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006760 if (ReturnType.isNull()) {
6761 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6762 Builder.AddTextChunk("void");
6763 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6764 }
6765
6766 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6767 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6768 Builder.AddPlaceholderChunk("NSUInteger");
6769 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6770 Builder.AddTextChunk("index");
6771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6772 Builder.AddTypedTextChunk("withObject:");
6773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6774 Builder.AddTextChunk("id");
6775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6776 Builder.AddTextChunk("object");
6777 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6778 CXCursor_ObjCInstanceMethodDecl));
6779 }
6780 }
6781
6782 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6783 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006784 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006785 = (Twine("replace") + UpperKey + "AtIndexes").str();
6786 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006787 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006788 &Context.Idents.get(SelectorName1),
6789 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006790 };
6791
David Blaikie82e95a32014-11-19 07:49:47 +00006792 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006793 if (ReturnType.isNull()) {
6794 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6795 Builder.AddTextChunk("void");
6796 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6797 }
6798
6799 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6800 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6801 Builder.AddPlaceholderChunk("NSIndexSet *");
6802 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6803 Builder.AddTextChunk("indexes");
6804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6805 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6807 Builder.AddTextChunk("NSArray *");
6808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6809 Builder.AddTextChunk("array");
6810 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6811 CXCursor_ObjCInstanceMethodDecl));
6812 }
6813 }
6814
6815 // Unordered getters
6816 // - (NSEnumerator *)enumeratorOfKey
6817 if (IsInstanceMethod &&
6818 (ReturnType.isNull() ||
6819 (ReturnType->isObjCObjectPointerType() &&
6820 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6821 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6822 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006823 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006824 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006825 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6826 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006827 if (ReturnType.isNull()) {
6828 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6829 Builder.AddTextChunk("NSEnumerator *");
6830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6831 }
6832
6833 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6834 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6835 CXCursor_ObjCInstanceMethodDecl));
6836 }
6837 }
6838
6839 // - (type *)memberOfKey:(type *)object
6840 if (IsInstanceMethod &&
6841 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006842 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006843 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006844 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006845 if (ReturnType.isNull()) {
6846 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6847 Builder.AddPlaceholderChunk("object-type");
6848 Builder.AddTextChunk(" *");
6849 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6850 }
6851
6852 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6853 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6854 if (ReturnType.isNull()) {
6855 Builder.AddPlaceholderChunk("object-type");
6856 Builder.AddTextChunk(" *");
6857 } else {
6858 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006859 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006860 Builder.getAllocator()));
6861 }
6862 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6863 Builder.AddTextChunk("object");
6864 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6865 CXCursor_ObjCInstanceMethodDecl));
6866 }
6867 }
6868
6869 // Mutable unordered accessors
6870 // - (void)addKeyObject:(type *)object
6871 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006872 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006873 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006874 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006875 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006876 if (ReturnType.isNull()) {
6877 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6878 Builder.AddTextChunk("void");
6879 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6880 }
6881
6882 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6883 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6884 Builder.AddPlaceholderChunk("object-type");
6885 Builder.AddTextChunk(" *");
6886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6887 Builder.AddTextChunk("object");
6888 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6889 CXCursor_ObjCInstanceMethodDecl));
6890 }
6891 }
6892
6893 // - (void)addKey:(NSSet *)objects
6894 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006895 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006896 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006897 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006898 if (ReturnType.isNull()) {
6899 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6900 Builder.AddTextChunk("void");
6901 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6902 }
6903
6904 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6905 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6906 Builder.AddTextChunk("NSSet *");
6907 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6908 Builder.AddTextChunk("objects");
6909 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6910 CXCursor_ObjCInstanceMethodDecl));
6911 }
6912 }
6913
6914 // - (void)removeKeyObject:(type *)object
6915 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006916 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006917 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006918 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006919 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006920 if (ReturnType.isNull()) {
6921 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6922 Builder.AddTextChunk("void");
6923 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6924 }
6925
6926 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6927 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6928 Builder.AddPlaceholderChunk("object-type");
6929 Builder.AddTextChunk(" *");
6930 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6931 Builder.AddTextChunk("object");
6932 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6933 CXCursor_ObjCInstanceMethodDecl));
6934 }
6935 }
6936
6937 // - (void)removeKey:(NSSet *)objects
6938 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006939 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006940 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006941 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006942 if (ReturnType.isNull()) {
6943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6944 Builder.AddTextChunk("void");
6945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6946 }
6947
6948 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6949 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6950 Builder.AddTextChunk("NSSet *");
6951 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6952 Builder.AddTextChunk("objects");
6953 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6954 CXCursor_ObjCInstanceMethodDecl));
6955 }
6956 }
6957
6958 // - (void)intersectKey:(NSSet *)objects
6959 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006960 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006961 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006962 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006963 if (ReturnType.isNull()) {
6964 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6965 Builder.AddTextChunk("void");
6966 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6967 }
6968
6969 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6970 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6971 Builder.AddTextChunk("NSSet *");
6972 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6973 Builder.AddTextChunk("objects");
6974 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6975 CXCursor_ObjCInstanceMethodDecl));
6976 }
6977 }
6978
6979 // Key-Value Observing
6980 // + (NSSet *)keyPathsForValuesAffectingKey
6981 if (!IsInstanceMethod &&
6982 (ReturnType.isNull() ||
6983 (ReturnType->isObjCObjectPointerType() &&
6984 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6985 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6986 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006987 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006988 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006989 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006990 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6991 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006992 if (ReturnType.isNull()) {
6993 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6994 Builder.AddTextChunk("NSSet *");
6995 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6996 }
6997
6998 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6999 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007000 CXCursor_ObjCClassMethodDecl));
7001 }
7002 }
7003
7004 // + (BOOL)automaticallyNotifiesObserversForKey
7005 if (!IsInstanceMethod &&
7006 (ReturnType.isNull() ||
7007 ReturnType->isIntegerType() ||
7008 ReturnType->isBooleanType())) {
7009 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007010 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007011 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007012 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7013 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007014 if (ReturnType.isNull()) {
7015 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7016 Builder.AddTextChunk("BOOL");
7017 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7018 }
7019
7020 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7021 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7022 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007023 }
7024 }
7025}
7026
Douglas Gregor636a61e2010-04-07 00:21:17 +00007027void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7028 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007029 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007030 // Determine the return type of the method we're declaring, if
7031 // provided.
7032 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007033 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007034 if (CurContext->isObjCContainer()) {
7035 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7036 IDecl = cast<Decl>(OCD);
7037 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007038 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007039 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007040 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007041 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007042 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7043 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007044 IsInImplementation = true;
7045 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007046 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007047 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007048 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007049 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007050 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007051 }
7052
7053 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007054 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007055 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007056 }
7057
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007058 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007059 HandleCodeCompleteResults(this, CodeCompleter,
7060 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007061 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007062 return;
7063 }
7064
7065 // Find all of the methods that we could declare/implement here.
7066 KnownMethodsMap KnownMethods;
7067 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007068 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007069
Douglas Gregor636a61e2010-04-07 00:21:17 +00007070 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007071 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007072 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007073 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007074 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007075 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007076 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007077 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7078 MEnd = KnownMethods.end();
7079 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007080 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007081 CodeCompletionBuilder Builder(Results.getAllocator(),
7082 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007083
7084 // If the result type was not already provided, add it to the
7085 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007086 if (ReturnType.isNull()) {
7087 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7088 AttributedType::stripOuterNullability(ResTy);
7089 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007090 Method->getObjCDeclQualifier(), Context, Policy,
7091 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007092 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007093
7094 Selector Sel = Method->getSelector();
7095
7096 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007097 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007098 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007099
7100 // Add parameters to the pattern.
7101 unsigned I = 0;
7102 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7103 PEnd = Method->param_end();
7104 P != PEnd; (void)++P, ++I) {
7105 // Add the part of the selector name.
7106 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007107 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007108 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7110 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007111 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007112 } else
7113 break;
7114
7115 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007116 QualType ParamType;
7117 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7118 ParamType = (*P)->getType();
7119 else
7120 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007121 ParamType = ParamType.substObjCTypeArgs(Context, {},
7122 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007123 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007124 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007125 (*P)->getObjCDeclQualifier(),
7126 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007127 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007128
7129 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007130 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007131 }
7132
7133 if (Method->isVariadic()) {
7134 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007135 Builder.AddChunk(CodeCompletionString::CK_Comma);
7136 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007137 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007138
Douglas Gregord37c59d2010-05-28 00:57:46 +00007139 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007140 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007141 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7142 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7143 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007144 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007145 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007146 Builder.AddTextChunk("return");
7147 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7148 Builder.AddPlaceholderChunk("expression");
7149 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007150 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007151 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007152
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007153 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7154 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007155 }
7156
Douglas Gregor416b5752010-08-25 01:08:01 +00007157 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007158 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007159 Priority += CCD_InBaseClass;
7160
Douglas Gregor78254c82012-03-27 23:34:16 +00007161 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007162 }
7163
Douglas Gregor669a25a2011-02-17 00:22:45 +00007164 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7165 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007166 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007167 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007168 Containers.push_back(SearchDecl);
7169
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007170 VisitedSelectorSet KnownSelectors;
7171 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7172 MEnd = KnownMethods.end();
7173 M != MEnd; ++M)
7174 KnownSelectors.insert(M->first);
7175
7176
Douglas Gregor669a25a2011-02-17 00:22:45 +00007177 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7178 if (!IFace)
7179 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7180 IFace = Category->getClassInterface();
7181
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007182 if (IFace)
7183 for (auto *Cat : IFace->visible_categories())
7184 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007185
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007186 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007187 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007188 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007189 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007190 }
7191
Douglas Gregor636a61e2010-04-07 00:21:17 +00007192 Results.ExitScope();
7193
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007194 HandleCodeCompleteResults(this, CodeCompleter,
7195 CodeCompletionContext::CCC_Other,
7196 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007197}
Douglas Gregor95887f92010-07-08 23:20:03 +00007198
7199void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7200 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007201 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007202 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007203 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007204 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007205 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007206 if (ExternalSource) {
7207 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7208 I != N; ++I) {
7209 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007210 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007211 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007212
7213 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007214 }
7215 }
7216
7217 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007218 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007219 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007220 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007221 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007222
7223 if (ReturnTy)
7224 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007225
Douglas Gregor95887f92010-07-08 23:20:03 +00007226 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007227 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7228 MEnd = MethodPool.end();
7229 M != MEnd; ++M) {
7230 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7231 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007232 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007233 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007234 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007235 continue;
7236
Douglas Gregor45879692010-07-08 23:37:41 +00007237 if (AtParameterName) {
7238 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007239 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007240 if (NumSelIdents &&
7241 NumSelIdents <= MethList->getMethod()->param_size()) {
7242 ParmVarDecl *Param =
7243 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007244 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007245 CodeCompletionBuilder Builder(Results.getAllocator(),
7246 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007247 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007248 Param->getIdentifier()->getName()));
7249 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007250 }
7251 }
7252
7253 continue;
7254 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007255
Nico Weber2e0c8f72014-12-27 03:58:08 +00007256 Result R(MethList->getMethod(),
7257 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007258 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007259 R.AllParametersAreInformative = false;
7260 R.DeclaringEntity = true;
7261 Results.MaybeAddResult(R, CurContext);
7262 }
7263 }
7264
7265 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007266 HandleCodeCompleteResults(this, CodeCompleter,
7267 CodeCompletionContext::CCC_Other,
7268 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007269}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007270
Douglas Gregorec00a262010-08-24 22:20:20 +00007271void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007272 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007273 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007274 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007275 Results.EnterNewScope();
7276
7277 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007278 CodeCompletionBuilder Builder(Results.getAllocator(),
7279 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007280 Builder.AddTypedTextChunk("if");
7281 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7282 Builder.AddPlaceholderChunk("condition");
7283 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007284
7285 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007286 Builder.AddTypedTextChunk("ifdef");
7287 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7288 Builder.AddPlaceholderChunk("macro");
7289 Results.AddResult(Builder.TakeString());
7290
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007291 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007292 Builder.AddTypedTextChunk("ifndef");
7293 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7294 Builder.AddPlaceholderChunk("macro");
7295 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007296
7297 if (InConditional) {
7298 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007299 Builder.AddTypedTextChunk("elif");
7300 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7301 Builder.AddPlaceholderChunk("condition");
7302 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007303
7304 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007305 Builder.AddTypedTextChunk("else");
7306 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007307
7308 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007309 Builder.AddTypedTextChunk("endif");
7310 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007311 }
7312
7313 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007314 Builder.AddTypedTextChunk("include");
7315 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7316 Builder.AddTextChunk("\"");
7317 Builder.AddPlaceholderChunk("header");
7318 Builder.AddTextChunk("\"");
7319 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007320
7321 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007322 Builder.AddTypedTextChunk("include");
7323 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7324 Builder.AddTextChunk("<");
7325 Builder.AddPlaceholderChunk("header");
7326 Builder.AddTextChunk(">");
7327 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007328
7329 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007330 Builder.AddTypedTextChunk("define");
7331 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7332 Builder.AddPlaceholderChunk("macro");
7333 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007334
7335 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007336 Builder.AddTypedTextChunk("define");
7337 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7338 Builder.AddPlaceholderChunk("macro");
7339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7340 Builder.AddPlaceholderChunk("args");
7341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7342 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007343
7344 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007345 Builder.AddTypedTextChunk("undef");
7346 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7347 Builder.AddPlaceholderChunk("macro");
7348 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007349
7350 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007351 Builder.AddTypedTextChunk("line");
7352 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7353 Builder.AddPlaceholderChunk("number");
7354 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007355
7356 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007357 Builder.AddTypedTextChunk("line");
7358 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7359 Builder.AddPlaceholderChunk("number");
7360 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7361 Builder.AddTextChunk("\"");
7362 Builder.AddPlaceholderChunk("filename");
7363 Builder.AddTextChunk("\"");
7364 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007365
7366 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007367 Builder.AddTypedTextChunk("error");
7368 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7369 Builder.AddPlaceholderChunk("message");
7370 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007371
7372 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007373 Builder.AddTypedTextChunk("pragma");
7374 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7375 Builder.AddPlaceholderChunk("arguments");
7376 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007377
David Blaikiebbafb8a2012-03-11 07:00:24 +00007378 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007379 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007380 Builder.AddTypedTextChunk("import");
7381 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7382 Builder.AddTextChunk("\"");
7383 Builder.AddPlaceholderChunk("header");
7384 Builder.AddTextChunk("\"");
7385 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007386
7387 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007388 Builder.AddTypedTextChunk("import");
7389 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7390 Builder.AddTextChunk("<");
7391 Builder.AddPlaceholderChunk("header");
7392 Builder.AddTextChunk(">");
7393 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007394 }
7395
7396 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007397 Builder.AddTypedTextChunk("include_next");
7398 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7399 Builder.AddTextChunk("\"");
7400 Builder.AddPlaceholderChunk("header");
7401 Builder.AddTextChunk("\"");
7402 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007403
7404 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007405 Builder.AddTypedTextChunk("include_next");
7406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7407 Builder.AddTextChunk("<");
7408 Builder.AddPlaceholderChunk("header");
7409 Builder.AddTextChunk(">");
7410 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007411
7412 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007413 Builder.AddTypedTextChunk("warning");
7414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7415 Builder.AddPlaceholderChunk("message");
7416 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007417
7418 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7419 // completions for them. And __include_macros is a Clang-internal extension
7420 // that we don't want to encourage anyone to use.
7421
7422 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7423 Results.ExitScope();
7424
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007425 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007426 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007427 Results.data(), Results.size());
7428}
7429
7430void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007431 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007432 S->getFnParent()? Sema::PCC_RecoveryInFunction
7433 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007434}
7435
Douglas Gregorec00a262010-08-24 22:20:20 +00007436void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007437 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007438 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007439 IsDefinition? CodeCompletionContext::CCC_MacroName
7440 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007441 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7442 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007443 CodeCompletionBuilder Builder(Results.getAllocator(),
7444 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007445 Results.EnterNewScope();
7446 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7447 MEnd = PP.macro_end();
7448 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007449 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007450 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007451 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7452 CCP_CodePattern,
7453 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007454 }
7455 Results.ExitScope();
7456 } else if (IsDefinition) {
7457 // FIXME: Can we detect when the user just wrote an include guard above?
7458 }
7459
Douglas Gregor0ac41382010-09-23 23:01:17 +00007460 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007461 Results.data(), Results.size());
7462}
7463
Douglas Gregorec00a262010-08-24 22:20:20 +00007464void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007465 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007466 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007467 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007468
7469 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007470 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007471
7472 // defined (<macro>)
7473 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007474 CodeCompletionBuilder Builder(Results.getAllocator(),
7475 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007476 Builder.AddTypedTextChunk("defined");
7477 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7478 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7479 Builder.AddPlaceholderChunk("macro");
7480 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7481 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007482 Results.ExitScope();
7483
7484 HandleCodeCompleteResults(this, CodeCompleter,
7485 CodeCompletionContext::CCC_PreprocessorExpression,
7486 Results.data(), Results.size());
7487}
7488
7489void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7490 IdentifierInfo *Macro,
7491 MacroInfo *MacroInfo,
7492 unsigned Argument) {
7493 // FIXME: In the future, we could provide "overload" results, much like we
7494 // do for function calls.
7495
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007496 // Now just ignore this. There will be another code-completion callback
7497 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007498}
7499
Douglas Gregor11583702010-08-25 17:04:25 +00007500void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007501 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007502 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007503 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007504}
7505
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007506void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007507 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007508 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007509 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7510 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007511 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7512 CodeCompletionDeclConsumer Consumer(Builder,
7513 Context.getTranslationUnitDecl());
7514 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7515 Consumer);
7516 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007517
7518 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007519 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007520
7521 Results.clear();
7522 Results.insert(Results.end(),
7523 Builder.data(), Builder.data() + Builder.size());
7524}