blob: 91a8c619b26c09ec7fba085030609f040d3b5931 [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]).
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000484static bool isReservedName(const IdentifierInfo *Id,
485 bool doubleUnderscoreOnly = false) {
Alp Toker034bbd52014-06-30 01:33:53 +0000486 if (Id->getLength() < 2)
487 return false;
488 const char *Name = Id->getNameStart();
489 return Name[0] == '_' &&
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
491 !doubleUnderscoreOnly));
492}
493
494// Some declarations have reserved names that we don't want to ever show.
495// Filter out names reserved for the implementation if they come from a
496// system header.
497static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
498 const IdentifierInfo *Id = ND->getIdentifier();
499 if (!Id)
500 return false;
501
502 // Ignore reserved names for compiler provided decls.
503 if (isReservedName(Id) && ND->getLocation().isInvalid())
504 return true;
505
506 // For system headers ignore only double-underscore names.
507 // This allows for system headers providing private symbols with a single
508 // underscore.
509 if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
510 SemaRef.SourceMgr.isInSystemHeader(
511 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
512 return true;
513
514 return false;
Alp Toker034bbd52014-06-30 01:33:53 +0000515}
516
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000517bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000518 bool &AsNestedNameSpecifier) const {
519 AsNestedNameSpecifier = false;
520
Richard Smithf2005d32015-12-29 23:34:32 +0000521 auto *Named = ND;
Douglas Gregor7c208612010-01-14 00:20:49 +0000522 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000523
524 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000525 if (!ND->getDeclName())
526 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000527
528 // Friend declarations and declarations introduced due to friends are never
529 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000530 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000531 return false;
532
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000533 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000534 if (isa<ClassTemplateSpecializationDecl>(ND) ||
535 isa<ClassTemplatePartialSpecializationDecl>(ND))
536 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000537
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000538 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000539 if (isa<UsingDecl>(ND))
540 return false;
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000541
542 if (shouldIgnoreDueToReservedName(ND, SemaRef))
543 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000544
Douglas Gregor59cab552010-08-16 23:05:20 +0000545 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
Richard Smithf2005d32015-12-29 23:34:32 +0000546 (isa<NamespaceDecl>(ND) &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000547 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000548 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000549 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000550 AsNestedNameSpecifier = true;
551
Douglas Gregor3545ff42009-09-21 16:56:56 +0000552 // Filter out any unwanted results.
Richard Smithf2005d32015-12-29 23:34:32 +0000553 if (Filter && !(this->*Filter)(Named)) {
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000554 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000555 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000556 IsNestedNameSpecifier(ND) &&
557 (Filter != &ResultBuilder::IsMember ||
558 (isa<CXXRecordDecl>(ND) &&
559 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
560 AsNestedNameSpecifier = true;
561 return true;
562 }
563
Douglas Gregor7c208612010-01-14 00:20:49 +0000564 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000565 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000566 // ... then it must be interesting!
567 return true;
568}
569
Douglas Gregore0717ab2010-01-14 00:41:07 +0000570bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000571 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000572 // In C, there is no way to refer to a hidden name.
573 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
574 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000575 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000576 return true;
577
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000578 const DeclContext *HiddenCtx =
579 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000580
581 // There is no way to qualify a name declared in a function or method.
582 if (HiddenCtx->isFunctionOrMethod())
583 return true;
584
Sebastian Redl50c68252010-08-31 00:36:30 +0000585 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000586 return true;
587
588 // We can refer to the result with the appropriate qualification. Do it.
589 R.Hidden = true;
590 R.QualifierIsInformative = false;
591
592 if (!R.Qualifier)
593 R.Qualifier = getRequiredQualification(SemaRef.Context,
594 CurContext,
595 R.Declaration->getDeclContext());
596 return false;
597}
598
Douglas Gregor95887f92010-07-08 23:20:03 +0000599/// \brief A simplified classification of types used to determine whether two
600/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000601SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000602 switch (T->getTypeClass()) {
603 case Type::Builtin:
604 switch (cast<BuiltinType>(T)->getKind()) {
605 case BuiltinType::Void:
606 return STC_Void;
607
608 case BuiltinType::NullPtr:
609 return STC_Pointer;
610
611 case BuiltinType::Overload:
612 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000613 return STC_Other;
614
615 case BuiltinType::ObjCId:
616 case BuiltinType::ObjCClass:
617 case BuiltinType::ObjCSel:
618 return STC_ObjectiveC;
619
620 default:
621 return STC_Arithmetic;
622 }
David Blaikie8a40f702012-01-17 06:56:22 +0000623
Douglas Gregor95887f92010-07-08 23:20:03 +0000624 case Type::Complex:
625 return STC_Arithmetic;
626
627 case Type::Pointer:
628 return STC_Pointer;
629
630 case Type::BlockPointer:
631 return STC_Block;
632
633 case Type::LValueReference:
634 case Type::RValueReference:
635 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
636
637 case Type::ConstantArray:
638 case Type::IncompleteArray:
639 case Type::VariableArray:
640 case Type::DependentSizedArray:
641 return STC_Array;
642
643 case Type::DependentSizedExtVector:
644 case Type::Vector:
645 case Type::ExtVector:
646 return STC_Arithmetic;
647
648 case Type::FunctionProto:
649 case Type::FunctionNoProto:
650 return STC_Function;
651
652 case Type::Record:
653 return STC_Record;
654
655 case Type::Enum:
656 return STC_Arithmetic;
657
658 case Type::ObjCObject:
659 case Type::ObjCInterface:
660 case Type::ObjCObjectPointer:
661 return STC_ObjectiveC;
662
663 default:
664 return STC_Other;
665 }
666}
667
668/// \brief Get the type that a given expression will have if this declaration
669/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000670QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000671 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
672
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000673 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000674 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000675 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000676 return C.getObjCInterfaceType(Iface);
677
678 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000679 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000680 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000681 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000682 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000683 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000684 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000685 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000686 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000687 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000688 T = Value->getType();
689 else
690 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000691
692 // Dig through references, function pointers, and block pointers to
693 // get down to the likely type of an expression when the entity is
694 // used.
695 do {
696 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
697 T = Ref->getPointeeType();
698 continue;
699 }
700
701 if (const PointerType *Pointer = T->getAs<PointerType>()) {
702 if (Pointer->getPointeeType()->isFunctionType()) {
703 T = Pointer->getPointeeType();
704 continue;
705 }
706
707 break;
708 }
709
710 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
711 T = Block->getPointeeType();
712 continue;
713 }
714
715 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000716 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000717 continue;
718 }
719
720 break;
721 } while (true);
722
723 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000724}
725
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000726unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
727 if (!ND)
728 return CCP_Unlikely;
729
730 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000731 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
732 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000733 // _cmd is relatively rare
734 if (const ImplicitParamDecl *ImplicitParam =
735 dyn_cast<ImplicitParamDecl>(ND))
736 if (ImplicitParam->getIdentifier() &&
737 ImplicitParam->getIdentifier()->isStr("_cmd"))
738 return CCP_ObjC_cmd;
739
740 return CCP_LocalDeclaration;
741 }
Richard Smith541b38b2013-09-20 01:15:31 +0000742
743 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000744 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
745 return CCP_MemberDeclaration;
746
747 // Content-based decisions.
748 if (isa<EnumConstantDecl>(ND))
749 return CCP_Constant;
750
Douglas Gregor52e0de42013-01-31 05:03:46 +0000751 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
752 // message receiver, or parenthesized expression context. There, it's as
753 // likely that the user will want to write a type as other declarations.
754 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
755 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
756 CompletionContext.getKind()
757 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
758 CompletionContext.getKind()
759 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000760 return CCP_Type;
761
762 return CCP_Declaration;
763}
764
Douglas Gregor50832e02010-09-20 22:39:41 +0000765void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
766 // If this is an Objective-C method declaration whose selector matches our
767 // preferred selector, give it a priority boost.
768 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000769 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000770 if (PreferredSelector == Method->getSelector())
771 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000772
Douglas Gregor50832e02010-09-20 22:39:41 +0000773 // If we have a preferred type, adjust the priority for results with exactly-
774 // matching or nearly-matching types.
775 if (!PreferredType.isNull()) {
776 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
777 if (!T.isNull()) {
778 CanQualType TC = SemaRef.Context.getCanonicalType(T);
779 // Check for exactly-matching types (modulo qualifiers).
780 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
781 R.Priority /= CCF_ExactTypeMatch;
782 // Check for nearly-matching types, based on classification of each.
783 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000784 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000785 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
786 R.Priority /= CCF_SimilarTypeMatch;
787 }
788 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000789}
790
Douglas Gregor0212fd72010-09-21 16:06:22 +0000791void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000792 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000793 !CompletionContext.wantConstructorResults())
794 return;
795
796 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000797 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000799 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000800 Record = ClassTemplate->getTemplatedDecl();
801 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
802 // Skip specializations and partial specializations.
803 if (isa<ClassTemplateSpecializationDecl>(Record))
804 return;
805 } else {
806 // There are no constructors here.
807 return;
808 }
809
810 Record = Record->getDefinition();
811 if (!Record)
812 return;
813
814
815 QualType RecordTy = Context.getTypeDeclType(Record);
816 DeclarationName ConstructorName
817 = Context.DeclarationNames.getCXXConstructorName(
818 Context.getCanonicalType(RecordTy));
Richard Smithcf4bdde2015-02-21 02:45:19 +0000819 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
820 for (DeclContext::lookup_iterator I = Ctors.begin(),
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000821 E = Ctors.end();
822 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000823 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000824 R.CursorKind = getCursorKindForDecl(R.Declaration);
825 Results.push_back(R);
826 }
827}
828
Douglas Gregor7c208612010-01-14 00:20:49 +0000829void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
830 assert(!ShadowMaps.empty() && "Must enter into a results scope");
831
832 if (R.Kind != Result::RK_Declaration) {
833 // For non-declaration results, just add the result.
834 Results.push_back(R);
835 return;
836 }
837
838 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000839 if (const UsingShadowDecl *Using =
840 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000841 MaybeAddResult(Result(Using->getTargetDecl(),
842 getBasePriority(Using->getTargetDecl()),
843 R.Qualifier),
844 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000845 return;
846 }
847
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000848 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000849 unsigned IDNS = CanonDecl->getIdentifierNamespace();
850
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000851 bool AsNestedNameSpecifier = false;
852 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000853 return;
854
Douglas Gregor0212fd72010-09-21 16:06:22 +0000855 // C++ constructors are never found by name lookup.
856 if (isa<CXXConstructorDecl>(R.Declaration))
857 return;
858
Douglas Gregor3545ff42009-09-21 16:56:56 +0000859 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000860 ShadowMapEntry::iterator I, IEnd;
861 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
862 if (NamePos != SMap.end()) {
863 I = NamePos->second.begin();
864 IEnd = NamePos->second.end();
865 }
866
867 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000868 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000869 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000870 if (ND->getCanonicalDecl() == CanonDecl) {
871 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000872 Results[Index].Declaration = R.Declaration;
873
Douglas Gregor3545ff42009-09-21 16:56:56 +0000874 // We're done.
875 return;
876 }
877 }
878
879 // This is a new declaration in this scope. However, check whether this
880 // declaration name is hidden by a similarly-named declaration in an outer
881 // scope.
882 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
883 --SMEnd;
884 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000885 ShadowMapEntry::iterator I, IEnd;
886 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
887 if (NamePos != SM->end()) {
888 I = NamePos->second.begin();
889 IEnd = NamePos->second.end();
890 }
891 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000892 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000893 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000894 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
895 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000896 continue;
897
898 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000899 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000900 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000901 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000902 continue;
903
904 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000905 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000906 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000907
908 break;
909 }
910 }
911
912 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000913 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000914 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000915
Douglas Gregore412a5a2009-09-23 22:26:46 +0000916 // If the filter is for nested-name-specifiers, then this result starts a
917 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000918 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000919 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000920 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000921 } else
922 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000923
Douglas Gregor5bf52692009-09-22 23:15:58 +0000924 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000925 if (R.QualifierIsInformative && !R.Qualifier &&
926 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000927 const DeclContext *Ctx = R.Declaration->getDeclContext();
928 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000929 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
930 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000931 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000932 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
933 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000934 else
935 R.QualifierIsInformative = false;
936 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000937
Douglas Gregor3545ff42009-09-21 16:56:56 +0000938 // Insert this result into the set of results and into the current shadow
939 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000940 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000941 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000942
943 if (!AsNestedNameSpecifier)
944 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000945}
946
Douglas Gregorc580c522010-01-14 01:09:38 +0000947void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000948 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000949 if (R.Kind != Result::RK_Declaration) {
950 // For non-declaration results, just add the result.
951 Results.push_back(R);
952 return;
953 }
954
Douglas Gregorc580c522010-01-14 01:09:38 +0000955 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000956 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000957 AddResult(Result(Using->getTargetDecl(),
958 getBasePriority(Using->getTargetDecl()),
959 R.Qualifier),
960 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000961 return;
962 }
963
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000964 bool AsNestedNameSpecifier = false;
965 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000966 return;
967
Douglas Gregor0212fd72010-09-21 16:06:22 +0000968 // C++ constructors are never found by name lookup.
969 if (isa<CXXConstructorDecl>(R.Declaration))
970 return;
971
Douglas Gregorc580c522010-01-14 01:09:38 +0000972 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
973 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000974
Douglas Gregorc580c522010-01-14 01:09:38 +0000975 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000976 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000977 return;
978
979 // If the filter is for nested-name-specifiers, then this result starts a
980 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000981 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000982 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000983 R.Priority = CCP_NestedNameSpecifier;
984 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000985 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
986 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000987 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000988 R.QualifierIsInformative = true;
989
Douglas Gregorc580c522010-01-14 01:09:38 +0000990 // If this result is supposed to have an informative qualifier, add one.
991 if (R.QualifierIsInformative && !R.Qualifier &&
992 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000993 const DeclContext *Ctx = R.Declaration->getDeclContext();
994 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000995 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
996 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000997 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000998 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000999 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +00001000 else
1001 R.QualifierIsInformative = false;
1002 }
1003
Douglas Gregora2db7932010-05-26 22:00:08 +00001004 // Adjust the priority if this result comes from a base class.
1005 if (InBaseClass)
1006 R.Priority += CCD_InBaseClass;
1007
Douglas Gregor50832e02010-09-20 22:39:41 +00001008 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001009
Douglas Gregor9be0ed42010-08-26 16:36:48 +00001010 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001011 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +00001012 if (Method->isInstance()) {
1013 Qualifiers MethodQuals
1014 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1015 if (ObjectTypeQualifiers == MethodQuals)
1016 R.Priority += CCD_ObjectQualifierMatch;
1017 else if (ObjectTypeQualifiers - MethodQuals) {
1018 // The method cannot be invoked, because doing so would drop
1019 // qualifiers.
1020 return;
1021 }
1022 }
1023
Douglas Gregorc580c522010-01-14 01:09:38 +00001024 // Insert this result into the set of results.
1025 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001026
1027 if (!AsNestedNameSpecifier)
1028 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001029}
1030
Douglas Gregor78a21012010-01-14 16:01:26 +00001031void ResultBuilder::AddResult(Result R) {
1032 assert(R.Kind != Result::RK_Declaration &&
1033 "Declaration results need more context");
1034 Results.push_back(R);
1035}
1036
Douglas Gregor3545ff42009-09-21 16:56:56 +00001037/// \brief Enter into a new scope.
Benjamin Kramer3204b152015-05-29 19:42:19 +00001038void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001039
1040/// \brief Exit from the current scope.
1041void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001042 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1043 EEnd = ShadowMaps.back().end();
1044 E != EEnd;
1045 ++E)
1046 E->second.Destroy();
1047
Douglas Gregor3545ff42009-09-21 16:56:56 +00001048 ShadowMaps.pop_back();
1049}
1050
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001051/// \brief Determines whether this given declaration will be found by
1052/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001053bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001054 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1055
Richard Smith541b38b2013-09-20 01:15:31 +00001056 // If name lookup finds a local extern declaration, then we are in a
1057 // context where it behaves like an ordinary name.
1058 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001059 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001060 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001061 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001062 if (isa<ObjCIvarDecl>(ND))
1063 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001064 }
1065
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001066 return ND->getIdentifierNamespace() & IDNS;
1067}
1068
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001069/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001070/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001071bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001072 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1073 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1074 return false;
1075
Richard Smith541b38b2013-09-20 01:15:31 +00001076 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001077 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001078 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001079 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001080 if (isa<ObjCIvarDecl>(ND))
1081 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001082 }
1083
Douglas Gregor70febae2010-05-28 00:49:12 +00001084 return ND->getIdentifierNamespace() & IDNS;
1085}
1086
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001087bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001088 if (!IsOrdinaryNonTypeName(ND))
1089 return 0;
1090
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001091 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001092 if (VD->getType()->isIntegralOrEnumerationType())
1093 return true;
1094
1095 return false;
1096}
1097
Douglas Gregor70febae2010-05-28 00:49:12 +00001098/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001099/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001100bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001101 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1102
Richard Smith541b38b2013-09-20 01:15:31 +00001103 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001104 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001105 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001106
1107 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001108 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1109 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001110}
1111
Douglas Gregor3545ff42009-09-21 16:56:56 +00001112/// \brief Determines whether the given declaration is suitable as the
1113/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001114bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001115 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001116 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001117 ND = ClassTemplate->getTemplatedDecl();
1118
1119 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1120}
1121
1122/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001123bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001124 return isa<EnumDecl>(ND);
1125}
1126
1127/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001128bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001129 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001130 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001131 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001132
1133 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001134 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001135 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001136 RD->getTagKind() == TTK_Struct ||
1137 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001138
1139 return false;
1140}
1141
1142/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001143bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001144 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001145 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001146 ND = ClassTemplate->getTemplatedDecl();
1147
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001148 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001149 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001150
1151 return false;
1152}
1153
1154/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001155bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001156 return isa<NamespaceDecl>(ND);
1157}
1158
1159/// \brief Determines whether the given declaration is a namespace or
1160/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001161bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001162 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001163}
1164
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001165/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001166bool ResultBuilder::IsType(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001167 ND = ND->getUnderlyingDecl();
Douglas Gregor99fa2642010-08-24 01:06:58 +00001168 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001169}
1170
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001171/// \brief Determines which members of a class should be visible via
1172/// "." or "->". Only value declarations, nested name specifiers, and
1173/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001174bool ResultBuilder::IsMember(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001175 ND = ND->getUnderlyingDecl();
Douglas Gregor70788392009-12-11 18:14:22 +00001176 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
Richard Smithf2005d32015-12-29 23:34:32 +00001177 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001178}
1179
Douglas Gregora817a192010-05-27 23:06:34 +00001180static bool isObjCReceiverType(ASTContext &C, QualType T) {
1181 T = C.getCanonicalType(T);
1182 switch (T->getTypeClass()) {
1183 case Type::ObjCObject:
1184 case Type::ObjCInterface:
1185 case Type::ObjCObjectPointer:
1186 return true;
1187
1188 case Type::Builtin:
1189 switch (cast<BuiltinType>(T)->getKind()) {
1190 case BuiltinType::ObjCId:
1191 case BuiltinType::ObjCClass:
1192 case BuiltinType::ObjCSel:
1193 return true;
1194
1195 default:
1196 break;
1197 }
1198 return false;
1199
1200 default:
1201 break;
1202 }
1203
David Blaikiebbafb8a2012-03-11 07:00:24 +00001204 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001205 return false;
1206
1207 // FIXME: We could perform more analysis here to determine whether a
1208 // particular class type has any conversions to Objective-C types. For now,
1209 // just accept all class types.
1210 return T->isDependentType() || T->isRecordType();
1211}
1212
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001213bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001214 QualType T = getDeclUsageType(SemaRef.Context, ND);
1215 if (T.isNull())
1216 return false;
1217
1218 T = SemaRef.Context.getBaseElementType(T);
1219 return isObjCReceiverType(SemaRef.Context, T);
1220}
1221
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001222bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001223 if (IsObjCMessageReceiver(ND))
1224 return true;
1225
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001226 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001227 if (!Var)
1228 return false;
1229
1230 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1231}
1232
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001233bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001234 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1235 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001236 return false;
1237
1238 QualType T = getDeclUsageType(SemaRef.Context, ND);
1239 if (T.isNull())
1240 return false;
1241
1242 T = SemaRef.Context.getBaseElementType(T);
1243 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1244 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001245 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001246}
Douglas Gregora817a192010-05-27 23:06:34 +00001247
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001248bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001249 return false;
1250}
1251
James Dennettf1243872012-06-17 05:33:25 +00001252/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001253/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001254bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001255 return isa<ObjCIvarDecl>(ND);
1256}
1257
Douglas Gregorc580c522010-01-14 01:09:38 +00001258namespace {
1259 /// \brief Visible declaration consumer that adds a code-completion result
1260 /// for each visible declaration.
1261 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1262 ResultBuilder &Results;
1263 DeclContext *CurContext;
1264
1265 public:
1266 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1267 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001268
1269 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1270 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001271 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001272 if (Ctx)
1273 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001274
1275 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1276 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001277 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001278 }
1279 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001280}
Douglas Gregorc580c522010-01-14 01:09:38 +00001281
Douglas Gregor3545ff42009-09-21 16:56:56 +00001282/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001283static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001284 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001285 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001286 Results.AddResult(Result("short", CCP_Type));
1287 Results.AddResult(Result("long", CCP_Type));
1288 Results.AddResult(Result("signed", CCP_Type));
1289 Results.AddResult(Result("unsigned", CCP_Type));
1290 Results.AddResult(Result("void", CCP_Type));
1291 Results.AddResult(Result("char", CCP_Type));
1292 Results.AddResult(Result("int", CCP_Type));
1293 Results.AddResult(Result("float", CCP_Type));
1294 Results.AddResult(Result("double", CCP_Type));
1295 Results.AddResult(Result("enum", CCP_Type));
1296 Results.AddResult(Result("struct", CCP_Type));
1297 Results.AddResult(Result("union", CCP_Type));
1298 Results.AddResult(Result("const", CCP_Type));
1299 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001300
Douglas Gregor3545ff42009-09-21 16:56:56 +00001301 if (LangOpts.C99) {
1302 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001303 Results.AddResult(Result("_Complex", CCP_Type));
1304 Results.AddResult(Result("_Imaginary", CCP_Type));
1305 Results.AddResult(Result("_Bool", CCP_Type));
1306 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001307 }
1308
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001309 CodeCompletionBuilder Builder(Results.getAllocator(),
1310 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001311 if (LangOpts.CPlusPlus) {
1312 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001313 Results.AddResult(Result("bool", CCP_Type +
1314 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001315 Results.AddResult(Result("class", CCP_Type));
1316 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001317
Douglas Gregorf4c33342010-05-28 00:22:41 +00001318 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001319 Builder.AddTypedTextChunk("typename");
1320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1321 Builder.AddPlaceholderChunk("qualifier");
1322 Builder.AddTextChunk("::");
1323 Builder.AddPlaceholderChunk("name");
1324 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001325
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001326 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001327 Results.AddResult(Result("auto", CCP_Type));
1328 Results.AddResult(Result("char16_t", CCP_Type));
1329 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001330
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001331 Builder.AddTypedTextChunk("decltype");
1332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1333 Builder.AddPlaceholderChunk("expression");
1334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1335 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001336 }
Alex Lorenz46eed9d2017-02-13 23:35:59 +00001337 } else
1338 Results.AddResult(Result("__auto_type", CCP_Type));
1339
Douglas Gregor3545ff42009-09-21 16:56:56 +00001340 // GNU extensions
1341 if (LangOpts.GNUMode) {
1342 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001343 // Results.AddResult(Result("_Decimal32"));
1344 // Results.AddResult(Result("_Decimal64"));
1345 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001346
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001347 Builder.AddTypedTextChunk("typeof");
1348 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1349 Builder.AddPlaceholderChunk("expression");
1350 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001351
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001352 Builder.AddTypedTextChunk("typeof");
1353 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1354 Builder.AddPlaceholderChunk("type");
1355 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1356 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001357 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001358
1359 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001360 Results.AddResult(Result("_Nonnull", CCP_Type));
1361 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1362 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001363}
1364
John McCallfaf5fb42010-08-26 23:41:50 +00001365static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001367 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001368 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001369 // Note: we don't suggest either "auto" or "register", because both
1370 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1371 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001372 Results.AddResult(Result("extern"));
1373 Results.AddResult(Result("static"));
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001374
1375 if (LangOpts.CPlusPlus11) {
1376 CodeCompletionAllocator &Allocator = Results.getAllocator();
1377 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1378
1379 // alignas
1380 Builder.AddTypedTextChunk("alignas");
1381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1382 Builder.AddPlaceholderChunk("expression");
1383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1384 Results.AddResult(Result(Builder.TakeString()));
1385
1386 Results.AddResult(Result("constexpr"));
1387 Results.AddResult(Result("thread_local"));
1388 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001389}
1390
John McCallfaf5fb42010-08-26 23:41:50 +00001391static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001392 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001393 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001394 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001395 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001396 case Sema::PCC_Class:
1397 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001398 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001399 Results.AddResult(Result("explicit"));
1400 Results.AddResult(Result("friend"));
1401 Results.AddResult(Result("mutable"));
1402 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001403 }
1404 // Fall through
1405
John McCallfaf5fb42010-08-26 23:41:50 +00001406 case Sema::PCC_ObjCInterface:
1407 case Sema::PCC_ObjCImplementation:
1408 case Sema::PCC_Namespace:
1409 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001410 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001411 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001412 break;
1413
John McCallfaf5fb42010-08-26 23:41:50 +00001414 case Sema::PCC_ObjCInstanceVariableList:
1415 case Sema::PCC_Expression:
1416 case Sema::PCC_Statement:
1417 case Sema::PCC_ForInit:
1418 case Sema::PCC_Condition:
1419 case Sema::PCC_RecoveryInFunction:
1420 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001421 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001422 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001423 break;
1424 }
1425}
1426
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001427static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1428static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1429static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001430 ResultBuilder &Results,
1431 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001432static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001433 ResultBuilder &Results,
1434 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001435static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001436 ResultBuilder &Results,
1437 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001438static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001439
Douglas Gregorf4c33342010-05-28 00:22:41 +00001440static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001441 CodeCompletionBuilder Builder(Results.getAllocator(),
1442 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001443 Builder.AddTypedTextChunk("typedef");
1444 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1445 Builder.AddPlaceholderChunk("type");
1446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1447 Builder.AddPlaceholderChunk("name");
1448 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001449}
1450
John McCallfaf5fb42010-08-26 23:41:50 +00001451static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001452 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001453 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001454 case Sema::PCC_Namespace:
1455 case Sema::PCC_Class:
1456 case Sema::PCC_ObjCInstanceVariableList:
1457 case Sema::PCC_Template:
1458 case Sema::PCC_MemberTemplate:
1459 case Sema::PCC_Statement:
1460 case Sema::PCC_RecoveryInFunction:
1461 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001462 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001463 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001464 return true;
1465
John McCallfaf5fb42010-08-26 23:41:50 +00001466 case Sema::PCC_Expression:
1467 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001468 return LangOpts.CPlusPlus;
1469
1470 case Sema::PCC_ObjCInterface:
1471 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001472 return false;
1473
John McCallfaf5fb42010-08-26 23:41:50 +00001474 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001475 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001476 }
David Blaikie8a40f702012-01-17 06:56:22 +00001477
1478 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001479}
1480
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001481static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1482 const Preprocessor &PP) {
1483 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001484 Policy.AnonymousTagLocations = false;
1485 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001486 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001487 return Policy;
1488}
1489
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001490/// \brief Retrieve a printing policy suitable for code completion.
1491static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1492 return getCompletionPrintingPolicy(S.Context, S.PP);
1493}
1494
Douglas Gregore5c79d52011-10-18 21:20:17 +00001495/// \brief Retrieve the string representation of the given type as a string
1496/// that has the appropriate lifetime for code completion.
1497///
1498/// This routine provides a fast path where we provide constant strings for
1499/// common type names.
1500static const char *GetCompletionTypeString(QualType T,
1501 ASTContext &Context,
1502 const PrintingPolicy &Policy,
1503 CodeCompletionAllocator &Allocator) {
1504 if (!T.getLocalQualifiers()) {
1505 // Built-in type names are constant strings.
1506 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001507 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001508
1509 // Anonymous tag types are constant strings.
1510 if (const TagType *TagT = dyn_cast<TagType>(T))
1511 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001512 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001513 switch (Tag->getTagKind()) {
1514 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001515 case TTK_Interface: return "__interface <anonymous>";
1516 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001517 case TTK_Union: return "union <anonymous>";
1518 case TTK_Enum: return "enum <anonymous>";
1519 }
1520 }
1521 }
1522
1523 // Slow path: format the type as a string.
1524 std::string Result;
1525 T.getAsStringInternal(Result, Policy);
1526 return Allocator.CopyString(Result);
1527}
1528
Douglas Gregord8c61782012-02-15 15:34:24 +00001529/// \brief Add a completion for "this", if we're in a member function.
1530static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1531 QualType ThisTy = S.getCurrentThisType();
1532 if (ThisTy.isNull())
1533 return;
1534
1535 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001536 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001537 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1538 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1539 S.Context,
1540 Policy,
1541 Allocator));
1542 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001543 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001544}
1545
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001546static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1547 ResultBuilder &Results,
1548 const LangOptions &LangOpts) {
1549 if (!LangOpts.CPlusPlus11)
1550 return;
1551
1552 Builder.AddTypedTextChunk("static_assert");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1554 Builder.AddPlaceholderChunk("expression");
1555 Builder.AddChunk(CodeCompletionString::CK_Comma);
1556 Builder.AddPlaceholderChunk("message");
1557 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1558 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1559}
1560
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001561/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001562static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001563 Scope *S,
1564 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001565 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001566 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001567 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001568
John McCall276321a2010-08-25 06:19:51 +00001569 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001570 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001571 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001572 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001573 if (Results.includeCodePatterns()) {
1574 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("namespace");
1576 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1577 Builder.AddPlaceholderChunk("identifier");
1578 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1579 Builder.AddPlaceholderChunk("declarations");
1580 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1581 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1582 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001583 }
1584
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001585 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001586 Builder.AddTypedTextChunk("namespace");
1587 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1588 Builder.AddPlaceholderChunk("name");
1589 Builder.AddChunk(CodeCompletionString::CK_Equal);
1590 Builder.AddPlaceholderChunk("namespace");
1591 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001592
1593 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001594 Builder.AddTypedTextChunk("using");
1595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1596 Builder.AddTextChunk("namespace");
1597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1598 Builder.AddPlaceholderChunk("identifier");
1599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001600
1601 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001602 Builder.AddTypedTextChunk("asm");
1603 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1604 Builder.AddPlaceholderChunk("string-literal");
1605 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001607
Douglas Gregorf4c33342010-05-28 00:22:41 +00001608 if (Results.includeCodePatterns()) {
1609 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001610 Builder.AddTypedTextChunk("template");
1611 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1612 Builder.AddPlaceholderChunk("declaration");
1613 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001614 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001615 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001616
David Blaikiebbafb8a2012-03-11 07:00:24 +00001617 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001618 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001619
Douglas Gregorf4c33342010-05-28 00:22:41 +00001620 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001621 // Fall through
1622
John McCallfaf5fb42010-08-26 23:41:50 +00001623 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001624 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001625 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001626 Builder.AddTypedTextChunk("using");
1627 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1628 Builder.AddPlaceholderChunk("qualifier");
1629 Builder.AddTextChunk("::");
1630 Builder.AddPlaceholderChunk("name");
1631 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632
Douglas Gregorf4c33342010-05-28 00:22:41 +00001633 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001634 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("using");
1636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1637 Builder.AddTextChunk("typename");
1638 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1639 Builder.AddPlaceholderChunk("qualifier");
1640 Builder.AddTextChunk("::");
1641 Builder.AddPlaceholderChunk("name");
1642 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001643 }
1644
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001645 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1646
John McCallfaf5fb42010-08-26 23:41:50 +00001647 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001648 AddTypedefResult(Results);
1649
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001650 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001651 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001652 if (Results.includeCodePatterns())
1653 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001654 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001655
1656 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001657 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001658 if (Results.includeCodePatterns())
1659 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001660 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001661
1662 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001663 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001664 if (Results.includeCodePatterns())
1665 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001666 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001667 }
1668 }
1669 // Fall through
1670
John McCallfaf5fb42010-08-26 23:41:50 +00001671 case Sema::PCC_Template:
1672 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001675 Builder.AddTypedTextChunk("template");
1676 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1677 Builder.AddPlaceholderChunk("parameters");
1678 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1679 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001680 }
1681
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1683 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001684 break;
1685
John McCallfaf5fb42010-08-26 23:41:50 +00001686 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001687 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1688 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1689 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001690 break;
1691
John McCallfaf5fb42010-08-26 23:41:50 +00001692 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001693 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1694 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1695 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001696 break;
1697
John McCallfaf5fb42010-08-26 23:41:50 +00001698 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001699 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001700 break;
1701
John McCallfaf5fb42010-08-26 23:41:50 +00001702 case Sema::PCC_RecoveryInFunction:
1703 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001704 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001705
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1707 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001708 Builder.AddTypedTextChunk("try");
1709 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1710 Builder.AddPlaceholderChunk("statements");
1711 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1712 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1713 Builder.AddTextChunk("catch");
1714 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1715 Builder.AddPlaceholderChunk("declaration");
1716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1717 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1718 Builder.AddPlaceholderChunk("statements");
1719 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1720 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1721 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001722 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001723 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001724 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001725
Douglas Gregorf64acca2010-05-25 21:41:55 +00001726 if (Results.includeCodePatterns()) {
1727 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001728 Builder.AddTypedTextChunk("if");
1729 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001730 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001731 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001732 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001733 Builder.AddPlaceholderChunk("expression");
1734 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1736 Builder.AddPlaceholderChunk("statements");
1737 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1738 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1739 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001740
Douglas Gregorf64acca2010-05-25 21:41:55 +00001741 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001742 Builder.AddTypedTextChunk("switch");
1743 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001744 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001745 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001746 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001747 Builder.AddPlaceholderChunk("expression");
1748 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1749 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1750 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1751 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1752 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001753 }
1754
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001755 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001756 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001757 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001758 Builder.AddTypedTextChunk("case");
1759 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1760 Builder.AddPlaceholderChunk("expression");
1761 Builder.AddChunk(CodeCompletionString::CK_Colon);
1762 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001763
1764 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001765 Builder.AddTypedTextChunk("default");
1766 Builder.AddChunk(CodeCompletionString::CK_Colon);
1767 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768 }
1769
Douglas Gregorf64acca2010-05-25 21:41:55 +00001770 if (Results.includeCodePatterns()) {
1771 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001772 Builder.AddTypedTextChunk("while");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001774 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001775 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001776 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001777 Builder.AddPlaceholderChunk("expression");
1778 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1779 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1780 Builder.AddPlaceholderChunk("statements");
1781 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1782 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1783 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001784
1785 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001786 Builder.AddTypedTextChunk("do");
1787 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1788 Builder.AddPlaceholderChunk("statements");
1789 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1790 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1791 Builder.AddTextChunk("while");
1792 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1793 Builder.AddPlaceholderChunk("expression");
1794 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1795 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001796
Douglas Gregorf64acca2010-05-25 21:41:55 +00001797 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001798 Builder.AddTypedTextChunk("for");
1799 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001800 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001801 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001802 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001803 Builder.AddPlaceholderChunk("init-expression");
1804 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1805 Builder.AddPlaceholderChunk("condition");
1806 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1807 Builder.AddPlaceholderChunk("inc-expression");
1808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1809 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1810 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1811 Builder.AddPlaceholderChunk("statements");
1812 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1813 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1814 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001815 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001816
1817 if (S->getContinueParent()) {
1818 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001819 Builder.AddTypedTextChunk("continue");
1820 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001821 }
1822
1823 if (S->getBreakParent()) {
1824 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001825 Builder.AddTypedTextChunk("break");
1826 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001827 }
1828
1829 // "return expression ;" or "return ;", depending on whether we
1830 // know the function is void or not.
1831 bool isVoid = false;
1832 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001833 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001834 else if (ObjCMethodDecl *Method
1835 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001836 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001837 else if (SemaRef.getCurBlock() &&
1838 !SemaRef.getCurBlock()->ReturnType.isNull())
1839 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001840 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001841 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1843 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001844 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001845 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001846
Douglas Gregorf4c33342010-05-28 00:22:41 +00001847 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001848 Builder.AddTypedTextChunk("goto");
1849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1850 Builder.AddPlaceholderChunk("label");
1851 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001852
Douglas Gregorf4c33342010-05-28 00:22:41 +00001853 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001854 Builder.AddTypedTextChunk("using");
1855 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1856 Builder.AddTextChunk("namespace");
1857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1858 Builder.AddPlaceholderChunk("identifier");
1859 Results.AddResult(Result(Builder.TakeString()));
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001860
1861 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001862 }
Galina Kistanovabe3ba9da2017-06-07 06:31:55 +00001863 LLVM_FALLTHROUGH;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001864
1865 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001866 case Sema::PCC_ForInit:
1867 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001868 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001869 // Fall through: conditions and statements can have expressions.
Galina Kistanova33399112017-06-03 06:35:06 +00001870 LLVM_FALLTHROUGH;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001871
Douglas Gregor5e35d592010-09-14 23:59:36 +00001872 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001873 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001874 CCC == Sema::PCC_ParenthesizedExpression) {
1875 // (__bridge <type>)<expression>
1876 Builder.AddTypedTextChunk("__bridge");
1877 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1878 Builder.AddPlaceholderChunk("type");
1879 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1880 Builder.AddPlaceholderChunk("expression");
1881 Results.AddResult(Result(Builder.TakeString()));
1882
1883 // (__bridge_transfer <Objective-C type>)<expression>
1884 Builder.AddTypedTextChunk("__bridge_transfer");
1885 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1886 Builder.AddPlaceholderChunk("Objective-C type");
1887 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1888 Builder.AddPlaceholderChunk("expression");
1889 Results.AddResult(Result(Builder.TakeString()));
1890
1891 // (__bridge_retained <CF type>)<expression>
1892 Builder.AddTypedTextChunk("__bridge_retained");
1893 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1894 Builder.AddPlaceholderChunk("CF type");
1895 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1896 Builder.AddPlaceholderChunk("expression");
1897 Results.AddResult(Result(Builder.TakeString()));
1898 }
1899 // Fall through
Galina Kistanova33399112017-06-03 06:35:06 +00001900 LLVM_FALLTHROUGH;
John McCall31168b02011-06-15 23:02:42 +00001901
John McCallfaf5fb42010-08-26 23:41:50 +00001902 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001903 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001904 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001905 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001906
Douglas Gregore5c79d52011-10-18 21:20:17 +00001907 // true
1908 Builder.AddResultTypeChunk("bool");
1909 Builder.AddTypedTextChunk("true");
1910 Results.AddResult(Result(Builder.TakeString()));
1911
1912 // false
1913 Builder.AddResultTypeChunk("bool");
1914 Builder.AddTypedTextChunk("false");
1915 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001916
David Blaikiebbafb8a2012-03-11 07:00:24 +00001917 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001918 // dynamic_cast < type-id > ( expression )
1919 Builder.AddTypedTextChunk("dynamic_cast");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1921 Builder.AddPlaceholderChunk("type");
1922 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1924 Builder.AddPlaceholderChunk("expression");
1925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1926 Results.AddResult(Result(Builder.TakeString()));
1927 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001928
1929 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001930 Builder.AddTypedTextChunk("static_cast");
1931 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1932 Builder.AddPlaceholderChunk("type");
1933 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935 Builder.AddPlaceholderChunk("expression");
1936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001938
Douglas Gregorf4c33342010-05-28 00:22:41 +00001939 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001940 Builder.AddTypedTextChunk("reinterpret_cast");
1941 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1942 Builder.AddPlaceholderChunk("type");
1943 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1944 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1945 Builder.AddPlaceholderChunk("expression");
1946 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1947 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001948
Douglas Gregorf4c33342010-05-28 00:22:41 +00001949 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001950 Builder.AddTypedTextChunk("const_cast");
1951 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1952 Builder.AddPlaceholderChunk("type");
1953 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1954 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1955 Builder.AddPlaceholderChunk("expression");
1956 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1957 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001958
David Blaikiebbafb8a2012-03-11 07:00:24 +00001959 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001960 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001961 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001962 Builder.AddTypedTextChunk("typeid");
1963 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1964 Builder.AddPlaceholderChunk("expression-or-type");
1965 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1966 Results.AddResult(Result(Builder.TakeString()));
1967 }
1968
Douglas Gregorf4c33342010-05-28 00:22:41 +00001969 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001970 Builder.AddTypedTextChunk("new");
1971 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1972 Builder.AddPlaceholderChunk("type");
1973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1974 Builder.AddPlaceholderChunk("expressions");
1975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1976 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001977
Douglas Gregorf4c33342010-05-28 00:22:41 +00001978 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001979 Builder.AddTypedTextChunk("new");
1980 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1981 Builder.AddPlaceholderChunk("type");
1982 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1983 Builder.AddPlaceholderChunk("size");
1984 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986 Builder.AddPlaceholderChunk("expressions");
1987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001989
Douglas Gregorf4c33342010-05-28 00:22:41 +00001990 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001991 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001992 Builder.AddTypedTextChunk("delete");
1993 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994 Builder.AddPlaceholderChunk("expression");
1995 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001996
Douglas Gregorf4c33342010-05-28 00:22:41 +00001997 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001998 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001999 Builder.AddTypedTextChunk("delete");
2000 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2001 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2002 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2003 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2004 Builder.AddPlaceholderChunk("expression");
2005 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002006
David Blaikiebbafb8a2012-03-11 07:00:24 +00002007 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00002008 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002009 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00002010 Builder.AddTypedTextChunk("throw");
2011 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2012 Builder.AddPlaceholderChunk("expression");
2013 Results.AddResult(Result(Builder.TakeString()));
2014 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00002015
Douglas Gregora2db7932010-05-26 22:00:08 +00002016 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00002017
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002018 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00002019 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00002020 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002021 Builder.AddTypedTextChunk("nullptr");
2022 Results.AddResult(Result(Builder.TakeString()));
2023
2024 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00002025 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002026 Builder.AddTypedTextChunk("alignof");
2027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2028 Builder.AddPlaceholderChunk("type");
2029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2030 Results.AddResult(Result(Builder.TakeString()));
2031
2032 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00002033 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002034 Builder.AddTypedTextChunk("noexcept");
2035 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2036 Builder.AddPlaceholderChunk("expression");
2037 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2038 Results.AddResult(Result(Builder.TakeString()));
2039
2040 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002041 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002042 Builder.AddTypedTextChunk("sizeof...");
2043 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2044 Builder.AddPlaceholderChunk("parameter-pack");
2045 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2046 Results.AddResult(Result(Builder.TakeString()));
2047 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002048 }
2049
David Blaikiebbafb8a2012-03-11 07:00:24 +00002050 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002051 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00002052 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2053 // The interface can be NULL.
2054 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002055 if (ID->getSuperClass()) {
2056 std::string SuperType;
2057 SuperType = ID->getSuperClass()->getNameAsString();
2058 if (Method->isInstanceMethod())
2059 SuperType += " *";
2060
2061 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2062 Builder.AddTypedTextChunk("super");
2063 Results.AddResult(Result(Builder.TakeString()));
2064 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002065 }
2066
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002067 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002068 }
2069
Jordan Rose58d54722012-06-30 21:33:57 +00002070 if (SemaRef.getLangOpts().C11) {
2071 // _Alignof
2072 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002073 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002074 Builder.AddTypedTextChunk("alignof");
2075 else
2076 Builder.AddTypedTextChunk("_Alignof");
2077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2078 Builder.AddPlaceholderChunk("type");
2079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2080 Results.AddResult(Result(Builder.TakeString()));
2081 }
2082
Douglas Gregorf4c33342010-05-28 00:22:41 +00002083 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002084 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002085 Builder.AddTypedTextChunk("sizeof");
2086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2087 Builder.AddPlaceholderChunk("expression-or-type");
2088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2089 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002090 break;
2091 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002092
John McCallfaf5fb42010-08-26 23:41:50 +00002093 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002094 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002095 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002096 }
2097
David Blaikiebbafb8a2012-03-11 07:00:24 +00002098 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2099 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002100
David Blaikiebbafb8a2012-03-11 07:00:24 +00002101 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002102 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002103}
2104
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002105/// \brief If the given declaration has an associated type, add it as a result
2106/// type chunk.
2107static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002108 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002109 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002110 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002111 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002112 if (!ND)
2113 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002114
2115 // Skip constructors and conversion functions, which have their return types
2116 // built into their names.
2117 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2118 return;
2119
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002120 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002121 QualType T;
2122 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002123 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002124 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2125 if (!BaseType.isNull())
2126 T = Method->getSendResultType(BaseType);
2127 else
2128 T = Method->getReturnType();
2129 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002130 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2131 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2132 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002133 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2134 if (!BaseType.isNull())
2135 T = Ivar->getUsageType(BaseType);
2136 else
2137 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002138 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002139 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002140 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2141 if (!BaseType.isNull())
2142 T = Property->getUsageType(BaseType);
2143 else
2144 T = Property->getType();
2145 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002146
2147 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2148 return;
2149
Douglas Gregor75acd922011-09-27 23:30:47 +00002150 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002151 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002152}
2153
Richard Smith20e883e2015-04-29 23:20:19 +00002154static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002155 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002156 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002157 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2158 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002159 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002160 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002161 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002162 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002163 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002164 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002165 }
2166}
2167
Douglas Gregor86b42682015-06-19 18:27:52 +00002168static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2169 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002170 std::string Result;
2171 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002172 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002173 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002174 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002175 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002176 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002177 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002178 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002179 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002180 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002181 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002182 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002183 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2184 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2185 switch (*nullability) {
2186 case NullabilityKind::NonNull:
2187 Result += "nonnull ";
2188 break;
2189
2190 case NullabilityKind::Nullable:
2191 Result += "nullable ";
2192 break;
2193
2194 case NullabilityKind::Unspecified:
2195 Result += "null_unspecified ";
2196 break;
2197 }
2198 }
2199 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002200 return Result;
2201}
2202
Alex Lorenza1951202016-10-18 10:35:27 +00002203/// \brief Tries to find the most appropriate type location for an Objective-C
2204/// block placeholder.
2205///
2206/// This function ignores things like typedefs and qualifiers in order to
2207/// present the most relevant and accurate block placeholders in code completion
2208/// results.
2209static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2210 FunctionTypeLoc &Block,
2211 FunctionProtoTypeLoc &BlockProto,
2212 bool SuppressBlock = false) {
2213 if (!TSInfo)
2214 return;
2215 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2216 while (true) {
2217 // Look through typedefs.
2218 if (!SuppressBlock) {
2219 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2220 if (TypeSourceInfo *InnerTSInfo =
2221 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2222 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2223 continue;
2224 }
2225 }
2226
2227 // Look through qualified types
2228 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2229 TL = QualifiedTL.getUnqualifiedLoc();
2230 continue;
2231 }
2232
2233 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2234 TL = AttrTL.getModifiedLoc();
2235 continue;
2236 }
2237 }
2238
2239 // Try to get the function prototype behind the block pointer type,
2240 // then we're done.
2241 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2242 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2243 Block = TL.getAs<FunctionTypeLoc>();
2244 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2245 }
2246 break;
2247 }
2248}
2249
Alex Lorenz920ae142016-10-18 10:38:58 +00002250static std::string
2251formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2252 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002253 bool SuppressBlockName = false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002254 bool SuppressBlock = false,
2255 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2256
Richard Smith20e883e2015-04-29 23:20:19 +00002257static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002258 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002259 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002260 bool SuppressBlock = false,
2261 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002262 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2263 if (Param->getType()->isDependentType() ||
2264 !Param->getType()->isBlockPointerType()) {
2265 // The argument for a dependent or non-block parameter is a placeholder
2266 // containing that parameter's type.
2267 std::string Result;
2268
Douglas Gregor981a0c42010-08-29 19:47:46 +00002269 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002270 Result = Param->getIdentifier()->getName();
2271
Douglas Gregor86b42682015-06-19 18:27:52 +00002272 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002273 if (ObjCSubsts)
2274 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2275 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002276 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002277 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2278 Type);
2279 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002280 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002281 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002282 } else {
2283 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002284 }
2285 return Result;
2286 }
Alex Lorenza1951202016-10-18 10:35:27 +00002287
Douglas Gregore90dd002010-08-24 16:15:59 +00002288 // The argument for a block pointer parameter is a block literal with
2289 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002290 FunctionTypeLoc Block;
2291 FunctionProtoTypeLoc BlockProto;
Alex Lorenza1951202016-10-18 10:35:27 +00002292 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2293 SuppressBlock);
Alex Lorenz6bf4a582017-03-13 15:43:42 +00002294 // Try to retrieve the block type information from the property if this is a
2295 // parameter in a setter.
2296 if (!Block && ObjCMethodParam &&
2297 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2298 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2299 ->findPropertyDecl(/*CheckOverrides=*/false))
2300 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2301 SuppressBlock);
2302 }
Douglas Gregore90dd002010-08-24 16:15:59 +00002303
2304 if (!Block) {
2305 // We were unable to find a FunctionProtoTypeLoc with parameter names
2306 // for the block; just use the parameter type as a placeholder.
2307 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002308 if (!ObjCMethodParam && Param->getIdentifier())
2309 Result = Param->getIdentifier()->getName();
2310
Douglas Gregor86b42682015-06-19 18:27:52 +00002311 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002312
2313 if (ObjCMethodParam) {
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002314 Result = Type.getAsString(Policy);
2315 std::string Quals =
2316 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2317 if (!Quals.empty())
2318 Result = "(" + Quals + " " + Result + ")";
2319 if (Result.back() != ')')
2320 Result += " ";
Douglas Gregore90dd002010-08-24 16:15:59 +00002321 if (Param->getIdentifier())
2322 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002323 } else {
2324 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002325 }
2326
2327 return Result;
2328 }
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002329
Douglas Gregore90dd002010-08-24 16:15:59 +00002330 // We have the function prototype behind the block pointer type, as it was
2331 // written in the source.
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002332 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2333 /*SuppressBlockName=*/false, SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002334 ObjCSubsts);
2335}
2336
2337/// \brief Returns a placeholder string that corresponds to an Objective-C block
2338/// declaration.
2339///
2340/// \param BlockDecl A declaration with an Objective-C block type.
2341///
2342/// \param Block The most relevant type location for that block type.
2343///
2344/// \param SuppressBlockName Determines wether or not the name of the block
2345/// declaration is included in the resulting string.
2346static std::string
2347formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2348 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002349 bool SuppressBlockName, bool SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002350 Optional<ArrayRef<QualType>> ObjCSubsts) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002351 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002352 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002353 if (ObjCSubsts)
Alex Lorenz920ae142016-10-18 10:38:58 +00002354 ResultType =
2355 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2356 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002357 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002358 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002359
2360 // Format the parameter list.
2361 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002362 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002363 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002364 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002365 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002366 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002367 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002368 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002369 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002370 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002371 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002372 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002373 /*SuppressName=*/false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002374 /*SuppressBlock=*/true, ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002375
David Blaikie6adc78e2013-02-18 22:06:02 +00002376 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002377 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002378 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002379 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002380 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002381
Douglas Gregord793e7c2011-10-18 04:23:19 +00002382 if (SuppressBlock) {
2383 // Format as a parameter.
2384 Result = Result + " (^";
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002385 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002386 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002387 Result += ")";
2388 Result += Params;
2389 } else {
2390 // Format as a block literal argument.
2391 Result = '^' + Result;
2392 Result += Params;
Alex Lorenz920ae142016-10-18 10:38:58 +00002393
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002394 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002395 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002396 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002397
Douglas Gregore90dd002010-08-24 16:15:59 +00002398 return Result;
2399}
2400
Erik Verbruggen11338c52017-07-19 10:45:40 +00002401static std::string GetDefaultValueString(const ParmVarDecl *Param,
2402 const SourceManager &SM,
2403 const LangOptions &LangOpts) {
2404 const Expr *defaultArg = Param->getDefaultArg();
2405 if (!defaultArg)
2406 return "";
2407 const SourceRange SrcRange = defaultArg->getSourceRange();
2408 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2409 bool Invalid = CharSrcRange.isInvalid();
2410 if (Invalid)
2411 return "";
2412 StringRef srcText = Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2413 if (Invalid)
2414 return "";
2415
2416 if (srcText.empty() || srcText == "=") {
2417 // Lexer can't determine the value.
2418 // This happens if the code is incorrect (for example class is forward declared).
2419 return "";
2420 }
Erik Verbruggen797980e2017-07-19 11:15:36 +00002421 std::string DefValue(srcText.str());
Erik Verbruggen11338c52017-07-19 10:45:40 +00002422 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2423 // this value always has (or always does not have) '=' in front of it
2424 if (DefValue.at(0) != '=') {
2425 // If we don't have '=' in front of value.
2426 // Lexer returns built-in types values without '=' and user-defined types values with it.
2427 return " = " + DefValue;
2428 }
2429 return " " + DefValue;
2430}
2431
Douglas Gregor3545ff42009-09-21 16:56:56 +00002432/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002433static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002434 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002435 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002436 CodeCompletionBuilder &Result,
2437 unsigned Start = 0,
2438 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002439 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002440
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002441 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002442 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002443
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002444 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002445 // When we see an optional default argument, put that argument and
2446 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002447 CodeCompletionBuilder Opt(Result.getAllocator(),
2448 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002449 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002450 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002451 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002452 Result.AddOptionalChunk(Opt.TakeString());
2453 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002454 }
2455
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002456 if (FirstParameter)
2457 FirstParameter = false;
2458 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002459 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002460
2461 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002462
2463 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002464 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
Erik Verbruggen11338c52017-07-19 10:45:40 +00002465 if (Param->hasDefaultArg())
2466 PlaceholderStr += GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
Richard Smith20e883e2015-04-29 23:20:19 +00002467
Douglas Gregor400f5972010-08-31 05:13:43 +00002468 if (Function->isVariadic() && P == N - 1)
2469 PlaceholderStr += ", ...";
2470
Douglas Gregor3545ff42009-09-21 16:56:56 +00002471 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002472 Result.AddPlaceholderChunk(
2473 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002474 }
Douglas Gregorba449032009-09-22 21:42:17 +00002475
2476 if (const FunctionProtoType *Proto
2477 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002478 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002479 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002480 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002481
Richard Smith20e883e2015-04-29 23:20:19 +00002482 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002483 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002484}
2485
2486/// \brief Add template parameter chunks to the given code completion string.
2487static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002488 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002489 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002490 CodeCompletionBuilder &Result,
2491 unsigned MaxParameters = 0,
2492 unsigned Start = 0,
2493 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002494 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002495
2496 // Prefer to take the template parameter names from the first declaration of
2497 // the template.
2498 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2499
Douglas Gregor3545ff42009-09-21 16:56:56 +00002500 TemplateParameterList *Params = Template->getTemplateParameters();
2501 TemplateParameterList::iterator PEnd = Params->end();
2502 if (MaxParameters)
2503 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002504 for (TemplateParameterList::iterator P = Params->begin() + Start;
2505 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002506 bool HasDefaultArg = false;
2507 std::string PlaceholderStr;
2508 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2509 if (TTP->wasDeclaredWithTypename())
2510 PlaceholderStr = "typename";
2511 else
2512 PlaceholderStr = "class";
2513
2514 if (TTP->getIdentifier()) {
2515 PlaceholderStr += ' ';
2516 PlaceholderStr += TTP->getIdentifier()->getName();
2517 }
2518
2519 HasDefaultArg = TTP->hasDefaultArgument();
2520 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002521 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002522 if (NTTP->getIdentifier())
2523 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002524 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002525 HasDefaultArg = NTTP->hasDefaultArgument();
2526 } else {
2527 assert(isa<TemplateTemplateParmDecl>(*P));
2528 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2529
2530 // Since putting the template argument list into the placeholder would
2531 // be very, very long, we just use an abbreviation.
2532 PlaceholderStr = "template<...> class";
2533 if (TTP->getIdentifier()) {
2534 PlaceholderStr += ' ';
2535 PlaceholderStr += TTP->getIdentifier()->getName();
2536 }
2537
2538 HasDefaultArg = TTP->hasDefaultArgument();
2539 }
2540
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002541 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002542 // When we see an optional default argument, put that argument and
2543 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002544 CodeCompletionBuilder Opt(Result.getAllocator(),
2545 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002546 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002547 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002548 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002549 P - Params->begin(), true);
2550 Result.AddOptionalChunk(Opt.TakeString());
2551 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002552 }
2553
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002554 InDefaultArg = false;
2555
Douglas Gregor3545ff42009-09-21 16:56:56 +00002556 if (FirstParameter)
2557 FirstParameter = false;
2558 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002559 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002560
2561 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002562 Result.AddPlaceholderChunk(
2563 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002564 }
2565}
2566
Douglas Gregorf2510672009-09-21 19:57:38 +00002567/// \brief Add a qualifier to the given code-completion string, if the
2568/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002569static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002570AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002571 NestedNameSpecifier *Qualifier,
2572 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002573 ASTContext &Context,
2574 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002575 if (!Qualifier)
2576 return;
2577
2578 std::string PrintedNNS;
2579 {
2580 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002581 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002582 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002583 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002584 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002585 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002586 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002587}
2588
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002589static void
2590AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002591 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002592 const FunctionProtoType *Proto
2593 = Function->getType()->getAs<FunctionProtoType>();
2594 if (!Proto || !Proto->getTypeQuals())
2595 return;
2596
Douglas Gregor304f9b02011-02-01 21:15:40 +00002597 // FIXME: Add ref-qualifier!
2598
2599 // Handle single qualifiers without copying
2600 if (Proto->getTypeQuals() == Qualifiers::Const) {
2601 Result.AddInformativeChunk(" const");
2602 return;
2603 }
2604
2605 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2606 Result.AddInformativeChunk(" volatile");
2607 return;
2608 }
2609
2610 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2611 Result.AddInformativeChunk(" restrict");
2612 return;
2613 }
2614
2615 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002616 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002617 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002618 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002619 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002620 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002621 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002622 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002623 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002624}
2625
Douglas Gregor0212fd72010-09-21 16:06:22 +00002626/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002627static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002628 const NamedDecl *ND,
2629 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002630 DeclarationName Name = ND->getDeclName();
2631 if (!Name)
2632 return;
2633
2634 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002635 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002636 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002637 switch (Name.getCXXOverloadedOperator()) {
2638 case OO_None:
2639 case OO_Conditional:
2640 case NUM_OVERLOADED_OPERATORS:
2641 OperatorName = "operator";
2642 break;
2643
2644#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2645 case OO_##Name: OperatorName = "operator" Spelling; break;
2646#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2647#include "clang/Basic/OperatorKinds.def"
2648
2649 case OO_New: OperatorName = "operator new"; break;
2650 case OO_Delete: OperatorName = "operator delete"; break;
2651 case OO_Array_New: OperatorName = "operator new[]"; break;
2652 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2653 case OO_Call: OperatorName = "operator()"; break;
2654 case OO_Subscript: OperatorName = "operator[]"; break;
2655 }
2656 Result.AddTypedTextChunk(OperatorName);
2657 break;
2658 }
2659
Douglas Gregor0212fd72010-09-21 16:06:22 +00002660 case DeclarationName::Identifier:
2661 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002662 case DeclarationName::CXXDestructorName:
2663 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002664 Result.AddTypedTextChunk(
2665 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002666 break;
2667
Richard Smith35845152017-02-07 01:37:30 +00002668 case DeclarationName::CXXDeductionGuideName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002669 case DeclarationName::CXXUsingDirective:
2670 case DeclarationName::ObjCZeroArgSelector:
2671 case DeclarationName::ObjCOneArgSelector:
2672 case DeclarationName::ObjCMultiArgSelector:
2673 break;
2674
2675 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002676 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002677 QualType Ty = Name.getCXXNameType();
2678 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2679 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2680 else if (const InjectedClassNameType *InjectedTy
2681 = Ty->getAs<InjectedClassNameType>())
2682 Record = InjectedTy->getDecl();
2683 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002684 Result.AddTypedTextChunk(
2685 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002686 break;
2687 }
2688
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002689 Result.AddTypedTextChunk(
2690 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002691 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002692 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002693 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002694 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002695 }
2696 break;
2697 }
2698 }
2699}
2700
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002701CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002702 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002703 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002704 CodeCompletionTUInfo &CCTUInfo,
2705 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002706 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2707 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002708}
2709
Douglas Gregor3545ff42009-09-21 16:56:56 +00002710/// \brief If possible, create a new code completion string for the given
2711/// result.
2712///
2713/// \returns Either a new, heap-allocated code completion string describing
2714/// how to use this result, or NULL to indicate that the string or name of the
2715/// result is all that is needed.
2716CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002717CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2718 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002719 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002720 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002721 CodeCompletionTUInfo &CCTUInfo,
2722 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002723 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002724
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002725 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002726 if (Kind == RK_Pattern) {
2727 Pattern->Priority = Priority;
2728 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002729
2730 if (Declaration) {
2731 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002732 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002733 // Provide code completion comment for self.GetterName where
2734 // GetterName is the getter method for a property with name
2735 // different from the property name (declared via a property
2736 // getter attribute.
2737 const NamedDecl *ND = Declaration;
2738 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2739 if (M->isPropertyAccessor())
2740 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2741 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002742 PDecl->getIdentifier() != M->getIdentifier()) {
2743 if (const RawComment *RC =
2744 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002745 Result.addBriefComment(RC->getBriefText(Ctx));
2746 Pattern->BriefComment = Result.getBriefComment();
2747 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002748 else if (const RawComment *RC =
2749 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2750 Result.addBriefComment(RC->getBriefText(Ctx));
2751 Pattern->BriefComment = Result.getBriefComment();
2752 }
2753 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002754 }
2755
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002756 return Pattern;
2757 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002758
Douglas Gregorf09935f2009-12-01 05:55:20 +00002759 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002760 Result.AddTypedTextChunk(Keyword);
2761 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002762 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002763
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002764 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002765 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002766 Result.AddTypedTextChunk(
2767 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002768
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002769 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002770 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002771
2772 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002773 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Faisal Valiac506d72017-07-17 17:18:43 +00002774 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002775
2776 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2777 if (MI->isC99Varargs()) {
2778 --AEnd;
2779
2780 if (A == AEnd) {
2781 Result.AddPlaceholderChunk("...");
2782 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002783 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002784
Faisal Valiac506d72017-07-17 17:18:43 +00002785 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
2786 if (A != MI->param_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002787 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002788
2789 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002790 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002791 if (MI->isC99Varargs())
2792 Arg += ", ...";
2793 else
2794 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002795 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002796 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002797 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002798
2799 // Non-variadic macros are simple.
2800 Result.AddPlaceholderChunk(
2801 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002802 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002803 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002804 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002805 }
2806
Douglas Gregorf64acca2010-05-25 21:41:55 +00002807 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002808 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002809 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002810
2811 if (IncludeBriefComments) {
2812 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002813 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002814 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002815 }
2816 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2817 if (OMD->isPropertyAccessor())
2818 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2819 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2820 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002821 }
2822
Douglas Gregor9eb77012009-11-07 00:00:49 +00002823 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002824 Result.AddTypedTextChunk(
2825 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002826 Result.AddTextChunk("::");
2827 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002828 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002829
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002830 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2831 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002832
Douglas Gregorc3425b12015-07-07 06:20:19 +00002833 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002834
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002835 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002836 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002837 Ctx, Policy);
2838 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002839 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002840 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002841 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002842 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002843 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002844 }
2845
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002846 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002847 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002848 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002849 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002850 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002851
Douglas Gregor3545ff42009-09-21 16:56:56 +00002852 // Figure out which template parameters are deduced (or have default
2853 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002854 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002855 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002856 unsigned LastDeducibleArgument;
2857 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2858 --LastDeducibleArgument) {
2859 if (!Deduced[LastDeducibleArgument - 1]) {
2860 // C++0x: Figure out if the template argument has a default. If so,
2861 // the user doesn't need to type this argument.
2862 // FIXME: We need to abstract template parameters better!
2863 bool HasDefaultArg = false;
2864 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002865 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002866 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2867 HasDefaultArg = TTP->hasDefaultArgument();
2868 else if (NonTypeTemplateParmDecl *NTTP
2869 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2870 HasDefaultArg = NTTP->hasDefaultArgument();
2871 else {
2872 assert(isa<TemplateTemplateParmDecl>(Param));
2873 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002874 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002875 }
2876
2877 if (!HasDefaultArg)
2878 break;
2879 }
2880 }
2881
2882 if (LastDeducibleArgument) {
2883 // Some of the function template arguments cannot be deduced from a
2884 // function call, so we introduce an explicit template argument list
2885 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002886 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002887 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002888 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002889 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002890 }
2891
2892 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002893 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002894 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002895 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002896 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002897 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002898 }
2899
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002900 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002901 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002902 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002903 Result.AddTypedTextChunk(
2904 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002905 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002906 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002907 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002908 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002909 }
2910
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002911 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002912 Selector Sel = Method->getSelector();
2913 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002914 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002915 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002916 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002917 }
2918
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002919 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002920 SelName += ':';
2921 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002922 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002923 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002924 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002925
2926 // If there is only one parameter, and we're past it, add an empty
2927 // typed-text chunk since there is nothing to type.
2928 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002929 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002930 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002931 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002932 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2933 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002934 P != PEnd; (void)++P, ++Idx) {
2935 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002936 std::string Keyword;
2937 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002938 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002939 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002940 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002941 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002942 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002943 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002944 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002945 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002946 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002947
2948 // If we're before the starting parameter, skip the placeholder.
2949 if (Idx < StartParameter)
2950 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002951
2952 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002953 QualType ParamType = (*P)->getType();
2954 Optional<ArrayRef<QualType>> ObjCSubsts;
2955 if (!CCContext.getBaseType().isNull())
2956 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2957
2958 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2959 Arg = FormatFunctionParameter(Policy, *P, true,
2960 /*SuppressBlock=*/false,
2961 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002962 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002963 if (ObjCSubsts)
2964 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2965 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002966 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002967 ParamType);
2968 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002969 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002970 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002971 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002972 }
2973
Douglas Gregor400f5972010-08-31 05:13:43 +00002974 if (Method->isVariadic() && (P + 1) == PEnd)
2975 Arg += ", ...";
2976
Douglas Gregor95887f92010-07-08 23:20:03 +00002977 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002978 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002979 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002980 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002981 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002982 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002983 }
2984
Douglas Gregor04c5f972009-12-23 00:21:46 +00002985 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002986 if (Method->param_size() == 0) {
2987 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002988 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002989 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002990 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002991 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002992 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002993 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002994
Richard Smith20e883e2015-04-29 23:20:19 +00002995 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002996 }
2997
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002998 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002999 }
3000
Douglas Gregorf09935f2009-12-01 05:55:20 +00003001 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00003002 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00003003 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00003004
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003005 Result.AddTypedTextChunk(
3006 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003007 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003008}
3009
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003010/// \brief Add function overload parameter chunks to the given code completion
3011/// string.
3012static void AddOverloadParameterChunks(ASTContext &Context,
3013 const PrintingPolicy &Policy,
3014 const FunctionDecl *Function,
3015 const FunctionProtoType *Prototype,
3016 CodeCompletionBuilder &Result,
3017 unsigned CurrentArg,
3018 unsigned Start = 0,
3019 bool InOptional = false) {
3020 bool FirstParameter = true;
3021 unsigned NumParams = Function ? Function->getNumParams()
3022 : Prototype->getNumParams();
3023
3024 for (unsigned P = Start; P != NumParams; ++P) {
3025 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3026 // When we see an optional default argument, put that argument and
3027 // the remaining default arguments into a new, optional string.
3028 CodeCompletionBuilder Opt(Result.getAllocator(),
3029 Result.getCodeCompletionTUInfo());
3030 if (!FirstParameter)
3031 Opt.AddChunk(CodeCompletionString::CK_Comma);
3032 // Optional sections are nested.
3033 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3034 CurrentArg, P, /*InOptional=*/true);
3035 Result.AddOptionalChunk(Opt.TakeString());
3036 return;
3037 }
3038
3039 if (FirstParameter)
3040 FirstParameter = false;
3041 else
3042 Result.AddChunk(CodeCompletionString::CK_Comma);
3043
3044 InOptional = false;
3045
3046 // Format the placeholder string.
3047 std::string Placeholder;
Erik Verbruggen11338c52017-07-19 10:45:40 +00003048 if (Function) {
3049 const ParmVarDecl *Param = Function->getParamDecl(P);
3050 Placeholder = FormatFunctionParameter(Policy, Param);
3051 if (Param->hasDefaultArg())
3052 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
3053 } else {
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003054 Placeholder = Prototype->getParamType(P).getAsString(Policy);
Erik Verbruggen11338c52017-07-19 10:45:40 +00003055 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003056
3057 if (P == CurrentArg)
3058 Result.AddCurrentParameterChunk(
3059 Result.getAllocator().CopyString(Placeholder));
3060 else
3061 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3062 }
3063
3064 if (Prototype && Prototype->isVariadic()) {
3065 CodeCompletionBuilder Opt(Result.getAllocator(),
3066 Result.getCodeCompletionTUInfo());
3067 if (!FirstParameter)
3068 Opt.AddChunk(CodeCompletionString::CK_Comma);
3069
3070 if (CurrentArg < NumParams)
3071 Opt.AddPlaceholderChunk("...");
3072 else
3073 Opt.AddCurrentParameterChunk("...");
3074
3075 Result.AddOptionalChunk(Opt.TakeString());
3076 }
3077}
3078
Douglas Gregorf0f51982009-09-23 00:34:09 +00003079CodeCompletionString *
3080CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003081 unsigned CurrentArg, Sema &S,
3082 CodeCompletionAllocator &Allocator,
3083 CodeCompletionTUInfo &CCTUInfo,
3084 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00003085 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00003086
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003087 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003088 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00003089 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003090 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00003091 = dyn_cast<FunctionProtoType>(getFunctionType());
3092 if (!FDecl && !Proto) {
3093 // Function without a prototype. Just give the return type and a
3094 // highlighted ellipsis.
3095 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003096 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3097 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003098 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3099 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3100 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003101 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003102 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003103
3104 if (FDecl) {
3105 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3106 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3107 FDecl->getParamDecl(CurrentArg)))
3108 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00003109 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003110 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003111 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3112 } else {
3113 Result.AddResultTypeChunk(
3114 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00003115 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003116 }
Alp Toker314cc812014-01-25 16:55:45 +00003117
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003118 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003119 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3120 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003121 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003122
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003123 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003124}
3125
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003126unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003127 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00003128 bool PreferredTypeIsPointer) {
3129 unsigned Priority = CCP_Macro;
3130
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003131 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3132 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3133 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00003134 Priority = CCP_Constant;
3135 if (PreferredTypeIsPointer)
3136 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003137 }
3138 // Treat "YES", "NO", "true", and "false" as constants.
3139 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3140 MacroName.equals("true") || MacroName.equals("false"))
3141 Priority = CCP_Constant;
3142 // Treat "bool" as a type.
3143 else if (MacroName.equals("bool"))
3144 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3145
Douglas Gregor6e240332010-08-16 16:18:59 +00003146
3147 return Priority;
3148}
3149
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003150CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003151 if (!D)
3152 return CXCursor_UnexposedDecl;
3153
3154 switch (D->getKind()) {
3155 case Decl::Enum: return CXCursor_EnumDecl;
3156 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3157 case Decl::Field: return CXCursor_FieldDecl;
3158 case Decl::Function:
3159 return CXCursor_FunctionDecl;
3160 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3161 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003162 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003163
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003164 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003165 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3166 case Decl::ObjCMethod:
3167 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3168 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3169 case Decl::CXXMethod: return CXCursor_CXXMethod;
3170 case Decl::CXXConstructor: return CXCursor_Constructor;
3171 case Decl::CXXDestructor: return CXCursor_Destructor;
3172 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3173 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003174 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003175 case Decl::ParmVar: return CXCursor_ParmDecl;
3176 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003177 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003178 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003179 case Decl::Var: return CXCursor_VarDecl;
3180 case Decl::Namespace: return CXCursor_Namespace;
3181 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3182 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3183 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3184 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3185 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3186 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003187 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003188 case Decl::ClassTemplatePartialSpecialization:
3189 return CXCursor_ClassTemplatePartialSpecialization;
3190 case Decl::UsingDirective: return CXCursor_UsingDirective;
Olivier Goffart81978012016-06-09 16:15:55 +00003191 case Decl::StaticAssert: return CXCursor_StaticAssert;
Olivier Goffartd211c642016-11-04 06:29:27 +00003192 case Decl::Friend: return CXCursor_FriendDecl;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003193 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003194
3195 case Decl::Using:
3196 case Decl::UnresolvedUsingValue:
3197 case Decl::UnresolvedUsingTypename:
3198 return CXCursor_UsingDeclaration;
3199
Douglas Gregor4cd65962011-06-03 23:08:58 +00003200 case Decl::ObjCPropertyImpl:
3201 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3202 case ObjCPropertyImplDecl::Dynamic:
3203 return CXCursor_ObjCDynamicDecl;
3204
3205 case ObjCPropertyImplDecl::Synthesize:
3206 return CXCursor_ObjCSynthesizeDecl;
3207 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003208
3209 case Decl::Import:
3210 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003211
3212 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3213
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003214 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003215 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003216 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003217 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003218 case TTK_Struct: return CXCursor_StructDecl;
3219 case TTK_Class: return CXCursor_ClassDecl;
3220 case TTK_Union: return CXCursor_UnionDecl;
3221 case TTK_Enum: return CXCursor_EnumDecl;
3222 }
3223 }
3224 }
3225
3226 return CXCursor_UnexposedDecl;
3227}
3228
Douglas Gregor55b037b2010-07-08 20:55:51 +00003229static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003230 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003231 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003232 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003233
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003234 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003235
Douglas Gregor9eb77012009-11-07 00:00:49 +00003236 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3237 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003238 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003239 auto MD = PP.getMacroDefinition(M->first);
3240 if (IncludeUndefined || MD) {
3241 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003242 if (MI->isUsedForHeaderGuard())
3243 continue;
3244
Douglas Gregor8cb17462012-10-09 16:01:50 +00003245 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003246 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003247 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003248 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003249 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003250 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003251
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003252 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003253
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003254}
3255
Douglas Gregorce0e8562010-08-23 21:54:33 +00003256static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3257 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003258 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003259
3260 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003261
Douglas Gregorce0e8562010-08-23 21:54:33 +00003262 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3263 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003264 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003265 Results.AddResult(Result("__func__", CCP_Constant));
3266 Results.ExitScope();
3267}
3268
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003269static void HandleCodeCompleteResults(Sema *S,
3270 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003271 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003272 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003273 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003274 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003275 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003276}
3277
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003278static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3279 Sema::ParserCompletionContext PCC) {
3280 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003281 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003282 return CodeCompletionContext::CCC_TopLevel;
3283
John McCallfaf5fb42010-08-26 23:41:50 +00003284 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003285 return CodeCompletionContext::CCC_ClassStructUnion;
3286
John McCallfaf5fb42010-08-26 23:41:50 +00003287 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003288 return CodeCompletionContext::CCC_ObjCInterface;
3289
John McCallfaf5fb42010-08-26 23:41:50 +00003290 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003291 return CodeCompletionContext::CCC_ObjCImplementation;
3292
John McCallfaf5fb42010-08-26 23:41:50 +00003293 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003294 return CodeCompletionContext::CCC_ObjCIvarList;
3295
John McCallfaf5fb42010-08-26 23:41:50 +00003296 case Sema::PCC_Template:
3297 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003298 if (S.CurContext->isFileContext())
3299 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003300 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003301 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003302 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003303
John McCallfaf5fb42010-08-26 23:41:50 +00003304 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003305 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003306
John McCallfaf5fb42010-08-26 23:41:50 +00003307 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003308 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3309 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003310 return CodeCompletionContext::CCC_ParenthesizedExpression;
3311 else
3312 return CodeCompletionContext::CCC_Expression;
3313
3314 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003315 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003316 return CodeCompletionContext::CCC_Expression;
3317
John McCallfaf5fb42010-08-26 23:41:50 +00003318 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003319 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003320
John McCallfaf5fb42010-08-26 23:41:50 +00003321 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003322 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003323
3324 case Sema::PCC_ParenthesizedExpression:
3325 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003326
3327 case Sema::PCC_LocalDeclarationSpecifiers:
3328 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003329 }
David Blaikie8a40f702012-01-17 06:56:22 +00003330
3331 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003332}
3333
Douglas Gregorac322ec2010-08-27 21:18:54 +00003334/// \brief If we're in a C++ virtual member function, add completion results
3335/// that invoke the functions we override, since it's common to invoke the
3336/// overridden function as well as adding new functionality.
3337///
3338/// \param S The semantic analysis object for which we are generating results.
3339///
3340/// \param InContext This context in which the nested-name-specifier preceding
3341/// the code-completion point
3342static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3343 ResultBuilder &Results) {
3344 // Look through blocks.
3345 DeclContext *CurContext = S.CurContext;
3346 while (isa<BlockDecl>(CurContext))
3347 CurContext = CurContext->getParent();
3348
3349
3350 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3351 if (!Method || !Method->isVirtual())
3352 return;
3353
3354 // We need to have names for all of the parameters, if we're going to
3355 // generate a forwarding call.
David Majnemer59f77922016-06-24 04:05:48 +00003356 for (auto P : Method->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003357 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003358 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003359
Douglas Gregor75acd922011-09-27 23:30:47 +00003360 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003361 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3362 MEnd = Method->end_overridden_methods();
3363 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003364 CodeCompletionBuilder Builder(Results.getAllocator(),
3365 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003366 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003367 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3368 continue;
3369
3370 // If we need a nested-name-specifier, add one now.
3371 if (!InContext) {
3372 NestedNameSpecifier *NNS
3373 = getRequiredQualification(S.Context, CurContext,
3374 Overridden->getDeclContext());
3375 if (NNS) {
3376 std::string Str;
3377 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003378 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003379 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003380 }
3381 } else if (!InContext->Equals(Overridden->getDeclContext()))
3382 continue;
3383
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003384 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003385 Overridden->getNameAsString()));
3386 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003387 bool FirstParam = true;
David Majnemer59f77922016-06-24 04:05:48 +00003388 for (auto P : Method->parameters()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003389 if (FirstParam)
3390 FirstParam = false;
3391 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003392 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003393
Aaron Ballman43b68be2014-03-07 17:50:17 +00003394 Builder.AddPlaceholderChunk(
3395 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003396 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003397 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3398 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003399 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003400 CXCursor_CXXMethod,
3401 CXAvailability_Available,
3402 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003403 Results.Ignore(Overridden);
3404 }
3405}
3406
Douglas Gregor07f43572012-01-29 18:15:03 +00003407void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3408 ModuleIdPath Path) {
3409 typedef CodeCompletionResult Result;
3410 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003411 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003412 CodeCompletionContext::CCC_Other);
3413 Results.EnterNewScope();
3414
3415 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003416 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003417 typedef CodeCompletionResult Result;
3418 if (Path.empty()) {
3419 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003420 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003421 PP.getHeaderSearchInfo().collectAllModules(Modules);
3422 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3423 Builder.AddTypedTextChunk(
3424 Builder.getAllocator().CopyString(Modules[I]->Name));
3425 Results.AddResult(Result(Builder.TakeString(),
3426 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003427 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003428 Modules[I]->isAvailable()
3429 ? CXAvailability_Available
3430 : CXAvailability_NotAvailable));
3431 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003432 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003433 // Load the named module.
3434 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3435 Module::AllVisible,
3436 /*IsInclusionDirective=*/false);
3437 // Enumerate submodules.
3438 if (Mod) {
3439 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3440 SubEnd = Mod->submodule_end();
3441 Sub != SubEnd; ++Sub) {
3442
3443 Builder.AddTypedTextChunk(
3444 Builder.getAllocator().CopyString((*Sub)->Name));
3445 Results.AddResult(Result(Builder.TakeString(),
3446 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003447 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003448 (*Sub)->isAvailable()
3449 ? CXAvailability_Available
3450 : CXAvailability_NotAvailable));
3451 }
3452 }
3453 }
3454 Results.ExitScope();
3455 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3456 Results.data(),Results.size());
3457}
3458
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003459void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003460 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003461 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003462 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003463 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003464 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003465
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003466 // Determine how to filter results, e.g., so that the names of
3467 // values (functions, enumerators, function templates, etc.) are
3468 // only allowed where we can have an expression.
3469 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003470 case PCC_Namespace:
3471 case PCC_Class:
3472 case PCC_ObjCInterface:
3473 case PCC_ObjCImplementation:
3474 case PCC_ObjCInstanceVariableList:
3475 case PCC_Template:
3476 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003477 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003478 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003479 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3480 break;
3481
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003482 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003483 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003484 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003485 case PCC_ForInit:
3486 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003487 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003488 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3489 else
3490 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003491
David Blaikiebbafb8a2012-03-11 07:00:24 +00003492 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003493 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003494 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003495
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003496 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003497 // Unfiltered
3498 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003499 }
3500
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003501 // If we are in a C++ non-static member function, check the qualifiers on
3502 // the member function to filter/prioritize the results list.
3503 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3504 if (CurMethod->isInstance())
3505 Results.setObjectTypeQualifiers(
3506 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3507
Douglas Gregorc580c522010-01-14 01:09:38 +00003508 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003509 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3510 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003511
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003512 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003513 Results.ExitScope();
3514
Douglas Gregorce0e8562010-08-23 21:54:33 +00003515 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003516 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003517 case PCC_Expression:
3518 case PCC_Statement:
3519 case PCC_RecoveryInFunction:
3520 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003521 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003522 break;
3523
3524 case PCC_Namespace:
3525 case PCC_Class:
3526 case PCC_ObjCInterface:
3527 case PCC_ObjCImplementation:
3528 case PCC_ObjCInstanceVariableList:
3529 case PCC_Template:
3530 case PCC_MemberTemplate:
3531 case PCC_ForInit:
3532 case PCC_Condition:
3533 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003534 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003535 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003536 }
3537
Douglas Gregor9eb77012009-11-07 00:00:49 +00003538 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003539 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003540
Douglas Gregor50832e02010-09-20 22:39:41 +00003541 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003542 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003543}
3544
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003545static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3546 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003547 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003548 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003549 bool IsSuper,
3550 ResultBuilder &Results);
3551
3552void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3553 bool AllowNonIdentifiers,
3554 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003555 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003556 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003557 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003558 AllowNestedNameSpecifiers
3559 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3560 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003561 Results.EnterNewScope();
3562
3563 // Type qualifiers can come after names.
3564 Results.AddResult(Result("const"));
3565 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003567 Results.AddResult(Result("restrict"));
3568
David Blaikiebbafb8a2012-03-11 07:00:24 +00003569 if (getLangOpts().CPlusPlus) {
Alex Lorenz8f4d3992017-02-13 23:19:40 +00003570 if (getLangOpts().CPlusPlus11 &&
3571 (DS.getTypeSpecType() == DeclSpec::TST_class ||
3572 DS.getTypeSpecType() == DeclSpec::TST_struct))
3573 Results.AddResult("final");
3574
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003575 if (AllowNonIdentifiers) {
3576 Results.AddResult(Result("operator"));
3577 }
3578
3579 // Add nested-name-specifiers.
3580 if (AllowNestedNameSpecifiers) {
3581 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003582 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003583 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3584 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3585 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003586 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003587 }
3588 }
3589 Results.ExitScope();
3590
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003591 // If we're in a context where we might have an expression (rather than a
3592 // declaration), and what we've seen so far is an Objective-C type that could
3593 // be a receiver of a class message, this may be a class message send with
3594 // the initial opening bracket '[' missing. Add appropriate completions.
3595 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003596 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003597 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003598 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3599 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003600 !DS.isTypeAltiVecVector() &&
3601 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003602 (S->getFlags() & Scope::DeclScope) != 0 &&
3603 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3604 Scope::FunctionPrototypeScope |
3605 Scope::AtCatchScope)) == 0) {
3606 ParsedType T = DS.getRepAsType();
3607 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003608 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003609 }
3610
Douglas Gregor56ccce02010-08-24 04:59:56 +00003611 // Note that we intentionally suppress macro results here, since we do not
3612 // encourage using macros to produce the names of entities.
3613
Douglas Gregor0ac41382010-09-23 23:01:17 +00003614 HandleCodeCompleteResults(this, CodeCompleter,
3615 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003616 Results.data(), Results.size());
3617}
3618
Douglas Gregor68762e72010-08-23 21:17:50 +00003619struct Sema::CodeCompleteExpressionData {
3620 CodeCompleteExpressionData(QualType PreferredType = QualType())
3621 : PreferredType(PreferredType), IntegralConstantExpression(false),
3622 ObjCCollection(false) { }
3623
3624 QualType PreferredType;
3625 bool IntegralConstantExpression;
3626 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003627 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003628};
3629
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003630/// \brief Perform code-completion in an expression context when we know what
3631/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003632void Sema::CodeCompleteExpression(Scope *S,
3633 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003634 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003635 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003636 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003637 if (Data.ObjCCollection)
3638 Results.setFilter(&ResultBuilder::IsObjCCollection);
3639 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003640 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003641 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003642 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3643 else
3644 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003645
3646 if (!Data.PreferredType.isNull())
3647 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3648
3649 // Ignore any declarations that we were told that we don't care about.
3650 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3651 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003652
3653 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003654 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3655 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003656
3657 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003658 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003659 Results.ExitScope();
3660
Douglas Gregor55b037b2010-07-08 20:55:51 +00003661 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003662 if (!Data.PreferredType.isNull())
3663 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3664 || Data.PreferredType->isMemberPointerType()
3665 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003666
Douglas Gregorce0e8562010-08-23 21:54:33 +00003667 if (S->getFnParent() &&
3668 !Data.ObjCCollection &&
3669 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003670 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003671
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003672 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003673 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003674 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003675 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3676 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003677 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003678}
3679
Douglas Gregoreda7e542010-09-18 01:28:11 +00003680void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3681 if (E.isInvalid())
3682 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003683 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003684 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003685}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003686
Douglas Gregorb888acf2010-12-09 23:01:55 +00003687/// \brief The set of properties that have already been added, referenced by
3688/// property name.
3689typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3690
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003691/// \brief Retrieve the container definition, if any?
3692static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3693 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3694 if (Interface->hasDefinition())
3695 return Interface->getDefinition();
3696
3697 return Interface;
3698 }
3699
3700 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3701 if (Protocol->hasDefinition())
3702 return Protocol->getDefinition();
3703
3704 return Protocol;
3705 }
3706 return Container;
3707}
3708
Alex Lorenzbaef8022016-11-09 13:43:18 +00003709/// \brief Adds a block invocation code completion result for the given block
3710/// declaration \p BD.
3711static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3712 CodeCompletionBuilder &Builder,
3713 const NamedDecl *BD,
3714 const FunctionTypeLoc &BlockLoc,
3715 const FunctionProtoTypeLoc &BlockProtoLoc) {
3716 Builder.AddResultTypeChunk(
3717 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3718 Policy, Builder.getAllocator()));
3719
3720 AddTypedNameChunk(Context, Policy, BD, Builder);
3721 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3722
3723 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3724 Builder.AddPlaceholderChunk("...");
3725 } else {
3726 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3727 if (I)
3728 Builder.AddChunk(CodeCompletionString::CK_Comma);
3729
3730 // Format the placeholder string.
3731 std::string PlaceholderStr =
3732 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3733
3734 if (I == N - 1 && BlockProtoLoc &&
3735 BlockProtoLoc.getTypePtr()->isVariadic())
3736 PlaceholderStr += ", ...";
3737
3738 // Add the placeholder string.
3739 Builder.AddPlaceholderChunk(
3740 Builder.getAllocator().CopyString(PlaceholderStr));
3741 }
3742 }
3743
3744 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3745}
3746
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003747static void AddObjCProperties(
3748 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3749 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3750 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3751 bool IsBaseExprStatement = false, bool IsClassProperty = false) {
John McCall276321a2010-08-25 06:19:51 +00003752 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003753
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003754 // Retrieve the definition.
3755 Container = getContainerDef(Container);
3756
Douglas Gregor9291bad2009-11-18 01:29:26 +00003757 // Add properties in this container.
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003758 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003759 if (!AddedProperties.insert(P->getIdentifier()).second)
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003760 return;
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003761
Alex Lorenzbaef8022016-11-09 13:43:18 +00003762 // FIXME: Provide block invocation completion for non-statement
3763 // expressions.
3764 if (!P->getType().getTypePtr()->isBlockPointerType() ||
3765 !IsBaseExprStatement) {
3766 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3767 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003768 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003769 }
3770
3771 // Block setter and invocation completion is provided only when we are able
3772 // to find the FunctionProtoTypeLoc with parameter names for the block.
3773 FunctionTypeLoc BlockLoc;
3774 FunctionProtoTypeLoc BlockProtoLoc;
3775 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3776 BlockProtoLoc);
3777 if (!BlockLoc) {
3778 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3779 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003780 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003781 }
3782
3783 // The default completion result for block properties should be the block
3784 // invocation completion when the base expression is a statement.
3785 CodeCompletionBuilder Builder(Results.getAllocator(),
3786 Results.getCodeCompletionTUInfo());
3787 AddObjCBlockCall(Container->getASTContext(),
3788 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3789 BlockLoc, BlockProtoLoc);
3790 Results.MaybeAddResult(
3791 Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3792 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003793
3794 // Provide additional block setter completion iff the base expression is a
Alex Lorenzbaef8022016-11-09 13:43:18 +00003795 // statement and the block property is mutable.
3796 if (!P->isReadOnly()) {
3797 CodeCompletionBuilder Builder(Results.getAllocator(),
3798 Results.getCodeCompletionTUInfo());
3799 AddResultTypeChunk(Container->getASTContext(),
3800 getCompletionPrintingPolicy(Results.getSema()), P,
3801 CCContext.getBaseType(), Builder);
3802 Builder.AddTypedTextChunk(
3803 Results.getAllocator().CopyString(P->getName()));
3804 Builder.AddChunk(CodeCompletionString::CK_Equal);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003805
Alex Lorenzbaef8022016-11-09 13:43:18 +00003806 std::string PlaceholderStr = formatBlockPlaceholder(
3807 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3808 BlockProtoLoc, /*SuppressBlockName=*/true);
3809 // Add the placeholder string.
3810 Builder.AddPlaceholderChunk(
3811 Builder.getAllocator().CopyString(PlaceholderStr));
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003812
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003813 // When completing blocks properties that return void the default
3814 // property completion result should show up before the setter,
3815 // otherwise the setter completion should show up before the default
3816 // property completion, as we normally want to use the result of the
3817 // call.
Alex Lorenzbaef8022016-11-09 13:43:18 +00003818 Results.MaybeAddResult(
3819 Result(Builder.TakeString(), P,
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003820 Results.getBasePriority(P) +
3821 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3822 ? CCD_BlockPropertySetter
3823 : -CCD_BlockPropertySetter)),
Alex Lorenzbaef8022016-11-09 13:43:18 +00003824 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003825 }
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003826 };
3827
3828 if (IsClassProperty) {
3829 for (const auto *P : Container->class_properties())
3830 AddProperty(P);
3831 } else {
3832 for (const auto *P : Container->instance_properties())
3833 AddProperty(P);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003834 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003835
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003836 // Add nullary methods or implicit class properties
Douglas Gregor95147142011-05-05 15:50:42 +00003837 if (AllowNullaryMethods) {
3838 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003839 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003840 // Adds a method result
3841 const auto AddMethod = [&](const ObjCMethodDecl *M) {
3842 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3843 if (!Name)
3844 return;
3845 if (!AddedProperties.insert(Name).second)
3846 return;
3847 CodeCompletionBuilder Builder(Results.getAllocator(),
3848 Results.getCodeCompletionTUInfo());
3849 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3850 Builder.AddTypedTextChunk(
3851 Results.getAllocator().CopyString(Name->getName()));
3852 Results.MaybeAddResult(
3853 Result(Builder.TakeString(), M,
3854 CCP_MemberDeclaration + CCD_MethodAsProperty),
3855 CurContext);
3856 };
3857
3858 if (IsClassProperty) {
3859 for (const auto *M : Container->methods()) {
3860 // Gather the class method that can be used as implicit property
3861 // getters. Methods with arguments or methods that return void aren't
3862 // added to the results as they can't be used as a getter.
3863 if (!M->getSelector().isUnarySelector() ||
3864 M->getReturnType()->isVoidType() || M->isInstanceMethod())
3865 continue;
3866 AddMethod(M);
3867 }
3868 } else {
3869 for (auto *M : Container->methods()) {
3870 if (M->getSelector().isUnarySelector())
3871 AddMethod(M);
3872 }
Douglas Gregor95147142011-05-05 15:50:42 +00003873 }
3874 }
Douglas Gregor95147142011-05-05 15:50:42 +00003875
Douglas Gregor9291bad2009-11-18 01:29:26 +00003876 // Add properties in referenced protocols.
3877 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003878 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003879 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003880 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003881 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003882 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003883 if (AllowCategories) {
3884 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003885 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003886 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003887 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003888 IsBaseExprStatement, IsClassProperty);
Douglas Gregor5d649882009-11-18 22:32:06 +00003889 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003890
Douglas Gregor9291bad2009-11-18 01:29:26 +00003891 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003892 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003893 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003894 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003895 IsBaseExprStatement, IsClassProperty);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003896
Douglas Gregor9291bad2009-11-18 01:29:26 +00003897 // Look in the superclass.
3898 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003899 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003900 AllowNullaryMethods, CurContext, AddedProperties,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003901 Results, IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003902 } else if (const ObjCCategoryDecl *Category
3903 = dyn_cast<ObjCCategoryDecl>(Container)) {
3904 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003905 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003906 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003907 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003908 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003909 }
3910}
3911
Alex Lorenz0fe0d982017-05-11 13:41:00 +00003912static void AddRecordMembersCompletionResults(Sema &SemaRef,
3913 ResultBuilder &Results, Scope *S,
3914 QualType BaseType,
3915 RecordDecl *RD) {
3916 // Indicate that we are performing a member access, and the cv-qualifiers
3917 // for the base object type.
3918 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3919
3920 // Access to a C/C++ class, struct, or union.
3921 Results.allowNestedNameSpecifiers();
3922 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3923 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003924 SemaRef.CodeCompleter->includeGlobals(),
3925 /*IncludeDependentBases=*/true);
Alex Lorenz0fe0d982017-05-11 13:41:00 +00003926
3927 if (SemaRef.getLangOpts().CPlusPlus) {
3928 if (!Results.empty()) {
3929 // The "template" keyword can follow "->" or "." in the grammar.
3930 // However, we only want to suggest the template keyword if something
3931 // is dependent.
3932 bool IsDependent = BaseType->isDependentType();
3933 if (!IsDependent) {
3934 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3935 if (DeclContext *Ctx = DepScope->getEntity()) {
3936 IsDependent = Ctx->isDependentContext();
3937 break;
3938 }
3939 }
3940
3941 if (IsDependent)
3942 Results.AddResult(CodeCompletionResult("template"));
3943 }
3944 }
3945}
3946
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003947void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003948 SourceLocation OpLoc, bool IsArrow,
3949 bool IsBaseExprStatement) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003950 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003951 return;
3952
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003953 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3954 if (ConvertedBase.isInvalid())
3955 return;
3956 Base = ConvertedBase.get();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003957
Douglas Gregor2436e712009-09-17 21:32:03 +00003958 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003959
3960 if (IsArrow) {
3961 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3962 BaseType = Ptr->getPointeeType();
3963 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003964 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003965 else
3966 return;
3967 }
3968
Douglas Gregor21325842011-07-07 16:03:39 +00003969 enum CodeCompletionContext::Kind contextKind;
3970
3971 if (IsArrow) {
3972 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3973 }
3974 else {
3975 if (BaseType->isObjCObjectPointerType() ||
3976 BaseType->isObjCObjectOrInterfaceType()) {
3977 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3978 }
3979 else {
3980 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3981 }
3982 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003983
3984 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003985 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003986 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003987 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003988 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003989 Results.EnterNewScope();
3990 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Alex Lorenz0fe0d982017-05-11 13:41:00 +00003991 AddRecordMembersCompletionResults(*this, Results, S, BaseType,
3992 Record->getDecl());
Alex Lorenze6afa392017-05-11 13:48:57 +00003993 } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
3994 TemplateName TN = TST->getTemplateName();
3995 if (const auto *TD =
3996 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
3997 CXXRecordDecl *RD = TD->getTemplatedDecl();
3998 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
3999 }
4000 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4001 if (auto *RD = ICNT->getDecl())
4002 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
Alex Lorenz06cfa992016-10-12 11:40:15 +00004003 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00004004 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00004005 AddedPropertiesSet AddedProperties;
Alex Lorenz06cfa992016-10-12 11:40:15 +00004006
4007 if (const ObjCObjectPointerType *ObjCPtr =
4008 BaseType->getAsObjCInterfacePointerType()) {
4009 // Add property results based on our interface.
4010 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4011 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4012 /*AllowNullaryMethods=*/true, CurContext,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00004013 AddedProperties, Results, IsBaseExprStatement);
Alex Lorenz06cfa992016-10-12 11:40:15 +00004014 }
4015
Douglas Gregor9291bad2009-11-18 01:29:26 +00004016 // Add properties from the protocols in a qualified interface.
Alex Lorenz06cfa992016-10-12 11:40:15 +00004017 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00004018 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00004019 CurContext, AddedProperties, Results,
4020 IsBaseExprStatement);
Douglas Gregor9291bad2009-11-18 01:29:26 +00004021 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00004022 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00004023 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00004024 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00004025 if (const ObjCObjectPointerType *ObjCPtr
4026 = BaseType->getAs<ObjCObjectPointerType>())
4027 Class = ObjCPtr->getInterfaceDecl();
4028 else
John McCall8b07ec22010-05-15 11:32:37 +00004029 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00004030
4031 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00004032 if (Class) {
4033 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4034 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00004035 LookupVisibleDecls(Class, LookupMemberName, Consumer,
4036 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00004037 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004038 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00004039
4040 // FIXME: How do we cope with isa?
4041
4042 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00004043
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00004044 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004045 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004046 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004047 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004048}
4049
Alex Lorenzfeafdf62016-12-08 15:09:40 +00004050void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4051 IdentifierInfo &ClassName,
4052 SourceLocation ClassNameLoc,
4053 bool IsBaseExprStatement) {
4054 IdentifierInfo *ClassNamePtr = &ClassName;
4055 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4056 if (!IFace)
4057 return;
4058 CodeCompletionContext CCContext(
4059 CodeCompletionContext::CCC_ObjCPropertyAccess);
4060 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4061 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4062 &ResultBuilder::IsMember);
4063 Results.EnterNewScope();
4064 AddedPropertiesSet AddedProperties;
4065 AddObjCProperties(CCContext, IFace, true,
4066 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4067 Results, IsBaseExprStatement,
4068 /*IsClassProperty=*/true);
4069 Results.ExitScope();
4070 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4071 Results.data(), Results.size());
4072}
4073
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004074void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4075 if (!CodeCompleter)
4076 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00004077
4078 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004079 enum CodeCompletionContext::Kind ContextKind
4080 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004081 switch ((DeclSpec::TST)TagSpec) {
4082 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004083 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004084 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004085 break;
4086
4087 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004088 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004089 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004090 break;
4091
4092 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004093 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00004094 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004095 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004096 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004097 break;
4098
4099 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004100 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004101 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004102
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004103 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4104 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004105 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00004106
4107 // First pass: look for tags.
4108 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00004109 LookupVisibleDecls(S, LookupTagName, Consumer,
4110 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00004111
Douglas Gregor39982192010-08-15 06:18:01 +00004112 if (CodeCompleter->includeGlobals()) {
4113 // Second pass: look for nested name specifiers.
4114 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4115 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4116 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004117
Douglas Gregor0ac41382010-09-23 23:01:17 +00004118 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004119 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004120}
4121
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004122static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4123 const LangOptions &LangOpts) {
4124 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4125 Results.AddResult("const");
4126 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4127 Results.AddResult("volatile");
4128 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4129 Results.AddResult("restrict");
4130 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4131 Results.AddResult("_Atomic");
4132 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4133 Results.AddResult("__unaligned");
4134}
4135
Douglas Gregor28c78432010-08-27 17:35:51 +00004136void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004137 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004138 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004139 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00004140 Results.EnterNewScope();
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004141 AddTypeQualifierResults(DS, Results, LangOpts);
Douglas Gregor28c78432010-08-27 17:35:51 +00004142 Results.ExitScope();
4143 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004144 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00004145 Results.data(), Results.size());
4146}
4147
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004148void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4149 const VirtSpecifiers *VS) {
4150 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4151 CodeCompleter->getCodeCompletionTUInfo(),
4152 CodeCompletionContext::CCC_TypeQualifiers);
4153 Results.EnterNewScope();
4154 AddTypeQualifierResults(DS, Results, LangOpts);
4155 if (LangOpts.CPlusPlus11) {
4156 Results.AddResult("noexcept");
4157 if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() &&
4158 !D.isStaticMember()) {
4159 if (!VS || !VS->isFinalSpecified())
4160 Results.AddResult("final");
4161 if (!VS || !VS->isOverrideSpecified())
4162 Results.AddResult("override");
4163 }
4164 }
4165 Results.ExitScope();
4166 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4167 Results.data(), Results.size());
4168}
4169
Benjamin Kramer72dae622016-02-18 15:30:24 +00004170void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4171 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4172}
4173
Douglas Gregord328d572009-09-21 18:10:23 +00004174void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00004175 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00004176 return;
John McCall5939b162011-08-06 07:30:58 +00004177
John McCallaab3e412010-08-25 08:40:02 +00004178 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00004179 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4180 if (!type->isEnumeralType()) {
4181 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00004182 Data.IntegralConstantExpression = true;
4183 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00004184 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00004185 }
Douglas Gregord328d572009-09-21 18:10:23 +00004186
4187 // Code-complete the cases of a switch statement over an enumeration type
4188 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00004189 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004190 if (EnumDecl *Def = Enum->getDefinition())
4191 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00004192
4193 // Determine which enumerators we have already seen in the switch statement.
4194 // FIXME: Ideally, we would also be able to look *past* the code-completion
4195 // token, in case we are code-completing in the middle of the switch and not
4196 // at the end. However, we aren't able to do so at the moment.
4197 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00004198 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00004199 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4200 SC = SC->getNextSwitchCase()) {
4201 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4202 if (!Case)
4203 continue;
4204
4205 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4206 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4207 if (EnumConstantDecl *Enumerator
4208 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4209 // We look into the AST of the case statement to determine which
4210 // enumerator was named. Alternatively, we could compute the value of
4211 // the integral constant expression, then compare it against the
4212 // values of each enumerator. However, value-based approach would not
4213 // work as well with C++ templates where enumerators declared within a
4214 // template are type- and value-dependent.
4215 EnumeratorsSeen.insert(Enumerator);
4216
Douglas Gregorf2510672009-09-21 19:57:38 +00004217 // If this is a qualified-id, keep track of the nested-name-specifier
4218 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00004219 //
4220 // switch (TagD.getKind()) {
4221 // case TagDecl::TK_enum:
4222 // break;
4223 // case XXX
4224 //
Douglas Gregorf2510672009-09-21 19:57:38 +00004225 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00004226 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4227 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004228 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00004229 }
4230 }
4231
David Blaikiebbafb8a2012-03-11 07:00:24 +00004232 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00004233 // If there are no prior enumerators in C++, check whether we have to
4234 // qualify the names of the enumerators that we suggest, because they
4235 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00004236 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00004237 }
4238
Douglas Gregord328d572009-09-21 18:10:23 +00004239 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004240 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004241 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004242 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00004243 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004244 for (auto *E : Enum->enumerators()) {
4245 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00004246 continue;
4247
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004248 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00004249 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00004250 }
4251 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00004252
Douglas Gregor21325842011-07-07 16:03:39 +00004253 //We need to make sure we're setting the right context,
4254 //so only say we include macros if the code completer says we do
4255 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4256 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00004257 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00004258 kind = CodeCompletionContext::CCC_OtherWithMacros;
4259 }
4260
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004261 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00004262 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004263 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00004264}
4265
Robert Wilhelm16e94b92013-08-09 18:02:13 +00004266static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004267 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004268 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004269
4270 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004271 if (!Args[I])
4272 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004273
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004274 return false;
4275}
4276
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004277typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4278
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004279static void mergeCandidatesWithResults(Sema &SemaRef,
4280 SmallVectorImpl<ResultCandidate> &Results,
4281 OverloadCandidateSet &CandidateSet,
4282 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004283 if (!CandidateSet.empty()) {
4284 // Sort the overload candidate set by placing the best overloads first.
4285 std::stable_sort(
4286 CandidateSet.begin(), CandidateSet.end(),
4287 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4288 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
4289 });
4290
4291 // Add the remaining viable overload candidates as code-completion results.
4292 for (auto &Candidate : CandidateSet)
4293 if (Candidate.Viable)
4294 Results.push_back(ResultCandidate(Candidate.Function));
4295 }
4296}
4297
4298/// \brief Get the type of the Nth parameter from a given set of overload
4299/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004300static QualType getParamType(Sema &SemaRef,
4301 ArrayRef<ResultCandidate> Candidates,
4302 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004303
4304 // Given the overloads 'Candidates' for a function call matching all arguments
4305 // up to N, return the type of the Nth parameter if it is the same for all
4306 // overload candidates.
4307 QualType ParamType;
4308 for (auto &Candidate : Candidates) {
4309 if (auto FType = Candidate.getFunctionType())
4310 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4311 if (N < Proto->getNumParams()) {
4312 if (ParamType.isNull())
4313 ParamType = Proto->getParamType(N);
4314 else if (!SemaRef.Context.hasSameUnqualifiedType(
4315 ParamType.getNonReferenceType(),
4316 Proto->getParamType(N).getNonReferenceType()))
4317 // Otherwise return a default-constructed QualType.
4318 return QualType();
4319 }
4320 }
4321
4322 return ParamType;
4323}
4324
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004325static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4326 MutableArrayRef<ResultCandidate> Candidates,
4327 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004328 bool CompleteExpressionWithCurrentArg = true) {
4329 QualType ParamType;
4330 if (CompleteExpressionWithCurrentArg)
4331 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4332
4333 if (ParamType.isNull())
4334 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4335 else
4336 SemaRef.CodeCompleteExpression(S, ParamType);
4337
4338 if (!Candidates.empty())
4339 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4340 Candidates.data(),
4341 Candidates.size());
4342}
4343
4344void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004345 if (!CodeCompleter)
4346 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004347
4348 // When we're code-completing for a call, we fall back to ordinary
4349 // name code-completion whenever we can't produce specific
4350 // results. We may want to revisit this strategy in the future,
4351 // e.g., by merging the two kinds of results.
4352
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004353 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004354
Douglas Gregorcabea402009-09-22 15:41:20 +00004355 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004356 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4357 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004358 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004359 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004360 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004361
John McCall57500772009-12-16 12:17:52 +00004362 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004363 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004364 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004365
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004366 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004367
John McCall57500772009-12-16 12:17:52 +00004368 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004369 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004370 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004371 /*PartialOverloading=*/true);
4372 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4373 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4374 if (UME->hasExplicitTemplateArgs()) {
4375 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4376 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004377 }
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00004378
4379 // Add the base as first argument (use a nullptr if the base is implicit).
4380 SmallVector<Expr *, 12> ArgExprs(
4381 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004382 ArgExprs.append(Args.begin(), Args.end());
4383 UnresolvedSet<8> Decls;
4384 Decls.append(UME->decls_begin(), UME->decls_end());
4385 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4386 /*SuppressUsedConversions=*/false,
4387 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004388 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004389 FunctionDecl *FD = nullptr;
4390 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4391 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4392 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4393 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004394 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004395 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004396 !FD->getType()->getAs<FunctionProtoType>())
4397 Results.push_back(ResultCandidate(FD));
4398 else
4399 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4400 Args, CandidateSet,
4401 /*SuppressUsedConversions=*/false,
4402 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004403
4404 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4405 // If expression's type is CXXRecordDecl, it may overload the function
4406 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004407 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004408 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004409 DeclarationName OpName = Context.DeclarationNames
4410 .getCXXOperatorName(OO_Call);
4411 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4412 LookupQualifiedName(R, DC);
4413 R.suppressDiagnostics();
4414 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4415 ArgExprs.append(Args.begin(), Args.end());
4416 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4417 /*ExplicitArgs=*/nullptr,
4418 /*SuppressUsedConversions=*/false,
4419 /*PartialOverloading=*/true);
4420 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004421 } else {
4422 // Lastly we check whether expression's type is function pointer or
4423 // function.
4424 QualType T = NakedFn->getType();
4425 if (!T->getPointeeType().isNull())
4426 T = T->getPointeeType();
4427
4428 if (auto FP = T->getAs<FunctionProtoType>()) {
4429 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004430 /*PartialOverloading=*/true) ||
4431 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004432 Results.push_back(ResultCandidate(FP));
4433 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004434 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004435 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004436 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004437 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004438
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004439 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4440 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4441 !CandidateSet.empty());
4442}
4443
4444void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4445 ArrayRef<Expr *> Args) {
4446 if (!CodeCompleter)
4447 return;
4448
4449 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004450 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004451 return;
4452
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004453 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4454 if (!RD) {
4455 CodeCompleteExpression(S, Type);
4456 return;
4457 }
4458
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004459 // FIXME: Provide support for member initializers.
4460 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004461
4462 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4463
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004464 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004465 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4466 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4467 Args, CandidateSet,
4468 /*SuppressUsedConversions=*/false,
4469 /*PartialOverloading=*/true);
4470 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4471 AddTemplateOverloadCandidate(FTD,
4472 DeclAccessPair::make(FTD, C->getAccess()),
4473 /*ExplicitTemplateArgs=*/nullptr,
4474 Args, CandidateSet,
4475 /*SuppressUsedConversions=*/false,
4476 /*PartialOverloading=*/true);
4477 }
4478 }
4479
4480 SmallVector<ResultCandidate, 8> Results;
4481 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4482 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004483}
4484
John McCall48871652010-08-21 09:40:31 +00004485void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4486 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004487 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004488 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004489 return;
4490 }
4491
4492 CodeCompleteExpression(S, VD->getType());
4493}
4494
4495void Sema::CodeCompleteReturn(Scope *S) {
4496 QualType ResultType;
4497 if (isa<BlockDecl>(CurContext)) {
4498 if (BlockScopeInfo *BSI = getCurBlock())
4499 ResultType = BSI->ReturnType;
4500 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004501 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004502 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004503 ResultType = Method->getReturnType();
4504
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004505 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004506 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004507 else
4508 CodeCompleteExpression(S, ResultType);
4509}
4510
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004511void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004512 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004513 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004514 mapCodeCompletionContext(*this, PCC_Statement));
4515 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4516 Results.EnterNewScope();
4517
4518 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4519 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4520 CodeCompleter->includeGlobals());
4521
4522 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4523
4524 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004525 CodeCompletionBuilder Builder(Results.getAllocator(),
4526 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004527 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004528 if (Results.includeCodePatterns()) {
4529 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4530 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4531 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4532 Builder.AddPlaceholderChunk("statements");
4533 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4534 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4535 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004536 Results.AddResult(Builder.TakeString());
4537
4538 // "else if" block
4539 Builder.AddTypedTextChunk("else");
4540 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4541 Builder.AddTextChunk("if");
4542 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4543 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004544 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004545 Builder.AddPlaceholderChunk("condition");
4546 else
4547 Builder.AddPlaceholderChunk("expression");
4548 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004549 if (Results.includeCodePatterns()) {
4550 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4551 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4552 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4553 Builder.AddPlaceholderChunk("statements");
4554 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4555 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4556 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004557 Results.AddResult(Builder.TakeString());
4558
4559 Results.ExitScope();
4560
4561 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004562 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004563
4564 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004565 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004566
4567 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4568 Results.data(),Results.size());
4569}
4570
Richard Trieu2bd04012011-09-09 02:00:50 +00004571void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004572 if (LHS)
4573 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4574 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004575 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004576}
4577
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004578void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004579 bool EnteringContext) {
4580 if (!SS.getScopeRep() || !CodeCompleter)
4581 return;
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004582
4583 // Always pretend to enter a context to ensure that a dependent type
4584 // resolves to a dependent record.
4585 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +00004586 if (!Ctx)
4587 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004588
4589 // Try to instantiate any non-dependent declaration contexts before
4590 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004591 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004592 return;
4593
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004594 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004595 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004596 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004597 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004598
Douglas Gregor3545ff42009-09-21 16:56:56 +00004599 // The "template" keyword can follow "::" in the grammar, but only
4600 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004601 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004602 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004603 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004604
4605 // Add calls to overridden virtual functions, if there are any.
4606 //
4607 // FIXME: This isn't wonderful, because we don't know whether we're actually
4608 // in a context that permits expressions. This is a general issue with
4609 // qualified-id completions.
4610 if (!EnteringContext)
4611 MaybeAddOverrideCalls(*this, Ctx, Results);
4612 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004613
Douglas Gregorac322ec2010-08-27 21:18:54 +00004614 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004615 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4616 /*IncludeGlobalScope=*/true,
4617 /*IncludeDependentBases=*/true);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004618
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004619 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004620 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004621 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004622}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004623
4624void Sema::CodeCompleteUsing(Scope *S) {
4625 if (!CodeCompleter)
4626 return;
4627
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004628 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004629 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004630 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4631 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004632 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004633
4634 // If we aren't in class scope, we could see the "namespace" keyword.
4635 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004636 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004637
4638 // After "using", we can see anything that would start a
4639 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004640 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004641 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4642 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004643 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004644
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004645 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004646 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004647 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004648}
4649
4650void Sema::CodeCompleteUsingDirective(Scope *S) {
4651 if (!CodeCompleter)
4652 return;
4653
Douglas Gregor3545ff42009-09-21 16:56:56 +00004654 // After "using namespace", we expect to see a namespace name or namespace
4655 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004656 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004657 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004658 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004659 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004660 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004661 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004662 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4663 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004664 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004665 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004666 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004667 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004668}
4669
4670void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4671 if (!CodeCompleter)
4672 return;
4673
Ted Kremenekc37877d2013-10-08 17:08:03 +00004674 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004675 if (!S->getParent())
4676 Ctx = Context.getTranslationUnitDecl();
4677
Douglas Gregor0ac41382010-09-23 23:01:17 +00004678 bool SuppressedGlobalResults
4679 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4680
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004681 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004682 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004683 SuppressedGlobalResults
4684 ? CodeCompletionContext::CCC_Namespace
4685 : CodeCompletionContext::CCC_Other,
4686 &ResultBuilder::IsNamespace);
4687
4688 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004689 // We only want to see those namespaces that have already been defined
4690 // within this scope, because its likely that the user is creating an
4691 // extended namespace declaration. Keep track of the most recent
4692 // definition of each namespace.
4693 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4694 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4695 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4696 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004697 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004698
4699 // Add the most recent definition (or extended definition) of each
4700 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004701 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004702 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004703 NS = OrigToLatest.begin(),
4704 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004705 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004706 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004707 NS->second, Results.getBasePriority(NS->second),
4708 nullptr),
4709 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004710 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004711 }
4712
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004713 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004714 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004715 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004716}
4717
4718void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4719 if (!CodeCompleter)
4720 return;
4721
Douglas Gregor3545ff42009-09-21 16:56:56 +00004722 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004723 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004724 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004725 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004726 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004727 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004728 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4729 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004730 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004731 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004732 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004733}
4734
Douglas Gregorc811ede2009-09-18 20:05:18 +00004735void Sema::CodeCompleteOperatorName(Scope *S) {
4736 if (!CodeCompleter)
4737 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004738
John McCall276321a2010-08-25 06:19:51 +00004739 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004740 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004741 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004742 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004743 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004744 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004745
Douglas Gregor3545ff42009-09-21 16:56:56 +00004746 // Add the names of overloadable operators.
4747#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4748 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004749 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004750#include "clang/Basic/OperatorKinds.def"
4751
4752 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004753 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004754 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004755 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4756 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004757
4758 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004759 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004760 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004761
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004762 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004763 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004764 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004765}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004766
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004767void Sema::CodeCompleteConstructorInitializer(
4768 Decl *ConstructorD,
4769 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004770 if (!ConstructorD)
4771 return;
4772
4773 AdjustDeclIfTemplate(ConstructorD);
4774
4775 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004776 if (!Constructor)
4777 return;
4778
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004779 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004780 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004781 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004782 Results.EnterNewScope();
4783
4784 // Fill in any already-initialized fields or base classes.
4785 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4786 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004787 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004788 if (Initializers[I]->isBaseInitializer())
4789 InitializedBases.insert(
4790 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4791 else
Francois Pichetd583da02010-12-04 09:14:42 +00004792 InitializedFields.insert(cast<FieldDecl>(
4793 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004794 }
4795
4796 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004797 CodeCompletionBuilder Builder(Results.getAllocator(),
4798 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004799 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004800 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004801 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004802 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004803 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4804 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004805 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004806 = !Initializers.empty() &&
4807 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004808 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004809 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004810 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004811 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004812
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004813 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004814 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004815 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004816 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4817 Builder.AddPlaceholderChunk("args");
4818 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4819 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004820 SawLastInitializer? CCP_NextInitializer
4821 : CCP_MemberDeclaration));
4822 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004823 }
4824
4825 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004826 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004827 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4828 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004829 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004830 = !Initializers.empty() &&
4831 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004832 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004833 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004834 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004835 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004836
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004837 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004838 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004839 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004840 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4841 Builder.AddPlaceholderChunk("args");
4842 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4843 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004844 SawLastInitializer? CCP_NextInitializer
4845 : CCP_MemberDeclaration));
4846 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004847 }
4848
4849 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004850 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004851 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4852 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004853 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004854 = !Initializers.empty() &&
4855 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004856 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004857 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004858 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004859
4860 if (!Field->getDeclName())
4861 continue;
4862
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004863 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004864 Field->getIdentifier()->getName()));
4865 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4866 Builder.AddPlaceholderChunk("args");
4867 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4868 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004869 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004870 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004871 CXCursor_MemberRef,
4872 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004873 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004874 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004875 }
4876 Results.ExitScope();
4877
Douglas Gregor0ac41382010-09-23 23:01:17 +00004878 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004879 Results.data(), Results.size());
4880}
4881
Douglas Gregord8c61782012-02-15 15:34:24 +00004882/// \brief Determine whether this scope denotes a namespace.
4883static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004884 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004885 if (!DC)
4886 return false;
4887
4888 return DC->isFileContext();
4889}
4890
4891void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4892 bool AfterAmpersand) {
4893 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004894 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004895 CodeCompletionContext::CCC_Other);
4896 Results.EnterNewScope();
4897
4898 // Note what has already been captured.
4899 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4900 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004901 for (const auto &C : Intro.Captures) {
4902 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004903 IncludedThis = true;
4904 continue;
4905 }
4906
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004907 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004908 }
4909
4910 // Look for other capturable variables.
4911 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004912 for (const auto *D : S->decls()) {
4913 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004914 if (!Var ||
4915 !Var->hasLocalStorage() ||
4916 Var->hasAttr<BlocksAttr>())
4917 continue;
4918
David Blaikie82e95a32014-11-19 07:49:47 +00004919 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004920 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004921 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004922 }
4923 }
4924
4925 // Add 'this', if it would be valid.
4926 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4927 addThisCompletion(*this, Results);
4928
4929 Results.ExitScope();
4930
4931 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4932 Results.data(), Results.size());
4933}
4934
James Dennett596e4752012-06-14 03:11:41 +00004935/// Macro that optionally prepends an "@" to the string literal passed in via
4936/// Keyword, depending on whether NeedAt is true or false.
4937#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4938
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004939static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004940 ResultBuilder &Results,
4941 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004942 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004943 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004944 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004945
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004946 CodeCompletionBuilder Builder(Results.getAllocator(),
4947 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004948 if (LangOpts.ObjC2) {
4949 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004950 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004951 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4952 Builder.AddPlaceholderChunk("property");
4953 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004954
4955 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004956 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004957 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4958 Builder.AddPlaceholderChunk("property");
4959 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004960 }
4961}
4962
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004963static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004964 ResultBuilder &Results,
4965 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004966 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004967
4968 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004969 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004970
4971 if (LangOpts.ObjC2) {
4972 // @property
James Dennett596e4752012-06-14 03:11:41 +00004973 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004974
4975 // @required
James Dennett596e4752012-06-14 03:11:41 +00004976 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004977
4978 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004979 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004980 }
4981}
4982
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004983static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004984 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004985 CodeCompletionBuilder Builder(Results.getAllocator(),
4986 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004987
4988 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004989 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004990 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4991 Builder.AddPlaceholderChunk("name");
4992 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004993
Douglas Gregorf4c33342010-05-28 00:22:41 +00004994 if (Results.includeCodePatterns()) {
4995 // @interface name
4996 // FIXME: Could introduce the whole pattern, including superclasses and
4997 // such.
James Dennett596e4752012-06-14 03:11:41 +00004998 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004999 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5000 Builder.AddPlaceholderChunk("class");
5001 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005002
Douglas Gregorf4c33342010-05-28 00:22:41 +00005003 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00005004 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005005 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5006 Builder.AddPlaceholderChunk("protocol");
5007 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005008
5009 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00005010 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005011 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5012 Builder.AddPlaceholderChunk("class");
5013 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005014 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005015
5016 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00005017 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005018 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5019 Builder.AddPlaceholderChunk("alias");
5020 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5021 Builder.AddPlaceholderChunk("class");
5022 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00005023
5024 if (Results.getSema().getLangOpts().Modules) {
5025 // @import name
5026 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5027 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5028 Builder.AddPlaceholderChunk("module");
5029 Results.AddResult(Result(Builder.TakeString()));
5030 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005031}
5032
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005033void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005034 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005035 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005036 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005037 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005038 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00005039 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005040 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00005041 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00005042 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005043 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005044 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005045 HandleCodeCompleteResults(this, CodeCompleter,
5046 CodeCompletionContext::CCC_Other,
5047 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00005048}
5049
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005050static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005051 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005052 CodeCompletionBuilder Builder(Results.getAllocator(),
5053 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005054
5055 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005056 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00005057 if (Results.getSema().getLangOpts().CPlusPlus ||
5058 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00005059 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00005060 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00005061 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005062 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5063 Builder.AddPlaceholderChunk("type-name");
5064 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5065 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005066
5067 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005068 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00005069 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005070 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5071 Builder.AddPlaceholderChunk("protocol-name");
5072 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5073 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005074
5075 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005076 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00005077 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5079 Builder.AddPlaceholderChunk("selector");
5080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5081 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005082
5083 // @"string"
5084 Builder.AddResultTypeChunk("NSString *");
5085 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5086 Builder.AddPlaceholderChunk("string");
5087 Builder.AddTextChunk("\"");
5088 Results.AddResult(Result(Builder.TakeString()));
5089
Douglas Gregor951de302012-07-17 23:24:47 +00005090 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00005091 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00005092 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005093 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005094 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5095 Results.AddResult(Result(Builder.TakeString()));
5096
Douglas Gregor951de302012-07-17 23:24:47 +00005097 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00005098 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00005099 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005100 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005101 Builder.AddChunk(CodeCompletionString::CK_Colon);
5102 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5103 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005104 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5105 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005106
Douglas Gregor951de302012-07-17 23:24:47 +00005107 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00005108 Builder.AddResultTypeChunk("id");
5109 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00005110 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00005111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5112 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005113}
5114
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005115static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005116 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005117 CodeCompletionBuilder Builder(Results.getAllocator(),
5118 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00005119
Douglas Gregorf4c33342010-05-28 00:22:41 +00005120 if (Results.includeCodePatterns()) {
5121 // @try { statements } @catch ( declaration ) { statements } @finally
5122 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00005123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005124 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5125 Builder.AddPlaceholderChunk("statements");
5126 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5127 Builder.AddTextChunk("@catch");
5128 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5129 Builder.AddPlaceholderChunk("parameter");
5130 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5131 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5132 Builder.AddPlaceholderChunk("statements");
5133 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5134 Builder.AddTextChunk("@finally");
5135 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5136 Builder.AddPlaceholderChunk("statements");
5137 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5138 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005139 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005140
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005141 // @throw
James Dennett596e4752012-06-14 03:11:41 +00005142 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005143 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5144 Builder.AddPlaceholderChunk("expression");
5145 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005146
Douglas Gregorf4c33342010-05-28 00:22:41 +00005147 if (Results.includeCodePatterns()) {
5148 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00005149 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005150 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5151 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5152 Builder.AddPlaceholderChunk("expression");
5153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5154 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5155 Builder.AddPlaceholderChunk("statements");
5156 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5157 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005158 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005159}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005160
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005161static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00005162 ResultBuilder &Results,
5163 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005164 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00005165 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5166 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5167 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005168 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00005169 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005170}
5171
5172void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005173 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005174 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005175 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00005176 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005177 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00005178 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005179 HandleCodeCompleteResults(this, CodeCompleter,
5180 CodeCompletionContext::CCC_Other,
5181 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00005182}
5183
5184void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005185 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005186 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005187 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00005188 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005189 AddObjCStatementResults(Results, false);
5190 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005191 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005192 HandleCodeCompleteResults(this, CodeCompleter,
5193 CodeCompletionContext::CCC_Other,
5194 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005195}
5196
5197void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005198 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005199 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005200 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005201 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005202 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005203 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005204 HandleCodeCompleteResults(this, CodeCompleter,
5205 CodeCompletionContext::CCC_Other,
5206 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005207}
5208
Douglas Gregore6078da2009-11-19 00:14:45 +00005209/// \brief Determine whether the addition of the given flag to an Objective-C
5210/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00005211static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00005212 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00005213 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00005214 return true;
5215
Bill Wendling44426052012-12-20 19:22:21 +00005216 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00005217
5218 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00005219 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5220 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00005221 return true;
5222
Jordan Rose53cb2f32012-08-20 20:01:13 +00005223 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00005224 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00005225 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00005226 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00005227 ObjCDeclSpec::DQ_PR_retain |
5228 ObjCDeclSpec::DQ_PR_strong |
5229 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00005230 if (AssignCopyRetMask &&
5231 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00005232 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00005233 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00005234 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00005235 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5236 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00005237 return true;
5238
5239 return false;
5240}
5241
Douglas Gregor36029f42009-11-18 23:08:07 +00005242void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00005243 if (!CodeCompleter)
5244 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005245
Bill Wendling44426052012-12-20 19:22:21 +00005246 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00005247
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005248 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005249 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005250 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00005251 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00005252 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00005253 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00005254 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00005255 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00005256 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00005257 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5258 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00005259 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00005260 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00005261 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00005262 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00005263 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00005264 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00005265 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00005266 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00005267 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00005268 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00005269 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00005270 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00005271
5272 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00005273 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00005274 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00005275 Results.AddResult(CodeCompletionResult("weak"));
5276
Bill Wendling44426052012-12-20 19:22:21 +00005277 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005278 CodeCompletionBuilder Setter(Results.getAllocator(),
5279 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005280 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005281 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005282 Setter.AddPlaceholderChunk("method");
5283 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005284 }
Bill Wendling44426052012-12-20 19:22:21 +00005285 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005286 CodeCompletionBuilder Getter(Results.getAllocator(),
5287 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005288 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005289 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005290 Getter.AddPlaceholderChunk("method");
5291 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005292 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005293 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5294 Results.AddResult(CodeCompletionResult("nonnull"));
5295 Results.AddResult(CodeCompletionResult("nullable"));
5296 Results.AddResult(CodeCompletionResult("null_unspecified"));
5297 Results.AddResult(CodeCompletionResult("null_resettable"));
5298 }
Steve Naroff936354c2009-10-08 21:55:05 +00005299 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005300 HandleCodeCompleteResults(this, CodeCompleter,
5301 CodeCompletionContext::CCC_Other,
5302 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00005303}
Steve Naroffeae65032009-11-07 02:08:14 +00005304
James Dennettf1243872012-06-17 05:33:25 +00005305/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00005306/// via code completion.
5307enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00005308 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5309 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5310 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005311};
5312
Douglas Gregor67c692c2010-08-26 15:07:07 +00005313static bool isAcceptableObjCSelector(Selector Sel,
5314 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005315 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005316 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005317 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00005318 if (NumSelIdents > Sel.getNumArgs())
5319 return false;
5320
5321 switch (WantKind) {
5322 case MK_Any: break;
5323 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5324 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5325 }
5326
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005327 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5328 return false;
5329
Douglas Gregor67c692c2010-08-26 15:07:07 +00005330 for (unsigned I = 0; I != NumSelIdents; ++I)
5331 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5332 return false;
5333
5334 return true;
5335}
5336
Douglas Gregorc8537c52009-11-19 07:41:15 +00005337static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5338 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005339 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005340 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005341 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005342 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005343}
Douglas Gregor1154e272010-09-16 16:06:31 +00005344
5345namespace {
5346 /// \brief A set of selectors, which is used to avoid introducing multiple
5347 /// completions with the same selector into the result set.
5348 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5349}
5350
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005351/// \brief Add all of the Objective-C methods in the given Objective-C
5352/// container to the set of results.
5353///
5354/// The container will be a class, protocol, category, or implementation of
5355/// any of the above. This mether will recurse to include methods from
5356/// the superclasses of classes along with their categories, protocols, and
5357/// implementations.
5358///
5359/// \param Container the container in which we'll look to find methods.
5360///
James Dennett596e4752012-06-14 03:11:41 +00005361/// \param WantInstanceMethods Whether to add instance methods (only); if
5362/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005363///
5364/// \param CurContext the context in which we're performing the lookup that
5365/// finds methods.
5366///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005367/// \param AllowSameLength Whether we allow a method to be added to the list
5368/// when it has the same number of parameters as we have selector identifiers.
5369///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005370/// \param Results the structure into which we'll add results.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005371static void AddObjCMethods(ObjCContainerDecl *Container,
5372 bool WantInstanceMethods, ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005373 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005374 DeclContext *CurContext,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005375 VisitedSelectorSet &Selectors, bool AllowSameLength,
5376 ResultBuilder &Results, bool InOriginalClass = true,
5377 bool IsRootClass = false) {
John McCall276321a2010-08-25 06:19:51 +00005378 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005379 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005380 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Alex Lorenz638dbc32017-01-24 14:15:08 +00005381 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005382 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005383 // The instance methods on the root class can be messaged via the
5384 // metaclass.
5385 if (M->isInstanceMethod() == WantInstanceMethods ||
Alex Lorenz638dbc32017-01-24 14:15:08 +00005386 (IsRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005387 // Check whether the selector identifiers we've been given are a
5388 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005389 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005390 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005391
David Blaikie82e95a32014-11-19 07:49:47 +00005392 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005393 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005394
5395 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005396 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005397 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005398 if (!InOriginalClass)
5399 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005400 Results.MaybeAddResult(R, CurContext);
5401 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005402 }
5403
Douglas Gregorf37c9492010-09-16 15:34:59 +00005404 // Visit the protocols of protocols.
5405 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005406 if (Protocol->hasDefinition()) {
5407 const ObjCList<ObjCProtocolDecl> &Protocols
5408 = Protocol->getReferencedProtocols();
5409 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5410 E = Protocols.end();
5411 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005412 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5413 Selectors, AllowSameLength, Results, false, IsRootClass);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005414 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005415 }
5416
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005417 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005418 return;
5419
5420 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005421 for (auto *I : IFace->protocols())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005422 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5423 Selectors, AllowSameLength, Results, false, IsRootClass);
5424
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005425 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005426 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005427 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005428 CurContext, Selectors, AllowSameLength, Results,
5429 InOriginalClass, IsRootClass);
5430
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005431 // Add a categories protocol methods.
5432 const ObjCList<ObjCProtocolDecl> &Protocols
5433 = CatDecl->getReferencedProtocols();
5434 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5435 E = Protocols.end();
5436 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005437 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5438 Selectors, AllowSameLength, Results, false, IsRootClass);
5439
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005440 // Add methods in category implementations.
5441 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005442 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5443 Selectors, AllowSameLength, Results, InOriginalClass,
5444 IsRootClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005445 }
5446
5447 // Add methods in superclass.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005448 // Avoid passing in IsRootClass since root classes won't have super classes.
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005449 if (IFace->getSuperClass())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005450 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5451 SelIdents, CurContext, Selectors, AllowSameLength, Results,
5452 /*IsRootClass=*/false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005453
5454 // Add methods in our implementation, if any.
5455 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005456 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5457 Selectors, AllowSameLength, Results, InOriginalClass,
5458 IsRootClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005459}
5460
5461
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005462void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005463 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005464 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005465 if (!Class) {
5466 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005467 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005468 Class = Category->getClassInterface();
5469
5470 if (!Class)
5471 return;
5472 }
5473
5474 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005475 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005476 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005477 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005478 Results.EnterNewScope();
5479
Douglas Gregor1154e272010-09-16 16:06:31 +00005480 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005481 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005482 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005483 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005484 HandleCodeCompleteResults(this, CodeCompleter,
5485 CodeCompletionContext::CCC_Other,
5486 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005487}
5488
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005489void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005490 // Try to find the interface where setters might live.
5491 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005492 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005493 if (!Class) {
5494 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005495 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005496 Class = Category->getClassInterface();
5497
5498 if (!Class)
5499 return;
5500 }
5501
5502 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005503 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005504 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005505 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005506 Results.EnterNewScope();
5507
Douglas Gregor1154e272010-09-16 16:06:31 +00005508 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005509 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005510 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005511
5512 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005513 HandleCodeCompleteResults(this, CodeCompleter,
5514 CodeCompletionContext::CCC_Other,
5515 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005516}
5517
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005518void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5519 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005520 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005521 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005522 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005523 Results.EnterNewScope();
5524
5525 // Add context-sensitive, Objective-C parameter-passing keywords.
5526 bool AddedInOut = false;
5527 if ((DS.getObjCDeclQualifier() &
5528 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5529 Results.AddResult("in");
5530 Results.AddResult("inout");
5531 AddedInOut = true;
5532 }
5533 if ((DS.getObjCDeclQualifier() &
5534 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5535 Results.AddResult("out");
5536 if (!AddedInOut)
5537 Results.AddResult("inout");
5538 }
5539 if ((DS.getObjCDeclQualifier() &
5540 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5541 ObjCDeclSpec::DQ_Oneway)) == 0) {
5542 Results.AddResult("bycopy");
5543 Results.AddResult("byref");
5544 Results.AddResult("oneway");
5545 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005546 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5547 Results.AddResult("nonnull");
5548 Results.AddResult("nullable");
5549 Results.AddResult("null_unspecified");
5550 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005551
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005552 // If we're completing the return type of an Objective-C method and the
5553 // identifier IBAction refers to a macro, provide a completion item for
5554 // an action, e.g.,
5555 // IBAction)<#selector#>:(id)sender
5556 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005557 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005558 CodeCompletionBuilder Builder(Results.getAllocator(),
5559 Results.getCodeCompletionTUInfo(),
5560 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005561 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005562 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005563 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005564 Builder.AddChunk(CodeCompletionString::CK_Colon);
5565 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005566 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005567 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005568 Builder.AddTextChunk("sender");
5569 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5570 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005571
5572 // If we're completing the return type, provide 'instancetype'.
5573 if (!IsParameter) {
5574 Results.AddResult(CodeCompletionResult("instancetype"));
5575 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005576
Douglas Gregor99fa2642010-08-24 01:06:58 +00005577 // Add various builtin type names and specifiers.
5578 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5579 Results.ExitScope();
5580
5581 // Add the various type names
5582 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5583 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5584 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5585 CodeCompleter->includeGlobals());
5586
5587 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005588 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005589
5590 HandleCodeCompleteResults(this, CodeCompleter,
5591 CodeCompletionContext::CCC_Type,
5592 Results.data(), Results.size());
5593}
5594
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005595/// \brief When we have an expression with type "id", we may assume
5596/// that it has some more-specific class type based on knowledge of
5597/// common uses of Objective-C. This routine returns that class type,
5598/// or NULL if no better result could be determined.
5599static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005600 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005601 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005602 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005603
5604 Selector Sel = Msg->getSelector();
5605 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005606 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005607
5608 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5609 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005610 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005611
5612 ObjCMethodDecl *Method = Msg->getMethodDecl();
5613 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005614 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005615
5616 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005617 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005618 switch (Msg->getReceiverKind()) {
5619 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005620 if (const ObjCObjectType *ObjType
5621 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5622 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005623 break;
5624
5625 case ObjCMessageExpr::Instance: {
5626 QualType T = Msg->getInstanceReceiver()->getType();
5627 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5628 IFace = Ptr->getInterfaceDecl();
5629 break;
5630 }
5631
5632 case ObjCMessageExpr::SuperInstance:
5633 case ObjCMessageExpr::SuperClass:
5634 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005635 }
5636
5637 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005638 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005639
5640 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5641 if (Method->isInstanceMethod())
5642 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5643 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005644 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005645 .Case("autorelease", IFace)
5646 .Case("copy", IFace)
5647 .Case("copyWithZone", IFace)
5648 .Case("mutableCopy", IFace)
5649 .Case("mutableCopyWithZone", IFace)
5650 .Case("awakeFromCoder", IFace)
5651 .Case("replacementObjectFromCoder", IFace)
5652 .Case("class", IFace)
5653 .Case("classForCoder", IFace)
5654 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005655 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005656
5657 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5658 .Case("new", IFace)
5659 .Case("alloc", IFace)
5660 .Case("allocWithZone", IFace)
5661 .Case("class", IFace)
5662 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005663 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005664}
5665
Douglas Gregor6fc04132010-08-27 15:10:57 +00005666// Add a special completion for a message send to "super", which fills in the
5667// most likely case of forwarding all of our arguments to the superclass
5668// function.
5669///
5670/// \param S The semantic analysis object.
5671///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005672/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005673/// the "super" keyword. Otherwise, we just need to provide the arguments.
5674///
5675/// \param SelIdents The identifiers in the selector that have already been
5676/// provided as arguments for a send to "super".
5677///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005678/// \param Results The set of results to augment.
5679///
5680/// \returns the Objective-C method declaration that would be invoked by
5681/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005682static ObjCMethodDecl *AddSuperSendCompletion(
5683 Sema &S, bool NeedSuperKeyword,
5684 ArrayRef<IdentifierInfo *> SelIdents,
5685 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005686 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5687 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005688 return nullptr;
5689
Douglas Gregor6fc04132010-08-27 15:10:57 +00005690 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5691 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005692 return nullptr;
5693
Douglas Gregor6fc04132010-08-27 15:10:57 +00005694 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005695 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005696 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5697 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005698 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5699 CurMethod->isInstanceMethod());
5700
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005701 // Check in categories or class extensions.
5702 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005703 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005704 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005705 CurMethod->isInstanceMethod())))
5706 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005707 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005708 }
5709 }
5710
Douglas Gregor6fc04132010-08-27 15:10:57 +00005711 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005712 return nullptr;
5713
Douglas Gregor6fc04132010-08-27 15:10:57 +00005714 // Check whether the superclass method has the same signature.
5715 if (CurMethod->param_size() != SuperMethod->param_size() ||
5716 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005717 return nullptr;
5718
Douglas Gregor6fc04132010-08-27 15:10:57 +00005719 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5720 CurPEnd = CurMethod->param_end(),
5721 SuperP = SuperMethod->param_begin();
5722 CurP != CurPEnd; ++CurP, ++SuperP) {
5723 // Make sure the parameter types are compatible.
5724 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5725 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005726 return nullptr;
5727
Douglas Gregor6fc04132010-08-27 15:10:57 +00005728 // Make sure we have a parameter name to forward!
5729 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005730 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005731 }
5732
5733 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005734 CodeCompletionBuilder Builder(Results.getAllocator(),
5735 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005736
5737 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005738 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5739 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005740 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005741
5742 // If we need the "super" keyword, add it (plus some spacing).
5743 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005744 Builder.AddTypedTextChunk("super");
5745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005746 }
5747
5748 Selector Sel = CurMethod->getSelector();
5749 if (Sel.isUnarySelector()) {
5750 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005751 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005752 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005753 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005754 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005755 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005756 } else {
5757 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5758 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005759 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005761
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005762 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005763 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005764 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005765 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005766 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005767 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005768 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005769 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005770 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005771 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005772 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005773 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005774 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005775 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005776 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005777 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005778 }
5779 }
5780 }
5781
Douglas Gregor78254c82012-03-27 23:34:16 +00005782 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5783 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005784 return SuperMethod;
5785}
5786
Douglas Gregora817a192010-05-27 23:06:34 +00005787void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005788 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005789 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005790 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005791 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005792 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005793 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5794 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005795
Douglas Gregora817a192010-05-27 23:06:34 +00005796 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5797 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005798 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5799 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005800
5801 // If we are in an Objective-C method inside a class that has a superclass,
5802 // add "super" as an option.
5803 if (ObjCMethodDecl *Method = getCurMethodDecl())
5804 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005805 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005806 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005807
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005808 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005809 }
Douglas Gregora817a192010-05-27 23:06:34 +00005810
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005811 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005812 addThisCompletion(*this, Results);
5813
Douglas Gregora817a192010-05-27 23:06:34 +00005814 Results.ExitScope();
5815
5816 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005817 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005818 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005819 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005820
5821}
5822
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005823void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005824 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005825 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005826 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005827 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5828 // Figure out which interface we're in.
5829 CDecl = CurMethod->getClassInterface();
5830 if (!CDecl)
5831 return;
5832
5833 // Find the superclass of this class.
5834 CDecl = CDecl->getSuperClass();
5835 if (!CDecl)
5836 return;
5837
5838 if (CurMethod->isInstanceMethod()) {
5839 // We are inside an instance method, which means that the message
5840 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005841 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005842 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005843 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005844 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005845 }
5846
5847 // Fall through to send to the superclass in CDecl.
5848 } else {
5849 // "super" may be the name of a type or variable. Figure out which
5850 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005851 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005852 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5853 LookupOrdinaryName);
5854 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5855 // "super" names an interface. Use it.
5856 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005857 if (const ObjCObjectType *Iface
5858 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5859 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005860 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5861 // "super" names an unresolved type; we can't be more specific.
5862 } else {
5863 // Assume that "super" names some kind of value and parse that way.
5864 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005865 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005866 UnqualifiedId id;
5867 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005868 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5869 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005870 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005871 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005872 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005873 }
5874
5875 // Fall through
5876 }
5877
John McCallba7bf592010-08-24 05:47:05 +00005878 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005879 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005880 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005881 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005882 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005883 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005884}
5885
Douglas Gregor74661272010-09-21 00:03:25 +00005886/// \brief Given a set of code-completion results for the argument of a message
5887/// send, determine the preferred type (if any) for that argument expression.
5888static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5889 unsigned NumSelIdents) {
5890 typedef CodeCompletionResult Result;
5891 ASTContext &Context = Results.getSema().Context;
5892
5893 QualType PreferredType;
5894 unsigned BestPriority = CCP_Unlikely * 2;
5895 Result *ResultsData = Results.data();
5896 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5897 Result &R = ResultsData[I];
5898 if (R.Kind == Result::RK_Declaration &&
5899 isa<ObjCMethodDecl>(R.Declaration)) {
5900 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005901 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005902 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005903 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005904 ->getType();
5905 if (R.Priority < BestPriority || PreferredType.isNull()) {
5906 BestPriority = R.Priority;
5907 PreferredType = MyPreferredType;
5908 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5909 MyPreferredType)) {
5910 PreferredType = QualType();
5911 }
5912 }
5913 }
5914 }
5915 }
5916
5917 return PreferredType;
5918}
5919
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005920static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5921 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005922 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005923 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005924 bool IsSuper,
5925 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005926 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005927 ObjCInterfaceDecl *CDecl = nullptr;
5928
Douglas Gregor8ce33212009-11-17 17:59:40 +00005929 // If the given name refers to an interface type, retrieve the
5930 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005931 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005932 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005933 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005934 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5935 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005936 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005937
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005938 // Add all of the factory methods in this Objective-C class, its protocols,
5939 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005940 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005941
Douglas Gregor6fc04132010-08-27 15:10:57 +00005942 // If this is a send-to-super, try to add the special "super" send
5943 // completion.
5944 if (IsSuper) {
5945 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005946 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005947 Results.Ignore(SuperMethod);
5948 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005949
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005950 // If we're inside an Objective-C method definition, prefer its selector to
5951 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005952 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005953 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005954
Douglas Gregor1154e272010-09-16 16:06:31 +00005955 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005956 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005957 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005958 SemaRef.CurContext, Selectors, AtArgumentExpression,
5959 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005960 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005961 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005962
Douglas Gregord720daf2010-04-06 17:30:22 +00005963 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005964 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005965 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005966 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005967 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005968 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005969 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005970 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005971 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005972
5973 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005974 }
5975 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005976
5977 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5978 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005979 M != MEnd; ++M) {
5980 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005981 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005982 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005983 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005984 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005985
Nico Weber2e0c8f72014-12-27 03:58:08 +00005986 Result R(MethList->getMethod(),
5987 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005988 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005989 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005990 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005991 }
5992 }
5993 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005994
5995 Results.ExitScope();
5996}
Douglas Gregor6285f752010-04-06 16:40:00 +00005997
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005998void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005999 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006000 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006001 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00006002
6003 QualType T = this->GetTypeFromParser(Receiver);
6004
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006005 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006006 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006007 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006008 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006009
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006010 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006011 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00006012
6013 // If we're actually at the argument expression (rather than prior to the
6014 // selector), we're actually performing code completion for an expression.
6015 // Determine whether we have a single, best method. If so, we can
6016 // code-complete the expression using the corresponding parameter type as
6017 // our preferred type, improving completion results.
6018 if (AtArgumentExpression) {
6019 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006020 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006021 if (PreferredType.isNull())
6022 CodeCompleteOrdinaryName(S, PCC_Expression);
6023 else
6024 CodeCompleteExpression(S, PreferredType);
6025 return;
6026 }
6027
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006028 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006029 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00006030 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006031}
6032
Richard Trieu2bd04012011-09-09 02:00:50 +00006033void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006034 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006035 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00006036 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00006037 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00006038
6039 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00006040
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006041 // If necessary, apply function/array conversion to the receiver.
6042 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00006043 if (RecExpr) {
6044 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6045 if (Conv.isInvalid()) // conversion failed. bail.
6046 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006047 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00006048 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00006049 QualType ReceiverType = RecExpr? RecExpr->getType()
6050 : Super? Context.getObjCObjectPointerType(
6051 Context.getObjCInterfaceType(Super))
6052 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00006053
Douglas Gregordc520b02010-11-08 21:12:30 +00006054 // If we're messaging an expression with type "id" or "Class", check
6055 // whether we know something special about the receiver that allows
6056 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00006057 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00006058 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6059 if (ReceiverType->isObjCClassType())
6060 return CodeCompleteObjCClassMessage(S,
6061 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006062 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00006063 AtArgumentExpression, Super);
6064
6065 ReceiverType = Context.getObjCObjectPointerType(
6066 Context.getObjCInterfaceType(IFace));
6067 }
Anders Carlsson382ba412014-02-28 19:07:22 +00006068 } else if (RecExpr && getLangOpts().CPlusPlus) {
6069 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6070 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006071 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00006072 ReceiverType = RecExpr->getType();
6073 }
6074 }
Douglas Gregordc520b02010-11-08 21:12:30 +00006075
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006076 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006077 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006078 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006079 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006080 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006081
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006082 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00006083
Douglas Gregor6fc04132010-08-27 15:10:57 +00006084 // If this is a send-to-super, try to add the special "super" send
6085 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00006086 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00006087 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006088 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00006089 Results.Ignore(SuperMethod);
6090 }
6091
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00006092 // If we're inside an Objective-C method definition, prefer its selector to
6093 // others.
6094 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6095 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006096
Douglas Gregor1154e272010-09-16 16:06:31 +00006097 // Keep track of the selectors we've already added.
6098 VisitedSelectorSet Selectors;
6099
Douglas Gregora3329fa2009-11-18 00:06:18 +00006100 // Handle messages to Class. This really isn't a message to an instance
6101 // method, so we treat it the same way we would treat a message send to a
6102 // class method.
6103 if (ReceiverType->isObjCClassType() ||
6104 ReceiverType->isObjCQualifiedClassType()) {
6105 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6106 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006107 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006108 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006109 }
6110 }
6111 // Handle messages to a qualified ID ("id<foo>").
6112 else if (const ObjCObjectPointerType *QualID
6113 = ReceiverType->getAsObjCQualifiedIdType()) {
6114 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006115 for (auto *I : QualID->quals())
6116 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006117 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006118 }
6119 // Handle messages to a pointer to interface type.
6120 else if (const ObjCObjectPointerType *IFacePtr
6121 = ReceiverType->getAsObjCInterfacePointerType()) {
6122 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00006123 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006124 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006125 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006126
6127 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006128 for (auto *I : IFacePtr->quals())
6129 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006130 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006131 }
Douglas Gregor6285f752010-04-06 16:40:00 +00006132 // Handle messages to "id".
6133 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00006134 // We're messaging "id", so provide all instance methods we know
6135 // about as code-completion results.
6136
6137 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006138 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00006139 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00006140 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6141 I != N; ++I) {
6142 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006143 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00006144 continue;
6145
Sebastian Redl75d8a322010-08-02 23:18:59 +00006146 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00006147 }
6148 }
6149
Sebastian Redl75d8a322010-08-02 23:18:59 +00006150 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6151 MEnd = MethodPool.end();
6152 M != MEnd; ++M) {
6153 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00006154 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006155 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00006156 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00006157 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00006158
Nico Weber2e0c8f72014-12-27 03:58:08 +00006159 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00006160 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00006161
Nico Weber2e0c8f72014-12-27 03:58:08 +00006162 Result R(MethList->getMethod(),
6163 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006164 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006165 R.AllParametersAreInformative = false;
6166 Results.MaybeAddResult(R, CurContext);
6167 }
6168 }
6169 }
Steve Naroffeae65032009-11-07 02:08:14 +00006170 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00006171
6172
6173 // If we're actually at the argument expression (rather than prior to the
6174 // selector), we're actually performing code completion for an expression.
6175 // Determine whether we have a single, best method. If so, we can
6176 // code-complete the expression using the corresponding parameter type as
6177 // our preferred type, improving completion results.
6178 if (AtArgumentExpression) {
6179 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006180 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006181 if (PreferredType.isNull())
6182 CodeCompleteOrdinaryName(S, PCC_Expression);
6183 else
6184 CodeCompleteExpression(S, PreferredType);
6185 return;
6186 }
6187
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006188 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006189 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006190 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006191}
Douglas Gregorbaf69612009-11-18 04:19:12 +00006192
Douglas Gregor68762e72010-08-23 21:17:50 +00006193void Sema::CodeCompleteObjCForCollection(Scope *S,
6194 DeclGroupPtrTy IterationVar) {
6195 CodeCompleteExpressionData Data;
6196 Data.ObjCCollection = true;
6197
6198 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00006199 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00006200 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6201 if (*I)
6202 Data.IgnoreDecls.push_back(*I);
6203 }
6204 }
6205
6206 CodeCompleteExpression(S, Data);
6207}
6208
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006209void Sema::CodeCompleteObjCSelector(Scope *S,
6210 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00006211 // If we have an external source, load the entire class method
6212 // pool from the AST file.
6213 if (ExternalSource) {
6214 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6215 I != N; ++I) {
6216 Selector Sel = ExternalSource->GetExternalSelector(I);
6217 if (Sel.isNull() || MethodPool.count(Sel))
6218 continue;
6219
6220 ReadMethodPool(Sel);
6221 }
6222 }
6223
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006224 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006225 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006226 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00006227 Results.EnterNewScope();
6228 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6229 MEnd = MethodPool.end();
6230 M != MEnd; ++M) {
6231
6232 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006233 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00006234 continue;
6235
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006236 CodeCompletionBuilder Builder(Results.getAllocator(),
6237 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006238 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006239 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006240 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006241 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006242 continue;
6243 }
6244
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006245 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00006246 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006247 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006248 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006249 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006250 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006251 Accumulator.clear();
6252 }
6253 }
6254
Benjamin Kramer632500c2011-07-26 16:59:25 +00006255 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006256 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00006257 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006258 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006259 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006260 }
6261 Results.ExitScope();
6262
6263 HandleCodeCompleteResults(this, CodeCompleter,
6264 CodeCompletionContext::CCC_SelectorName,
6265 Results.data(), Results.size());
6266}
6267
Douglas Gregorbaf69612009-11-18 04:19:12 +00006268/// \brief Add all of the protocol declarations that we find in the given
6269/// (translation unit) context.
6270static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006271 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00006272 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006273 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00006274
Aaron Ballman629afae2014-03-07 19:56:05 +00006275 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00006276 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006277 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00006278 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00006279 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6280 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006281 }
6282}
6283
Craig Topper883dd332015-12-24 23:58:11 +00006284void Sema::CodeCompleteObjCProtocolReferences(
6285 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006286 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006287 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006288 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006289
Chandler Carruthede11632016-11-04 06:06:50 +00006290 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006291 Results.EnterNewScope();
6292
6293 // Tell the result set to ignore all of the protocols we have
6294 // already seen.
6295 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00006296 for (const IdentifierLocPair &Pair : Protocols)
6297 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6298 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00006299 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006300
Douglas Gregora3b23b02010-12-09 21:44:02 +00006301 // Add all protocols.
6302 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6303 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006304
Douglas Gregora3b23b02010-12-09 21:44:02 +00006305 Results.ExitScope();
6306 }
6307
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006308 HandleCodeCompleteResults(this, CodeCompleter,
6309 CodeCompletionContext::CCC_ObjCProtocolName,
6310 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006311}
6312
6313void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006314 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006315 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006316 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006317
Chandler Carruthede11632016-11-04 06:06:50 +00006318 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006319 Results.EnterNewScope();
6320
6321 // Add all protocols.
6322 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6323 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006324
Douglas Gregora3b23b02010-12-09 21:44:02 +00006325 Results.ExitScope();
6326 }
6327
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006328 HandleCodeCompleteResults(this, CodeCompleter,
6329 CodeCompletionContext::CCC_ObjCProtocolName,
6330 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00006331}
Douglas Gregor49c22a72009-11-18 16:26:39 +00006332
6333/// \brief Add all of the Objective-C interface declarations that we find in
6334/// the given (translation unit) context.
6335static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6336 bool OnlyForwardDeclarations,
6337 bool OnlyUnimplemented,
6338 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006339 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00006340
Aaron Ballman629afae2014-03-07 19:56:05 +00006341 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00006342 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006343 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00006344 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00006345 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00006346 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6347 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006348 }
6349}
6350
6351void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006352 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006353 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006354 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006355 Results.EnterNewScope();
6356
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006357 if (CodeCompleter->includeGlobals()) {
6358 // Add all classes.
6359 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6360 false, Results);
6361 }
6362
Douglas Gregor49c22a72009-11-18 16:26:39 +00006363 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006364
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006365 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006366 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006367 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006368}
6369
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006370void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6371 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006372 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006373 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006374 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006375 Results.EnterNewScope();
6376
6377 // Make sure that we ignore the class we're currently defining.
6378 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006379 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006380 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006381 Results.Ignore(CurClass);
6382
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006383 if (CodeCompleter->includeGlobals()) {
6384 // Add all classes.
6385 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6386 false, Results);
6387 }
6388
Douglas Gregor49c22a72009-11-18 16:26:39 +00006389 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006390
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006391 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006392 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006393 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006394}
6395
6396void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006397 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006398 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006399 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006400 Results.EnterNewScope();
6401
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006402 if (CodeCompleter->includeGlobals()) {
6403 // Add all unimplemented classes.
6404 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6405 true, Results);
6406 }
6407
Douglas Gregor49c22a72009-11-18 16:26:39 +00006408 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006409
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006410 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006411 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006412 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006413}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006414
6415void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006416 IdentifierInfo *ClassName,
6417 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006418 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006419
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006420 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006421 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006422 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006423
6424 // Ignore any categories we find that have already been implemented by this
6425 // interface.
6426 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6427 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006428 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006429 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006430 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006431 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006432 }
6433
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006434 // Add all of the categories we know about.
6435 Results.EnterNewScope();
6436 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006437 for (const auto *D : TU->decls())
6438 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006439 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006440 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6441 nullptr),
6442 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006443 Results.ExitScope();
6444
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006445 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006446 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006447 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006448}
6449
6450void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006451 IdentifierInfo *ClassName,
6452 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006453 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006454
6455 // Find the corresponding interface. If we couldn't find the interface, the
6456 // program itself is ill-formed. However, we'll try to be helpful still by
6457 // providing the list of all of the categories we know about.
6458 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006459 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006460 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6461 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006462 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006463
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006464 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006465 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006466 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006467
6468 // Add all of the categories that have have corresponding interface
6469 // declarations in this class and any of its superclasses, except for
6470 // already-implemented categories in the class itself.
6471 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6472 Results.EnterNewScope();
6473 bool IgnoreImplemented = true;
6474 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006475 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006476 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006477 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006478 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6479 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006480 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006481
6482 Class = Class->getSuperClass();
6483 IgnoreImplemented = false;
6484 }
6485 Results.ExitScope();
6486
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006487 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006488 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006489 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006490}
Douglas Gregor5d649882009-11-18 22:32:06 +00006491
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006492void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006493 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006494 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006495 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006496 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006497
6498 // Figure out where this @synthesize lives.
6499 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006500 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006501 if (!Container ||
6502 (!isa<ObjCImplementationDecl>(Container) &&
6503 !isa<ObjCCategoryImplDecl>(Container)))
6504 return;
6505
6506 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006507 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006508 for (const auto *D : Container->decls())
6509 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006510 Results.Ignore(PropertyImpl->getPropertyDecl());
6511
6512 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006513 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006514 Results.EnterNewScope();
6515 if (ObjCImplementationDecl *ClassImpl
6516 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006517 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006518 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006519 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006520 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006521 AddObjCProperties(CCContext,
6522 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006523 false, /*AllowNullaryMethods=*/false, CurContext,
6524 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006525 Results.ExitScope();
6526
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006527 HandleCodeCompleteResults(this, CodeCompleter,
6528 CodeCompletionContext::CCC_Other,
6529 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006530}
6531
6532void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006533 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006534 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006535 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006536 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006537 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006538
6539 // Figure out where this @synthesize lives.
6540 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006541 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006542 if (!Container ||
6543 (!isa<ObjCImplementationDecl>(Container) &&
6544 !isa<ObjCCategoryImplDecl>(Container)))
6545 return;
6546
6547 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006548 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006549 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006550 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006551 Class = ClassImpl->getClassInterface();
6552 else
6553 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6554 ->getClassInterface();
6555
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006556 // Determine the type of the property we're synthesizing.
6557 QualType PropertyType = Context.getObjCIdType();
6558 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006559 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6560 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006561 PropertyType
6562 = Property->getType().getNonReferenceType().getUnqualifiedType();
6563
6564 // Give preference to ivars
6565 Results.setPreferredType(PropertyType);
6566 }
6567 }
6568
Douglas Gregor5d649882009-11-18 22:32:06 +00006569 // Add all of the instance variables in this class and its superclasses.
6570 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006571 bool SawSimilarlyNamedIvar = false;
6572 std::string NameWithPrefix;
6573 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006574 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006575 std::string NameWithSuffix = PropertyName->getName().str();
6576 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006577 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006578 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6579 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006580 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6581 CurContext, nullptr, false);
6582
Douglas Gregor331faa02011-04-18 14:13:53 +00006583 // Determine whether we've seen an ivar with a name similar to the
6584 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006585 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006586 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006587 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006588 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006589
6590 // Reduce the priority of this result by one, to give it a slight
6591 // advantage over other results whose names don't match so closely.
6592 if (Results.size() &&
6593 Results.data()[Results.size() - 1].Kind
6594 == CodeCompletionResult::RK_Declaration &&
6595 Results.data()[Results.size() - 1].Declaration == Ivar)
6596 Results.data()[Results.size() - 1].Priority--;
6597 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006598 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006599 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006600
6601 if (!SawSimilarlyNamedIvar) {
6602 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006603 // an ivar of the appropriate type.
6604 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006605 typedef CodeCompletionResult Result;
6606 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006607 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6608 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006609
Douglas Gregor75acd922011-09-27 23:30:47 +00006610 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006611 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006612 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006613 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6614 Results.AddResult(Result(Builder.TakeString(), Priority,
6615 CXCursor_ObjCIvarDecl));
6616 }
6617
Douglas Gregor5d649882009-11-18 22:32:06 +00006618 Results.ExitScope();
6619
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006620 HandleCodeCompleteResults(this, CodeCompleter,
6621 CodeCompletionContext::CCC_Other,
6622 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006623}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006624
Douglas Gregor416b5752010-08-25 01:08:01 +00006625// Mapping from selectors to the methods that implement that selector, along
6626// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006627typedef llvm::DenseMap<
6628 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006629
6630/// \brief Find all of the methods that reside in the given container
6631/// (and its superclasses, protocols, etc.) that meet the given
6632/// criteria. Insert those methods into the map of known methods,
6633/// indexed by selector so they can be easily found.
6634static void FindImplementableMethods(ASTContext &Context,
6635 ObjCContainerDecl *Container,
6636 bool WantInstanceMethods,
6637 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006638 KnownMethodsMap &KnownMethods,
6639 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006640 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006641 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006642 if (!IFace->hasDefinition())
6643 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006644
6645 IFace = IFace->getDefinition();
6646 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006647
Douglas Gregor636a61e2010-04-07 00:21:17 +00006648 const ObjCList<ObjCProtocolDecl> &Protocols
6649 = IFace->getReferencedProtocols();
6650 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006651 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006652 I != E; ++I)
6653 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006654 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006655
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006656 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006657 for (auto *Cat : IFace->visible_categories()) {
6658 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006659 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006660 }
6661
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006662 // Visit the superclass.
6663 if (IFace->getSuperClass())
6664 FindImplementableMethods(Context, IFace->getSuperClass(),
6665 WantInstanceMethods, ReturnType,
6666 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006667 }
6668
6669 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6670 // Recurse into protocols.
6671 const ObjCList<ObjCProtocolDecl> &Protocols
6672 = Category->getReferencedProtocols();
6673 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006674 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006675 I != E; ++I)
6676 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006677 KnownMethods, InOriginalClass);
6678
6679 // If this category is the original class, jump to the interface.
6680 if (InOriginalClass && Category->getClassInterface())
6681 FindImplementableMethods(Context, Category->getClassInterface(),
6682 WantInstanceMethods, ReturnType, KnownMethods,
6683 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006684 }
6685
6686 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006687 // Make sure we have a definition; that's what we'll walk.
6688 if (!Protocol->hasDefinition())
6689 return;
6690 Protocol = Protocol->getDefinition();
6691 Container = Protocol;
6692
6693 // Recurse into protocols.
6694 const ObjCList<ObjCProtocolDecl> &Protocols
6695 = Protocol->getReferencedProtocols();
6696 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6697 E = Protocols.end();
6698 I != E; ++I)
6699 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6700 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006701 }
6702
6703 // Add methods in this container. This operation occurs last because
6704 // we want the methods from this container to override any methods
6705 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006706 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006707 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006708 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006709 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006710 continue;
6711
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006712 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006713 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006714 }
6715 }
6716}
6717
Douglas Gregor669a25a2011-02-17 00:22:45 +00006718/// \brief Add the parenthesized return or parameter type chunk to a code
6719/// completion string.
6720static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006721 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006722 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006723 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006724 CodeCompletionBuilder &Builder) {
6725 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006726 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006727 if (!Quals.empty())
6728 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006729 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006730 Builder.getAllocator()));
6731 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6732}
6733
6734/// \brief Determine whether the given class is or inherits from a class by
6735/// the given name.
6736static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006737 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006738 if (!Class)
6739 return false;
6740
6741 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6742 return true;
6743
6744 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6745}
6746
6747/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6748/// Key-Value Observing (KVO).
6749static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6750 bool IsInstanceMethod,
6751 QualType ReturnType,
6752 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006753 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006754 ResultBuilder &Results) {
6755 IdentifierInfo *PropName = Property->getIdentifier();
6756 if (!PropName || PropName->getLength() == 0)
6757 return;
6758
Douglas Gregor75acd922011-09-27 23:30:47 +00006759 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6760
Douglas Gregor669a25a2011-02-17 00:22:45 +00006761 // Builder that will create each code completion.
6762 typedef CodeCompletionResult Result;
6763 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006764 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006765
6766 // The selector table.
6767 SelectorTable &Selectors = Context.Selectors;
6768
6769 // The property name, copied into the code completion allocation region
6770 // on demand.
6771 struct KeyHolder {
6772 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006773 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006774 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006775
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006777 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6778
Douglas Gregor669a25a2011-02-17 00:22:45 +00006779 operator const char *() {
6780 if (CopiedKey)
6781 return CopiedKey;
6782
6783 return CopiedKey = Allocator.CopyString(Key);
6784 }
6785 } Key(Allocator, PropName->getName());
6786
6787 // The uppercased name of the property name.
6788 std::string UpperKey = PropName->getName();
6789 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006790 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006791
6792 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6793 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6794 Property->getType());
6795 bool ReturnTypeMatchesVoid
6796 = ReturnType.isNull() || ReturnType->isVoidType();
6797
6798 // Add the normal accessor -(type)key.
6799 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006800 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006801 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6802 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006803 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6804 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006805
6806 Builder.AddTypedTextChunk(Key);
6807 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6808 CXCursor_ObjCInstanceMethodDecl));
6809 }
6810
6811 // If we have an integral or boolean property (or the user has provided
6812 // an integral or boolean return type), add the accessor -(type)isKey.
6813 if (IsInstanceMethod &&
6814 ((!ReturnType.isNull() &&
6815 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6816 (ReturnType.isNull() &&
6817 (Property->getType()->isIntegerType() ||
6818 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006819 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006820 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006821 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6822 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006823 if (ReturnType.isNull()) {
6824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6825 Builder.AddTextChunk("BOOL");
6826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6827 }
6828
6829 Builder.AddTypedTextChunk(
6830 Allocator.CopyString(SelectorId->getName()));
6831 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6832 CXCursor_ObjCInstanceMethodDecl));
6833 }
6834 }
6835
6836 // Add the normal mutator.
6837 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6838 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006839 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006840 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006841 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006842 if (ReturnType.isNull()) {
6843 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6844 Builder.AddTextChunk("void");
6845 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6846 }
6847
6848 Builder.AddTypedTextChunk(
6849 Allocator.CopyString(SelectorId->getName()));
6850 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006851 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6852 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006853 Builder.AddTextChunk(Key);
6854 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6855 CXCursor_ObjCInstanceMethodDecl));
6856 }
6857 }
6858
6859 // Indexed and unordered accessors
6860 unsigned IndexedGetterPriority = CCP_CodePattern;
6861 unsigned IndexedSetterPriority = CCP_CodePattern;
6862 unsigned UnorderedGetterPriority = CCP_CodePattern;
6863 unsigned UnorderedSetterPriority = CCP_CodePattern;
6864 if (const ObjCObjectPointerType *ObjCPointer
6865 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6866 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6867 // If this interface type is not provably derived from a known
6868 // collection, penalize the corresponding completions.
6869 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6870 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6871 if (!InheritsFromClassNamed(IFace, "NSArray"))
6872 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6873 }
6874
6875 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6876 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6877 if (!InheritsFromClassNamed(IFace, "NSSet"))
6878 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6879 }
6880 }
6881 } else {
6882 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6883 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6884 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6885 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6886 }
6887
6888 // Add -(NSUInteger)countOf<key>
6889 if (IsInstanceMethod &&
6890 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006891 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006892 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006893 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6894 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006895 if (ReturnType.isNull()) {
6896 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6897 Builder.AddTextChunk("NSUInteger");
6898 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6899 }
6900
6901 Builder.AddTypedTextChunk(
6902 Allocator.CopyString(SelectorId->getName()));
6903 Results.AddResult(Result(Builder.TakeString(),
6904 std::min(IndexedGetterPriority,
6905 UnorderedGetterPriority),
6906 CXCursor_ObjCInstanceMethodDecl));
6907 }
6908 }
6909
6910 // Indexed getters
6911 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6912 if (IsInstanceMethod &&
6913 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006914 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006915 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006916 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006917 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006918 if (ReturnType.isNull()) {
6919 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6920 Builder.AddTextChunk("id");
6921 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6922 }
6923
6924 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6926 Builder.AddTextChunk("NSUInteger");
6927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6928 Builder.AddTextChunk("index");
6929 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6930 CXCursor_ObjCInstanceMethodDecl));
6931 }
6932 }
6933
6934 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6935 if (IsInstanceMethod &&
6936 (ReturnType.isNull() ||
6937 (ReturnType->isObjCObjectPointerType() &&
6938 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6939 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6940 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006941 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006942 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006943 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006944 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006945 if (ReturnType.isNull()) {
6946 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6947 Builder.AddTextChunk("NSArray *");
6948 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6949 }
6950
6951 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6952 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6953 Builder.AddTextChunk("NSIndexSet *");
6954 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6955 Builder.AddTextChunk("indexes");
6956 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6957 CXCursor_ObjCInstanceMethodDecl));
6958 }
6959 }
6960
6961 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6962 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006963 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006964 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006965 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006966 &Context.Idents.get("range")
6967 };
6968
David Blaikie82e95a32014-11-19 07:49:47 +00006969 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006970 if (ReturnType.isNull()) {
6971 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6972 Builder.AddTextChunk("void");
6973 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6974 }
6975
6976 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6978 Builder.AddPlaceholderChunk("object-type");
6979 Builder.AddTextChunk(" **");
6980 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6981 Builder.AddTextChunk("buffer");
6982 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6983 Builder.AddTypedTextChunk("range:");
6984 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6985 Builder.AddTextChunk("NSRange");
6986 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6987 Builder.AddTextChunk("inRange");
6988 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6989 CXCursor_ObjCInstanceMethodDecl));
6990 }
6991 }
6992
6993 // Mutable indexed accessors
6994
6995 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6996 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006997 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006998 IdentifierInfo *SelectorIds[2] = {
6999 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007000 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007001 };
7002
David Blaikie82e95a32014-11-19 07:49:47 +00007003 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007004 if (ReturnType.isNull()) {
7005 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7006 Builder.AddTextChunk("void");
7007 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7008 }
7009
7010 Builder.AddTypedTextChunk("insertObject:");
7011 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7012 Builder.AddPlaceholderChunk("object-type");
7013 Builder.AddTextChunk(" *");
7014 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7015 Builder.AddTextChunk("object");
7016 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7017 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7018 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7019 Builder.AddPlaceholderChunk("NSUInteger");
7020 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7021 Builder.AddTextChunk("index");
7022 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7023 CXCursor_ObjCInstanceMethodDecl));
7024 }
7025 }
7026
7027 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7028 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007029 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007030 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007031 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007032 &Context.Idents.get("atIndexes")
7033 };
7034
David Blaikie82e95a32014-11-19 07:49:47 +00007035 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007036 if (ReturnType.isNull()) {
7037 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7038 Builder.AddTextChunk("void");
7039 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7040 }
7041
7042 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7043 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7044 Builder.AddTextChunk("NSArray *");
7045 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7046 Builder.AddTextChunk("array");
7047 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7048 Builder.AddTypedTextChunk("atIndexes:");
7049 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7050 Builder.AddPlaceholderChunk("NSIndexSet *");
7051 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7052 Builder.AddTextChunk("indexes");
7053 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7054 CXCursor_ObjCInstanceMethodDecl));
7055 }
7056 }
7057
7058 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7059 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007060 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007061 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007062 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007063 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007064 if (ReturnType.isNull()) {
7065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7066 Builder.AddTextChunk("void");
7067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7068 }
7069
7070 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7072 Builder.AddTextChunk("NSUInteger");
7073 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7074 Builder.AddTextChunk("index");
7075 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7076 CXCursor_ObjCInstanceMethodDecl));
7077 }
7078 }
7079
7080 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7081 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007082 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007083 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007084 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007085 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007086 if (ReturnType.isNull()) {
7087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7088 Builder.AddTextChunk("void");
7089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7090 }
7091
7092 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7093 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7094 Builder.AddTextChunk("NSIndexSet *");
7095 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7096 Builder.AddTextChunk("indexes");
7097 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7098 CXCursor_ObjCInstanceMethodDecl));
7099 }
7100 }
7101
7102 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7103 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007104 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007105 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007106 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007107 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007108 &Context.Idents.get("withObject")
7109 };
7110
David Blaikie82e95a32014-11-19 07:49:47 +00007111 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007112 if (ReturnType.isNull()) {
7113 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7114 Builder.AddTextChunk("void");
7115 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7116 }
7117
7118 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7119 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7120 Builder.AddPlaceholderChunk("NSUInteger");
7121 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7122 Builder.AddTextChunk("index");
7123 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7124 Builder.AddTypedTextChunk("withObject:");
7125 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7126 Builder.AddTextChunk("id");
7127 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7128 Builder.AddTextChunk("object");
7129 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7130 CXCursor_ObjCInstanceMethodDecl));
7131 }
7132 }
7133
7134 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7135 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007136 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007137 = (Twine("replace") + UpperKey + "AtIndexes").str();
7138 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007139 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007140 &Context.Idents.get(SelectorName1),
7141 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007142 };
7143
David Blaikie82e95a32014-11-19 07:49:47 +00007144 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007145 if (ReturnType.isNull()) {
7146 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7147 Builder.AddTextChunk("void");
7148 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7149 }
7150
7151 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7152 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7153 Builder.AddPlaceholderChunk("NSIndexSet *");
7154 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7155 Builder.AddTextChunk("indexes");
7156 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7157 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7158 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7159 Builder.AddTextChunk("NSArray *");
7160 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7161 Builder.AddTextChunk("array");
7162 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7163 CXCursor_ObjCInstanceMethodDecl));
7164 }
7165 }
7166
7167 // Unordered getters
7168 // - (NSEnumerator *)enumeratorOfKey
7169 if (IsInstanceMethod &&
7170 (ReturnType.isNull() ||
7171 (ReturnType->isObjCObjectPointerType() &&
7172 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7173 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7174 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007175 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007176 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007177 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7178 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007179 if (ReturnType.isNull()) {
7180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7181 Builder.AddTextChunk("NSEnumerator *");
7182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7183 }
7184
7185 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7186 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7187 CXCursor_ObjCInstanceMethodDecl));
7188 }
7189 }
7190
7191 // - (type *)memberOfKey:(type *)object
7192 if (IsInstanceMethod &&
7193 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007194 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007195 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007196 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007197 if (ReturnType.isNull()) {
7198 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7199 Builder.AddPlaceholderChunk("object-type");
7200 Builder.AddTextChunk(" *");
7201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7202 }
7203
7204 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7205 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7206 if (ReturnType.isNull()) {
7207 Builder.AddPlaceholderChunk("object-type");
7208 Builder.AddTextChunk(" *");
7209 } else {
7210 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00007211 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00007212 Builder.getAllocator()));
7213 }
7214 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7215 Builder.AddTextChunk("object");
7216 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7217 CXCursor_ObjCInstanceMethodDecl));
7218 }
7219 }
7220
7221 // Mutable unordered accessors
7222 // - (void)addKeyObject:(type *)object
7223 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007224 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007225 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007226 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007227 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007228 if (ReturnType.isNull()) {
7229 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7230 Builder.AddTextChunk("void");
7231 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7232 }
7233
7234 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7235 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7236 Builder.AddPlaceholderChunk("object-type");
7237 Builder.AddTextChunk(" *");
7238 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7239 Builder.AddTextChunk("object");
7240 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7241 CXCursor_ObjCInstanceMethodDecl));
7242 }
7243 }
7244
7245 // - (void)addKey:(NSSet *)objects
7246 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007247 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007248 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007249 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007250 if (ReturnType.isNull()) {
7251 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7252 Builder.AddTextChunk("void");
7253 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7254 }
7255
7256 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7257 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7258 Builder.AddTextChunk("NSSet *");
7259 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7260 Builder.AddTextChunk("objects");
7261 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7262 CXCursor_ObjCInstanceMethodDecl));
7263 }
7264 }
7265
7266 // - (void)removeKeyObject:(type *)object
7267 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007268 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007269 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007270 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007271 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007272 if (ReturnType.isNull()) {
7273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274 Builder.AddTextChunk("void");
7275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276 }
7277
7278 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7280 Builder.AddPlaceholderChunk("object-type");
7281 Builder.AddTextChunk(" *");
7282 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7283 Builder.AddTextChunk("object");
7284 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7285 CXCursor_ObjCInstanceMethodDecl));
7286 }
7287 }
7288
7289 // - (void)removeKey:(NSSet *)objects
7290 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007291 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007292 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007293 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007294 if (ReturnType.isNull()) {
7295 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7296 Builder.AddTextChunk("void");
7297 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7298 }
7299
7300 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7301 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7302 Builder.AddTextChunk("NSSet *");
7303 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7304 Builder.AddTextChunk("objects");
7305 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7306 CXCursor_ObjCInstanceMethodDecl));
7307 }
7308 }
7309
7310 // - (void)intersectKey:(NSSet *)objects
7311 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007312 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007313 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007314 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007315 if (ReturnType.isNull()) {
7316 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7317 Builder.AddTextChunk("void");
7318 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7319 }
7320
7321 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7322 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7323 Builder.AddTextChunk("NSSet *");
7324 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7325 Builder.AddTextChunk("objects");
7326 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7327 CXCursor_ObjCInstanceMethodDecl));
7328 }
7329 }
7330
7331 // Key-Value Observing
7332 // + (NSSet *)keyPathsForValuesAffectingKey
7333 if (!IsInstanceMethod &&
7334 (ReturnType.isNull() ||
7335 (ReturnType->isObjCObjectPointerType() &&
7336 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7337 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7338 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007339 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007340 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007341 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007342 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7343 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007344 if (ReturnType.isNull()) {
7345 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Alex Lorenz71ecb072016-12-08 16:49:05 +00007346 Builder.AddTextChunk("NSSet<NSString *> *");
Douglas Gregor669a25a2011-02-17 00:22:45 +00007347 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7348 }
7349
7350 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7351 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007352 CXCursor_ObjCClassMethodDecl));
7353 }
7354 }
7355
7356 // + (BOOL)automaticallyNotifiesObserversForKey
7357 if (!IsInstanceMethod &&
7358 (ReturnType.isNull() ||
7359 ReturnType->isIntegerType() ||
7360 ReturnType->isBooleanType())) {
7361 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007362 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007363 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007364 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7365 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007366 if (ReturnType.isNull()) {
7367 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7368 Builder.AddTextChunk("BOOL");
7369 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7370 }
7371
7372 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7373 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7374 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007375 }
7376 }
7377}
7378
Douglas Gregor636a61e2010-04-07 00:21:17 +00007379void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7380 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007381 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007382 // Determine the return type of the method we're declaring, if
7383 // provided.
7384 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007385 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007386 if (CurContext->isObjCContainer()) {
7387 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7388 IDecl = cast<Decl>(OCD);
7389 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007390 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007391 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007392 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007393 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007394 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7395 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007396 IsInImplementation = true;
7397 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007398 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007399 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007400 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007401 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007402 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007403 }
7404
7405 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007406 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007407 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007408 }
7409
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007410 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007411 HandleCodeCompleteResults(this, CodeCompleter,
7412 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007413 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007414 return;
7415 }
7416
7417 // Find all of the methods that we could declare/implement here.
7418 KnownMethodsMap KnownMethods;
7419 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007420 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007421
Douglas Gregor636a61e2010-04-07 00:21:17 +00007422 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007423 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007424 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007425 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007426 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007427 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007428 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007429 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7430 MEnd = KnownMethods.end();
7431 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007432 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007433 CodeCompletionBuilder Builder(Results.getAllocator(),
7434 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007435
7436 // If the result type was not already provided, add it to the
7437 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007438 if (ReturnType.isNull()) {
7439 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7440 AttributedType::stripOuterNullability(ResTy);
7441 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007442 Method->getObjCDeclQualifier(), Context, Policy,
7443 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007444 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007445
7446 Selector Sel = Method->getSelector();
7447
7448 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007449 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007450 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007451
7452 // Add parameters to the pattern.
7453 unsigned I = 0;
7454 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7455 PEnd = Method->param_end();
7456 P != PEnd; (void)++P, ++I) {
7457 // Add the part of the selector name.
7458 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007459 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007460 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007461 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7462 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007463 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007464 } else
7465 break;
7466
7467 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007468 QualType ParamType;
7469 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7470 ParamType = (*P)->getType();
7471 else
7472 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007473 ParamType = ParamType.substObjCTypeArgs(Context, {},
7474 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007475 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007476 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007477 (*P)->getObjCDeclQualifier(),
7478 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007479 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007480
7481 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007482 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007483 }
7484
7485 if (Method->isVariadic()) {
7486 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007487 Builder.AddChunk(CodeCompletionString::CK_Comma);
7488 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007489 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007490
Douglas Gregord37c59d2010-05-28 00:57:46 +00007491 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007492 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007493 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7494 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7495 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007496 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007497 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007498 Builder.AddTextChunk("return");
7499 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7500 Builder.AddPlaceholderChunk("expression");
7501 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007502 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007503 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007504
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007505 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7506 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007507 }
7508
Douglas Gregor416b5752010-08-25 01:08:01 +00007509 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007510 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007511 Priority += CCD_InBaseClass;
7512
Douglas Gregor78254c82012-03-27 23:34:16 +00007513 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007514 }
7515
Douglas Gregor669a25a2011-02-17 00:22:45 +00007516 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7517 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007518 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007519 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007520 Containers.push_back(SearchDecl);
7521
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007522 VisitedSelectorSet KnownSelectors;
7523 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7524 MEnd = KnownMethods.end();
7525 M != MEnd; ++M)
7526 KnownSelectors.insert(M->first);
7527
7528
Douglas Gregor669a25a2011-02-17 00:22:45 +00007529 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7530 if (!IFace)
7531 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7532 IFace = Category->getClassInterface();
7533
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007534 if (IFace)
7535 for (auto *Cat : IFace->visible_categories())
7536 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007537
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007538 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007539 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007540 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007541 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007542 }
7543
Douglas Gregor636a61e2010-04-07 00:21:17 +00007544 Results.ExitScope();
7545
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007546 HandleCodeCompleteResults(this, CodeCompleter,
7547 CodeCompletionContext::CCC_Other,
7548 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007549}
Douglas Gregor95887f92010-07-08 23:20:03 +00007550
7551void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7552 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007553 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007554 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007555 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007556 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007557 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007558 if (ExternalSource) {
7559 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7560 I != N; ++I) {
7561 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007562 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007563 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007564
7565 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007566 }
7567 }
7568
7569 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007570 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007571 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007572 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007573 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007574
7575 if (ReturnTy)
7576 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007577
Douglas Gregor95887f92010-07-08 23:20:03 +00007578 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007579 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7580 MEnd = MethodPool.end();
7581 M != MEnd; ++M) {
7582 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7583 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007584 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007585 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007586 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007587 continue;
7588
Douglas Gregor45879692010-07-08 23:37:41 +00007589 if (AtParameterName) {
7590 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007591 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007592 if (NumSelIdents &&
7593 NumSelIdents <= MethList->getMethod()->param_size()) {
7594 ParmVarDecl *Param =
7595 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007596 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007597 CodeCompletionBuilder Builder(Results.getAllocator(),
7598 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007599 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007600 Param->getIdentifier()->getName()));
7601 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007602 }
7603 }
7604
7605 continue;
7606 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007607
Nico Weber2e0c8f72014-12-27 03:58:08 +00007608 Result R(MethList->getMethod(),
7609 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007610 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007611 R.AllParametersAreInformative = false;
7612 R.DeclaringEntity = true;
7613 Results.MaybeAddResult(R, CurContext);
7614 }
7615 }
7616
7617 Results.ExitScope();
Alex Lorenz847fda12017-01-03 11:56:40 +00007618
7619 if (!AtParameterName && !SelIdents.empty() &&
7620 SelIdents.front()->getName().startswith("init")) {
7621 for (const auto &M : PP.macros()) {
7622 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7623 continue;
7624 Results.EnterNewScope();
7625 CodeCompletionBuilder Builder(Results.getAllocator(),
7626 Results.getCodeCompletionTUInfo());
7627 Builder.AddTypedTextChunk(
7628 Builder.getAllocator().CopyString(M.first->getName()));
7629 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7630 CXCursor_MacroDefinition));
7631 Results.ExitScope();
7632 }
7633 }
7634
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007635 HandleCodeCompleteResults(this, CodeCompleter,
7636 CodeCompletionContext::CCC_Other,
7637 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007638}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007639
Douglas Gregorec00a262010-08-24 22:20:20 +00007640void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007641 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007642 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007643 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007644 Results.EnterNewScope();
7645
7646 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007647 CodeCompletionBuilder Builder(Results.getAllocator(),
7648 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007649 Builder.AddTypedTextChunk("if");
7650 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7651 Builder.AddPlaceholderChunk("condition");
7652 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007653
7654 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007655 Builder.AddTypedTextChunk("ifdef");
7656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7657 Builder.AddPlaceholderChunk("macro");
7658 Results.AddResult(Builder.TakeString());
7659
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007660 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007661 Builder.AddTypedTextChunk("ifndef");
7662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7663 Builder.AddPlaceholderChunk("macro");
7664 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007665
7666 if (InConditional) {
7667 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007668 Builder.AddTypedTextChunk("elif");
7669 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7670 Builder.AddPlaceholderChunk("condition");
7671 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007672
7673 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007674 Builder.AddTypedTextChunk("else");
7675 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007676
7677 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007678 Builder.AddTypedTextChunk("endif");
7679 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007680 }
7681
7682 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007683 Builder.AddTypedTextChunk("include");
7684 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7685 Builder.AddTextChunk("\"");
7686 Builder.AddPlaceholderChunk("header");
7687 Builder.AddTextChunk("\"");
7688 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007689
7690 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007691 Builder.AddTypedTextChunk("include");
7692 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7693 Builder.AddTextChunk("<");
7694 Builder.AddPlaceholderChunk("header");
7695 Builder.AddTextChunk(">");
7696 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007697
7698 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007699 Builder.AddTypedTextChunk("define");
7700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7701 Builder.AddPlaceholderChunk("macro");
7702 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007703
7704 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007705 Builder.AddTypedTextChunk("define");
7706 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7707 Builder.AddPlaceholderChunk("macro");
7708 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7709 Builder.AddPlaceholderChunk("args");
7710 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7711 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007712
7713 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007714 Builder.AddTypedTextChunk("undef");
7715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7716 Builder.AddPlaceholderChunk("macro");
7717 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007718
7719 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007720 Builder.AddTypedTextChunk("line");
7721 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7722 Builder.AddPlaceholderChunk("number");
7723 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007724
7725 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007726 Builder.AddTypedTextChunk("line");
7727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7728 Builder.AddPlaceholderChunk("number");
7729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7730 Builder.AddTextChunk("\"");
7731 Builder.AddPlaceholderChunk("filename");
7732 Builder.AddTextChunk("\"");
7733 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007734
7735 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007736 Builder.AddTypedTextChunk("error");
7737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7738 Builder.AddPlaceholderChunk("message");
7739 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007740
7741 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007742 Builder.AddTypedTextChunk("pragma");
7743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7744 Builder.AddPlaceholderChunk("arguments");
7745 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007746
David Blaikiebbafb8a2012-03-11 07:00:24 +00007747 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007748 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007749 Builder.AddTypedTextChunk("import");
7750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7751 Builder.AddTextChunk("\"");
7752 Builder.AddPlaceholderChunk("header");
7753 Builder.AddTextChunk("\"");
7754 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007755
7756 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007757 Builder.AddTypedTextChunk("import");
7758 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7759 Builder.AddTextChunk("<");
7760 Builder.AddPlaceholderChunk("header");
7761 Builder.AddTextChunk(">");
7762 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007763 }
7764
7765 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007766 Builder.AddTypedTextChunk("include_next");
7767 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7768 Builder.AddTextChunk("\"");
7769 Builder.AddPlaceholderChunk("header");
7770 Builder.AddTextChunk("\"");
7771 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007772
7773 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007774 Builder.AddTypedTextChunk("include_next");
7775 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7776 Builder.AddTextChunk("<");
7777 Builder.AddPlaceholderChunk("header");
7778 Builder.AddTextChunk(">");
7779 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007780
7781 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007782 Builder.AddTypedTextChunk("warning");
7783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7784 Builder.AddPlaceholderChunk("message");
7785 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007786
7787 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7788 // completions for them. And __include_macros is a Clang-internal extension
7789 // that we don't want to encourage anyone to use.
7790
7791 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7792 Results.ExitScope();
7793
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007794 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007795 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007796 Results.data(), Results.size());
7797}
7798
7799void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007800 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007801 S->getFnParent()? Sema::PCC_RecoveryInFunction
7802 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007803}
7804
Douglas Gregorec00a262010-08-24 22:20:20 +00007805void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007806 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007807 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007808 IsDefinition? CodeCompletionContext::CCC_MacroName
7809 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007810 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7811 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007812 CodeCompletionBuilder Builder(Results.getAllocator(),
7813 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007814 Results.EnterNewScope();
7815 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7816 MEnd = PP.macro_end();
7817 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007818 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007819 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007820 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7821 CCP_CodePattern,
7822 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007823 }
7824 Results.ExitScope();
7825 } else if (IsDefinition) {
7826 // FIXME: Can we detect when the user just wrote an include guard above?
7827 }
7828
Douglas Gregor0ac41382010-09-23 23:01:17 +00007829 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007830 Results.data(), Results.size());
7831}
7832
Douglas Gregorec00a262010-08-24 22:20:20 +00007833void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007834 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007835 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007836 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007837
7838 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007839 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007840
7841 // defined (<macro>)
7842 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007843 CodeCompletionBuilder Builder(Results.getAllocator(),
7844 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007845 Builder.AddTypedTextChunk("defined");
7846 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7847 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7848 Builder.AddPlaceholderChunk("macro");
7849 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7850 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007851 Results.ExitScope();
7852
7853 HandleCodeCompleteResults(this, CodeCompleter,
7854 CodeCompletionContext::CCC_PreprocessorExpression,
7855 Results.data(), Results.size());
7856}
7857
7858void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7859 IdentifierInfo *Macro,
7860 MacroInfo *MacroInfo,
7861 unsigned Argument) {
7862 // FIXME: In the future, we could provide "overload" results, much like we
7863 // do for function calls.
7864
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007865 // Now just ignore this. There will be another code-completion callback
7866 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007867}
7868
Douglas Gregor11583702010-08-25 17:04:25 +00007869void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007870 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007871 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007872 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007873}
7874
Alex Lorenzf7f6f822017-05-09 16:05:04 +00007875void Sema::CodeCompleteAvailabilityPlatformName() {
7876 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7877 CodeCompleter->getCodeCompletionTUInfo(),
7878 CodeCompletionContext::CCC_Other);
7879 Results.EnterNewScope();
7880 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7881 for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7882 Results.AddResult(CodeCompletionResult(Platform));
7883 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7884 Twine(Platform) + "ApplicationExtension")));
7885 }
7886 Results.ExitScope();
7887 HandleCodeCompleteResults(this, CodeCompleter,
7888 CodeCompletionContext::CCC_Other, Results.data(),
7889 Results.size());
7890}
7891
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007892void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007893 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007894 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007895 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7896 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007897 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7898 CodeCompletionDeclConsumer Consumer(Builder,
7899 Context.getTranslationUnitDecl());
7900 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7901 Consumer);
7902 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007903
7904 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007905 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007906
7907 Results.clear();
7908 Results.insert(Results.end(),
7909 Builder.data(), Builder.data() + Builder.size());
7910}