blob: 94cfc4baca514a23fde62ea93419d11cdeadf8f5 [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 }
1337 }
1338
1339 // GNU extensions
1340 if (LangOpts.GNUMode) {
1341 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001342 // Results.AddResult(Result("_Decimal32"));
1343 // Results.AddResult(Result("_Decimal64"));
1344 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001345
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001346 Builder.AddTypedTextChunk("typeof");
1347 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1348 Builder.AddPlaceholderChunk("expression");
1349 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001350
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001351 Builder.AddTypedTextChunk("typeof");
1352 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1353 Builder.AddPlaceholderChunk("type");
1354 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1355 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001356 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001357
1358 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001359 Results.AddResult(Result("_Nonnull", CCP_Type));
1360 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1361 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001362}
1363
John McCallfaf5fb42010-08-26 23:41:50 +00001364static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001365 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001367 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001368 // Note: we don't suggest either "auto" or "register", because both
1369 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1370 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001371 Results.AddResult(Result("extern"));
1372 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001373}
1374
John McCallfaf5fb42010-08-26 23:41:50 +00001375static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001376 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001377 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001378 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001379 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001380 case Sema::PCC_Class:
1381 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001382 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001383 Results.AddResult(Result("explicit"));
1384 Results.AddResult(Result("friend"));
1385 Results.AddResult(Result("mutable"));
1386 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001387 }
1388 // Fall through
1389
John McCallfaf5fb42010-08-26 23:41:50 +00001390 case Sema::PCC_ObjCInterface:
1391 case Sema::PCC_ObjCImplementation:
1392 case Sema::PCC_Namespace:
1393 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001394 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001395 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001396 break;
1397
John McCallfaf5fb42010-08-26 23:41:50 +00001398 case Sema::PCC_ObjCInstanceVariableList:
1399 case Sema::PCC_Expression:
1400 case Sema::PCC_Statement:
1401 case Sema::PCC_ForInit:
1402 case Sema::PCC_Condition:
1403 case Sema::PCC_RecoveryInFunction:
1404 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001405 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001406 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001407 break;
1408 }
1409}
1410
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001411static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1412static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1413static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001414 ResultBuilder &Results,
1415 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001416static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001417 ResultBuilder &Results,
1418 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001419static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001420 ResultBuilder &Results,
1421 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001422static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001423
Douglas Gregorf4c33342010-05-28 00:22:41 +00001424static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001425 CodeCompletionBuilder Builder(Results.getAllocator(),
1426 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001427 Builder.AddTypedTextChunk("typedef");
1428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1429 Builder.AddPlaceholderChunk("type");
1430 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1431 Builder.AddPlaceholderChunk("name");
1432 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001433}
1434
John McCallfaf5fb42010-08-26 23:41:50 +00001435static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001436 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001437 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001438 case Sema::PCC_Namespace:
1439 case Sema::PCC_Class:
1440 case Sema::PCC_ObjCInstanceVariableList:
1441 case Sema::PCC_Template:
1442 case Sema::PCC_MemberTemplate:
1443 case Sema::PCC_Statement:
1444 case Sema::PCC_RecoveryInFunction:
1445 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001446 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001447 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001448 return true;
1449
John McCallfaf5fb42010-08-26 23:41:50 +00001450 case Sema::PCC_Expression:
1451 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001452 return LangOpts.CPlusPlus;
1453
1454 case Sema::PCC_ObjCInterface:
1455 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001456 return false;
1457
John McCallfaf5fb42010-08-26 23:41:50 +00001458 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001459 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001460 }
David Blaikie8a40f702012-01-17 06:56:22 +00001461
1462 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001463}
1464
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001465static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1466 const Preprocessor &PP) {
1467 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001468 Policy.AnonymousTagLocations = false;
1469 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001470 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001471 return Policy;
1472}
1473
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001474/// \brief Retrieve a printing policy suitable for code completion.
1475static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1476 return getCompletionPrintingPolicy(S.Context, S.PP);
1477}
1478
Douglas Gregore5c79d52011-10-18 21:20:17 +00001479/// \brief Retrieve the string representation of the given type as a string
1480/// that has the appropriate lifetime for code completion.
1481///
1482/// This routine provides a fast path where we provide constant strings for
1483/// common type names.
1484static const char *GetCompletionTypeString(QualType T,
1485 ASTContext &Context,
1486 const PrintingPolicy &Policy,
1487 CodeCompletionAllocator &Allocator) {
1488 if (!T.getLocalQualifiers()) {
1489 // Built-in type names are constant strings.
1490 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001491 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001492
1493 // Anonymous tag types are constant strings.
1494 if (const TagType *TagT = dyn_cast<TagType>(T))
1495 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001496 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001497 switch (Tag->getTagKind()) {
1498 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001499 case TTK_Interface: return "__interface <anonymous>";
1500 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001501 case TTK_Union: return "union <anonymous>";
1502 case TTK_Enum: return "enum <anonymous>";
1503 }
1504 }
1505 }
1506
1507 // Slow path: format the type as a string.
1508 std::string Result;
1509 T.getAsStringInternal(Result, Policy);
1510 return Allocator.CopyString(Result);
1511}
1512
Douglas Gregord8c61782012-02-15 15:34:24 +00001513/// \brief Add a completion for "this", if we're in a member function.
1514static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1515 QualType ThisTy = S.getCurrentThisType();
1516 if (ThisTy.isNull())
1517 return;
1518
1519 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001520 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001521 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1522 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1523 S.Context,
1524 Policy,
1525 Allocator));
1526 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001527 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001528}
1529
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001530/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001531static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001532 Scope *S,
1533 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001534 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001535 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001536 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001537
John McCall276321a2010-08-25 06:19:51 +00001538 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001539 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001540 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001541 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001542 if (Results.includeCodePatterns()) {
1543 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001544 Builder.AddTypedTextChunk("namespace");
1545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1546 Builder.AddPlaceholderChunk("identifier");
1547 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1548 Builder.AddPlaceholderChunk("declarations");
1549 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1550 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1551 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001552 }
1553
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001554 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001555 Builder.AddTypedTextChunk("namespace");
1556 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1557 Builder.AddPlaceholderChunk("name");
1558 Builder.AddChunk(CodeCompletionString::CK_Equal);
1559 Builder.AddPlaceholderChunk("namespace");
1560 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001561
1562 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001563 Builder.AddTypedTextChunk("using");
1564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1565 Builder.AddTextChunk("namespace");
1566 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1567 Builder.AddPlaceholderChunk("identifier");
1568 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001569
1570 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001571 Builder.AddTypedTextChunk("asm");
1572 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1573 Builder.AddPlaceholderChunk("string-literal");
1574 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1575 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001576
Douglas Gregorf4c33342010-05-28 00:22:41 +00001577 if (Results.includeCodePatterns()) {
1578 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001579 Builder.AddTypedTextChunk("template");
1580 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1581 Builder.AddPlaceholderChunk("declaration");
1582 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001583 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001584 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001585
David Blaikiebbafb8a2012-03-11 07:00:24 +00001586 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001587 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001588
Douglas Gregorf4c33342010-05-28 00:22:41 +00001589 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001590 // Fall through
1591
John McCallfaf5fb42010-08-26 23:41:50 +00001592 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001593 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001594 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001595 Builder.AddTypedTextChunk("using");
1596 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1597 Builder.AddPlaceholderChunk("qualifier");
1598 Builder.AddTextChunk("::");
1599 Builder.AddPlaceholderChunk("name");
1600 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001601
Douglas Gregorf4c33342010-05-28 00:22:41 +00001602 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001603 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001604 Builder.AddTypedTextChunk("using");
1605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1606 Builder.AddTextChunk("typename");
1607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1608 Builder.AddPlaceholderChunk("qualifier");
1609 Builder.AddTextChunk("::");
1610 Builder.AddPlaceholderChunk("name");
1611 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001612 }
1613
John McCallfaf5fb42010-08-26 23:41:50 +00001614 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001615 AddTypedefResult(Results);
1616
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001617 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001618 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001619 if (Results.includeCodePatterns())
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001621 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001622
1623 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001624 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001625 if (Results.includeCodePatterns())
1626 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001627 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001628
1629 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001630 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001631 if (Results.includeCodePatterns())
1632 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001633 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001634 }
1635 }
1636 // Fall through
1637
John McCallfaf5fb42010-08-26 23:41:50 +00001638 case Sema::PCC_Template:
1639 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001640 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001641 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001642 Builder.AddTypedTextChunk("template");
1643 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1644 Builder.AddPlaceholderChunk("parameters");
1645 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1646 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001647 }
1648
David Blaikiebbafb8a2012-03-11 07:00:24 +00001649 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1650 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001651 break;
1652
John McCallfaf5fb42010-08-26 23:41:50 +00001653 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001654 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1655 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1656 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001657 break;
1658
John McCallfaf5fb42010-08-26 23:41:50 +00001659 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1661 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1662 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001663 break;
1664
John McCallfaf5fb42010-08-26 23:41:50 +00001665 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001666 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001667 break;
1668
John McCallfaf5fb42010-08-26 23:41:50 +00001669 case Sema::PCC_RecoveryInFunction:
1670 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001671 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001672
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1674 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001675 Builder.AddTypedTextChunk("try");
1676 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1677 Builder.AddPlaceholderChunk("statements");
1678 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1679 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1680 Builder.AddTextChunk("catch");
1681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1682 Builder.AddPlaceholderChunk("declaration");
1683 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1684 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1685 Builder.AddPlaceholderChunk("statements");
1686 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1687 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1688 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001689 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001690 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001691 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001692
Douglas Gregorf64acca2010-05-25 21:41:55 +00001693 if (Results.includeCodePatterns()) {
1694 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001695 Builder.AddTypedTextChunk("if");
1696 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001697 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001698 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001699 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001700 Builder.AddPlaceholderChunk("expression");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1703 Builder.AddPlaceholderChunk("statements");
1704 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1705 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1706 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001707
Douglas Gregorf64acca2010-05-25 21:41:55 +00001708 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001709 Builder.AddTypedTextChunk("switch");
1710 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001711 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001712 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001713 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001714 Builder.AddPlaceholderChunk("expression");
1715 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1716 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1717 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1718 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1719 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001720 }
1721
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001722 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001723 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001724 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001725 Builder.AddTypedTextChunk("case");
1726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1727 Builder.AddPlaceholderChunk("expression");
1728 Builder.AddChunk(CodeCompletionString::CK_Colon);
1729 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001730
1731 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001732 Builder.AddTypedTextChunk("default");
1733 Builder.AddChunk(CodeCompletionString::CK_Colon);
1734 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001735 }
1736
Douglas Gregorf64acca2010-05-25 21:41:55 +00001737 if (Results.includeCodePatterns()) {
1738 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001739 Builder.AddTypedTextChunk("while");
1740 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001741 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001742 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001743 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001744 Builder.AddPlaceholderChunk("expression");
1745 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1746 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1747 Builder.AddPlaceholderChunk("statements");
1748 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1749 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1750 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001751
1752 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddTypedTextChunk("do");
1754 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1755 Builder.AddPlaceholderChunk("statements");
1756 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1757 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1758 Builder.AddTextChunk("while");
1759 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1760 Builder.AddPlaceholderChunk("expression");
1761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1762 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001763
Douglas Gregorf64acca2010-05-25 21:41:55 +00001764 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001765 Builder.AddTypedTextChunk("for");
1766 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001767 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001768 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001769 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001770 Builder.AddPlaceholderChunk("init-expression");
1771 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1772 Builder.AddPlaceholderChunk("condition");
1773 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1774 Builder.AddPlaceholderChunk("inc-expression");
1775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1776 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1777 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1778 Builder.AddPlaceholderChunk("statements");
1779 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1780 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1781 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001782 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001783
1784 if (S->getContinueParent()) {
1785 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001786 Builder.AddTypedTextChunk("continue");
1787 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001788 }
1789
1790 if (S->getBreakParent()) {
1791 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001792 Builder.AddTypedTextChunk("break");
1793 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001794 }
1795
1796 // "return expression ;" or "return ;", depending on whether we
1797 // know the function is void or not.
1798 bool isVoid = false;
1799 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001800 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001801 else if (ObjCMethodDecl *Method
1802 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001803 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001804 else if (SemaRef.getCurBlock() &&
1805 !SemaRef.getCurBlock()->ReturnType.isNull())
1806 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001807 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001808 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1810 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001811 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001812 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001813
Douglas Gregorf4c33342010-05-28 00:22:41 +00001814 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001815 Builder.AddTypedTextChunk("goto");
1816 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1817 Builder.AddPlaceholderChunk("label");
1818 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001819
Douglas Gregorf4c33342010-05-28 00:22:41 +00001820 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001821 Builder.AddTypedTextChunk("using");
1822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1823 Builder.AddTextChunk("namespace");
1824 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1825 Builder.AddPlaceholderChunk("identifier");
1826 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001827 }
1828
1829 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001830 case Sema::PCC_ForInit:
1831 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001832 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001833 // Fall through: conditions and statements can have expressions.
1834
Douglas Gregor5e35d592010-09-14 23:59:36 +00001835 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001836 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001837 CCC == Sema::PCC_ParenthesizedExpression) {
1838 // (__bridge <type>)<expression>
1839 Builder.AddTypedTextChunk("__bridge");
1840 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1841 Builder.AddPlaceholderChunk("type");
1842 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1843 Builder.AddPlaceholderChunk("expression");
1844 Results.AddResult(Result(Builder.TakeString()));
1845
1846 // (__bridge_transfer <Objective-C type>)<expression>
1847 Builder.AddTypedTextChunk("__bridge_transfer");
1848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1849 Builder.AddPlaceholderChunk("Objective-C type");
1850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1851 Builder.AddPlaceholderChunk("expression");
1852 Results.AddResult(Result(Builder.TakeString()));
1853
1854 // (__bridge_retained <CF type>)<expression>
1855 Builder.AddTypedTextChunk("__bridge_retained");
1856 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1857 Builder.AddPlaceholderChunk("CF type");
1858 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1859 Builder.AddPlaceholderChunk("expression");
1860 Results.AddResult(Result(Builder.TakeString()));
1861 }
1862 // Fall through
1863
John McCallfaf5fb42010-08-26 23:41:50 +00001864 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001865 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001866 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001867 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001868
Douglas Gregore5c79d52011-10-18 21:20:17 +00001869 // true
1870 Builder.AddResultTypeChunk("bool");
1871 Builder.AddTypedTextChunk("true");
1872 Results.AddResult(Result(Builder.TakeString()));
1873
1874 // false
1875 Builder.AddResultTypeChunk("bool");
1876 Builder.AddTypedTextChunk("false");
1877 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001878
David Blaikiebbafb8a2012-03-11 07:00:24 +00001879 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001880 // dynamic_cast < type-id > ( expression )
1881 Builder.AddTypedTextChunk("dynamic_cast");
1882 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1883 Builder.AddPlaceholderChunk("type");
1884 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1885 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1886 Builder.AddPlaceholderChunk("expression");
1887 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1888 Results.AddResult(Result(Builder.TakeString()));
1889 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001890
1891 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001892 Builder.AddTypedTextChunk("static_cast");
1893 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1894 Builder.AddPlaceholderChunk("type");
1895 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1896 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1897 Builder.AddPlaceholderChunk("expression");
1898 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1899 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001900
Douglas Gregorf4c33342010-05-28 00:22:41 +00001901 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001902 Builder.AddTypedTextChunk("reinterpret_cast");
1903 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1904 Builder.AddPlaceholderChunk("type");
1905 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1906 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1907 Builder.AddPlaceholderChunk("expression");
1908 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1909 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001910
Douglas Gregorf4c33342010-05-28 00:22:41 +00001911 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001912 Builder.AddTypedTextChunk("const_cast");
1913 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1914 Builder.AddPlaceholderChunk("type");
1915 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1916 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1917 Builder.AddPlaceholderChunk("expression");
1918 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1919 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001920
David Blaikiebbafb8a2012-03-11 07:00:24 +00001921 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001922 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001923 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001924 Builder.AddTypedTextChunk("typeid");
1925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1926 Builder.AddPlaceholderChunk("expression-or-type");
1927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1928 Results.AddResult(Result(Builder.TakeString()));
1929 }
1930
Douglas Gregorf4c33342010-05-28 00:22:41 +00001931 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001932 Builder.AddTypedTextChunk("new");
1933 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1934 Builder.AddPlaceholderChunk("type");
1935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1936 Builder.AddPlaceholderChunk("expressions");
1937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1938 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001939
Douglas Gregorf4c33342010-05-28 00:22:41 +00001940 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001941 Builder.AddTypedTextChunk("new");
1942 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1943 Builder.AddPlaceholderChunk("type");
1944 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1945 Builder.AddPlaceholderChunk("size");
1946 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1948 Builder.AddPlaceholderChunk("expressions");
1949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1950 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001951
Douglas Gregorf4c33342010-05-28 00:22:41 +00001952 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001953 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001954 Builder.AddTypedTextChunk("delete");
1955 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1956 Builder.AddPlaceholderChunk("expression");
1957 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001958
Douglas Gregorf4c33342010-05-28 00:22:41 +00001959 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001960 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001961 Builder.AddTypedTextChunk("delete");
1962 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1963 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1964 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1965 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1966 Builder.AddPlaceholderChunk("expression");
1967 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001968
David Blaikiebbafb8a2012-03-11 07:00:24 +00001969 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001970 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001971 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001972 Builder.AddTypedTextChunk("throw");
1973 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1974 Builder.AddPlaceholderChunk("expression");
1975 Results.AddResult(Result(Builder.TakeString()));
1976 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001977
Douglas Gregora2db7932010-05-26 22:00:08 +00001978 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001979
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001980 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001981 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001982 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001983 Builder.AddTypedTextChunk("nullptr");
1984 Results.AddResult(Result(Builder.TakeString()));
1985
1986 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001987 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001988 Builder.AddTypedTextChunk("alignof");
1989 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1990 Builder.AddPlaceholderChunk("type");
1991 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1992 Results.AddResult(Result(Builder.TakeString()));
1993
1994 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001995 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001996 Builder.AddTypedTextChunk("noexcept");
1997 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1998 Builder.AddPlaceholderChunk("expression");
1999 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2000 Results.AddResult(Result(Builder.TakeString()));
2001
2002 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002003 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002004 Builder.AddTypedTextChunk("sizeof...");
2005 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2006 Builder.AddPlaceholderChunk("parameter-pack");
2007 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2008 Results.AddResult(Result(Builder.TakeString()));
2009 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002010 }
2011
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002013 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00002014 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2015 // The interface can be NULL.
2016 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002017 if (ID->getSuperClass()) {
2018 std::string SuperType;
2019 SuperType = ID->getSuperClass()->getNameAsString();
2020 if (Method->isInstanceMethod())
2021 SuperType += " *";
2022
2023 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2024 Builder.AddTypedTextChunk("super");
2025 Results.AddResult(Result(Builder.TakeString()));
2026 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002027 }
2028
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002029 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002030 }
2031
Jordan Rose58d54722012-06-30 21:33:57 +00002032 if (SemaRef.getLangOpts().C11) {
2033 // _Alignof
2034 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002035 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002036 Builder.AddTypedTextChunk("alignof");
2037 else
2038 Builder.AddTypedTextChunk("_Alignof");
2039 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2040 Builder.AddPlaceholderChunk("type");
2041 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2042 Results.AddResult(Result(Builder.TakeString()));
2043 }
2044
Douglas Gregorf4c33342010-05-28 00:22:41 +00002045 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002046 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002047 Builder.AddTypedTextChunk("sizeof");
2048 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2049 Builder.AddPlaceholderChunk("expression-or-type");
2050 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2051 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002052 break;
2053 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002054
John McCallfaf5fb42010-08-26 23:41:50 +00002055 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002056 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002057 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002058 }
2059
David Blaikiebbafb8a2012-03-11 07:00:24 +00002060 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2061 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002062
David Blaikiebbafb8a2012-03-11 07:00:24 +00002063 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002064 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002065}
2066
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002067/// \brief If the given declaration has an associated type, add it as a result
2068/// type chunk.
2069static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002070 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002071 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002072 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002073 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002074 if (!ND)
2075 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002076
2077 // Skip constructors and conversion functions, which have their return types
2078 // built into their names.
2079 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2080 return;
2081
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002082 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002083 QualType T;
2084 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002085 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002086 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2087 if (!BaseType.isNull())
2088 T = Method->getSendResultType(BaseType);
2089 else
2090 T = Method->getReturnType();
2091 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002092 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2093 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2094 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002095 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2096 if (!BaseType.isNull())
2097 T = Ivar->getUsageType(BaseType);
2098 else
2099 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002100 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002101 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002102 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2103 if (!BaseType.isNull())
2104 T = Property->getUsageType(BaseType);
2105 else
2106 T = Property->getType();
2107 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002108
2109 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2110 return;
2111
Douglas Gregor75acd922011-09-27 23:30:47 +00002112 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002113 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002114}
2115
Richard Smith20e883e2015-04-29 23:20:19 +00002116static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002117 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002118 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002119 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2120 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002121 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002122 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002123 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002124 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002125 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002126 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002127 }
2128}
2129
Douglas Gregor86b42682015-06-19 18:27:52 +00002130static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2131 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002132 std::string Result;
2133 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002134 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002135 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002136 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002137 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002138 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002139 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002140 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002141 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002142 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002143 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002144 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002145 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2146 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2147 switch (*nullability) {
2148 case NullabilityKind::NonNull:
2149 Result += "nonnull ";
2150 break;
2151
2152 case NullabilityKind::Nullable:
2153 Result += "nullable ";
2154 break;
2155
2156 case NullabilityKind::Unspecified:
2157 Result += "null_unspecified ";
2158 break;
2159 }
2160 }
2161 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002162 return Result;
2163}
2164
Alex Lorenza1951202016-10-18 10:35:27 +00002165/// \brief Tries to find the most appropriate type location for an Objective-C
2166/// block placeholder.
2167///
2168/// This function ignores things like typedefs and qualifiers in order to
2169/// present the most relevant and accurate block placeholders in code completion
2170/// results.
2171static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2172 FunctionTypeLoc &Block,
2173 FunctionProtoTypeLoc &BlockProto,
2174 bool SuppressBlock = false) {
2175 if (!TSInfo)
2176 return;
2177 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2178 while (true) {
2179 // Look through typedefs.
2180 if (!SuppressBlock) {
2181 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2182 if (TypeSourceInfo *InnerTSInfo =
2183 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2184 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2185 continue;
2186 }
2187 }
2188
2189 // Look through qualified types
2190 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2191 TL = QualifiedTL.getUnqualifiedLoc();
2192 continue;
2193 }
2194
2195 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2196 TL = AttrTL.getModifiedLoc();
2197 continue;
2198 }
2199 }
2200
2201 // Try to get the function prototype behind the block pointer type,
2202 // then we're done.
2203 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2204 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2205 Block = TL.getAs<FunctionTypeLoc>();
2206 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2207 }
2208 break;
2209 }
2210}
2211
Alex Lorenz920ae142016-10-18 10:38:58 +00002212static std::string
2213formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2214 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002215 bool SuppressBlockName = false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002216 bool SuppressBlock = false,
2217 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2218
Richard Smith20e883e2015-04-29 23:20:19 +00002219static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002220 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002221 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002222 bool SuppressBlock = false,
2223 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002224 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2225 if (Param->getType()->isDependentType() ||
2226 !Param->getType()->isBlockPointerType()) {
2227 // The argument for a dependent or non-block parameter is a placeholder
2228 // containing that parameter's type.
2229 std::string Result;
2230
Douglas Gregor981a0c42010-08-29 19:47:46 +00002231 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002232 Result = Param->getIdentifier()->getName();
2233
Douglas Gregor86b42682015-06-19 18:27:52 +00002234 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002235 if (ObjCSubsts)
2236 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2237 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002238 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002239 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2240 Type);
2241 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002242 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002243 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002244 } else {
2245 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002246 }
2247 return Result;
2248 }
Alex Lorenza1951202016-10-18 10:35:27 +00002249
Douglas Gregore90dd002010-08-24 16:15:59 +00002250 // The argument for a block pointer parameter is a block literal with
2251 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002252 FunctionTypeLoc Block;
2253 FunctionProtoTypeLoc BlockProto;
Alex Lorenza1951202016-10-18 10:35:27 +00002254 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2255 SuppressBlock);
Douglas Gregore90dd002010-08-24 16:15:59 +00002256
2257 if (!Block) {
2258 // We were unable to find a FunctionProtoTypeLoc with parameter names
2259 // for the block; just use the parameter type as a placeholder.
2260 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002261 if (!ObjCMethodParam && Param->getIdentifier())
2262 Result = Param->getIdentifier()->getName();
2263
Douglas Gregor86b42682015-06-19 18:27:52 +00002264 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002265
2266 if (ObjCMethodParam) {
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002267 Result = Type.getAsString(Policy);
2268 std::string Quals =
2269 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2270 if (!Quals.empty())
2271 Result = "(" + Quals + " " + Result + ")";
2272 if (Result.back() != ')')
2273 Result += " ";
Douglas Gregore90dd002010-08-24 16:15:59 +00002274 if (Param->getIdentifier())
2275 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002276 } else {
2277 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002278 }
2279
2280 return Result;
2281 }
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002282
Douglas Gregore90dd002010-08-24 16:15:59 +00002283 // We have the function prototype behind the block pointer type, as it was
2284 // written in the source.
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002285 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2286 /*SuppressBlockName=*/false, SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002287 ObjCSubsts);
2288}
2289
2290/// \brief Returns a placeholder string that corresponds to an Objective-C block
2291/// declaration.
2292///
2293/// \param BlockDecl A declaration with an Objective-C block type.
2294///
2295/// \param Block The most relevant type location for that block type.
2296///
2297/// \param SuppressBlockName Determines wether or not the name of the block
2298/// declaration is included in the resulting string.
2299static std::string
2300formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2301 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002302 bool SuppressBlockName, bool SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002303 Optional<ArrayRef<QualType>> ObjCSubsts) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002304 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002305 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002306 if (ObjCSubsts)
Alex Lorenz920ae142016-10-18 10:38:58 +00002307 ResultType =
2308 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2309 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002310 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002311 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002312
2313 // Format the parameter list.
2314 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002315 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002316 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002317 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002318 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002319 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002320 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002321 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002322 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002323 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002324 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002325 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002326 /*SuppressName=*/false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002327 /*SuppressBlock=*/true, ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002328
David Blaikie6adc78e2013-02-18 22:06:02 +00002329 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002330 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002331 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002332 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002333 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002334
Douglas Gregord793e7c2011-10-18 04:23:19 +00002335 if (SuppressBlock) {
2336 // Format as a parameter.
2337 Result = Result + " (^";
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002338 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002339 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002340 Result += ")";
2341 Result += Params;
2342 } else {
2343 // Format as a block literal argument.
2344 Result = '^' + Result;
2345 Result += Params;
Alex Lorenz920ae142016-10-18 10:38:58 +00002346
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002347 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002348 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002349 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002350
Douglas Gregore90dd002010-08-24 16:15:59 +00002351 return Result;
2352}
2353
Douglas Gregor3545ff42009-09-21 16:56:56 +00002354/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002355static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002356 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002357 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002358 CodeCompletionBuilder &Result,
2359 unsigned Start = 0,
2360 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002361 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002362
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002363 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002364 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002365
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002366 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002367 // When we see an optional default argument, put that argument and
2368 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002369 CodeCompletionBuilder Opt(Result.getAllocator(),
2370 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002371 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002372 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002373 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002374 Result.AddOptionalChunk(Opt.TakeString());
2375 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002376 }
2377
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002378 if (FirstParameter)
2379 FirstParameter = false;
2380 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002381 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002382
2383 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002384
2385 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002386 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2387
Douglas Gregor400f5972010-08-31 05:13:43 +00002388 if (Function->isVariadic() && P == N - 1)
2389 PlaceholderStr += ", ...";
2390
Douglas Gregor3545ff42009-09-21 16:56:56 +00002391 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002392 Result.AddPlaceholderChunk(
2393 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002394 }
Douglas Gregorba449032009-09-22 21:42:17 +00002395
2396 if (const FunctionProtoType *Proto
2397 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002398 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002399 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002400 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002401
Richard Smith20e883e2015-04-29 23:20:19 +00002402 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002403 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002404}
2405
2406/// \brief Add template parameter chunks to the given code completion string.
2407static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002408 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002409 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002410 CodeCompletionBuilder &Result,
2411 unsigned MaxParameters = 0,
2412 unsigned Start = 0,
2413 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002414 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002415
2416 // Prefer to take the template parameter names from the first declaration of
2417 // the template.
2418 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2419
Douglas Gregor3545ff42009-09-21 16:56:56 +00002420 TemplateParameterList *Params = Template->getTemplateParameters();
2421 TemplateParameterList::iterator PEnd = Params->end();
2422 if (MaxParameters)
2423 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002424 for (TemplateParameterList::iterator P = Params->begin() + Start;
2425 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002426 bool HasDefaultArg = false;
2427 std::string PlaceholderStr;
2428 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2429 if (TTP->wasDeclaredWithTypename())
2430 PlaceholderStr = "typename";
2431 else
2432 PlaceholderStr = "class";
2433
2434 if (TTP->getIdentifier()) {
2435 PlaceholderStr += ' ';
2436 PlaceholderStr += TTP->getIdentifier()->getName();
2437 }
2438
2439 HasDefaultArg = TTP->hasDefaultArgument();
2440 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002441 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002442 if (NTTP->getIdentifier())
2443 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002444 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002445 HasDefaultArg = NTTP->hasDefaultArgument();
2446 } else {
2447 assert(isa<TemplateTemplateParmDecl>(*P));
2448 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2449
2450 // Since putting the template argument list into the placeholder would
2451 // be very, very long, we just use an abbreviation.
2452 PlaceholderStr = "template<...> class";
2453 if (TTP->getIdentifier()) {
2454 PlaceholderStr += ' ';
2455 PlaceholderStr += TTP->getIdentifier()->getName();
2456 }
2457
2458 HasDefaultArg = TTP->hasDefaultArgument();
2459 }
2460
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002461 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002462 // When we see an optional default argument, put that argument and
2463 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002464 CodeCompletionBuilder Opt(Result.getAllocator(),
2465 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002466 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002467 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002468 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002469 P - Params->begin(), true);
2470 Result.AddOptionalChunk(Opt.TakeString());
2471 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002472 }
2473
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002474 InDefaultArg = false;
2475
Douglas Gregor3545ff42009-09-21 16:56:56 +00002476 if (FirstParameter)
2477 FirstParameter = false;
2478 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002479 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002480
2481 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002482 Result.AddPlaceholderChunk(
2483 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002484 }
2485}
2486
Douglas Gregorf2510672009-09-21 19:57:38 +00002487/// \brief Add a qualifier to the given code-completion string, if the
2488/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002489static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002490AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002491 NestedNameSpecifier *Qualifier,
2492 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002493 ASTContext &Context,
2494 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002495 if (!Qualifier)
2496 return;
2497
2498 std::string PrintedNNS;
2499 {
2500 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002501 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002502 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002503 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002504 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002505 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002506 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002507}
2508
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002509static void
2510AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002511 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002512 const FunctionProtoType *Proto
2513 = Function->getType()->getAs<FunctionProtoType>();
2514 if (!Proto || !Proto->getTypeQuals())
2515 return;
2516
Douglas Gregor304f9b02011-02-01 21:15:40 +00002517 // FIXME: Add ref-qualifier!
2518
2519 // Handle single qualifiers without copying
2520 if (Proto->getTypeQuals() == Qualifiers::Const) {
2521 Result.AddInformativeChunk(" const");
2522 return;
2523 }
2524
2525 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2526 Result.AddInformativeChunk(" volatile");
2527 return;
2528 }
2529
2530 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2531 Result.AddInformativeChunk(" restrict");
2532 return;
2533 }
2534
2535 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002536 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002537 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002538 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002539 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002540 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002541 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002542 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002543 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002544}
2545
Douglas Gregor0212fd72010-09-21 16:06:22 +00002546/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002547static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002548 const NamedDecl *ND,
2549 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002550 DeclarationName Name = ND->getDeclName();
2551 if (!Name)
2552 return;
2553
2554 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002555 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002556 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002557 switch (Name.getCXXOverloadedOperator()) {
2558 case OO_None:
2559 case OO_Conditional:
2560 case NUM_OVERLOADED_OPERATORS:
2561 OperatorName = "operator";
2562 break;
2563
2564#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2565 case OO_##Name: OperatorName = "operator" Spelling; break;
2566#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2567#include "clang/Basic/OperatorKinds.def"
2568
2569 case OO_New: OperatorName = "operator new"; break;
2570 case OO_Delete: OperatorName = "operator delete"; break;
2571 case OO_Array_New: OperatorName = "operator new[]"; break;
2572 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2573 case OO_Call: OperatorName = "operator()"; break;
2574 case OO_Subscript: OperatorName = "operator[]"; break;
2575 }
2576 Result.AddTypedTextChunk(OperatorName);
2577 break;
2578 }
2579
Douglas Gregor0212fd72010-09-21 16:06:22 +00002580 case DeclarationName::Identifier:
2581 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002582 case DeclarationName::CXXDestructorName:
2583 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002584 Result.AddTypedTextChunk(
2585 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002586 break;
2587
2588 case DeclarationName::CXXUsingDirective:
2589 case DeclarationName::ObjCZeroArgSelector:
2590 case DeclarationName::ObjCOneArgSelector:
2591 case DeclarationName::ObjCMultiArgSelector:
2592 break;
2593
2594 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002595 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002596 QualType Ty = Name.getCXXNameType();
2597 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2598 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2599 else if (const InjectedClassNameType *InjectedTy
2600 = Ty->getAs<InjectedClassNameType>())
2601 Record = InjectedTy->getDecl();
2602 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002603 Result.AddTypedTextChunk(
2604 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002605 break;
2606 }
2607
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002608 Result.AddTypedTextChunk(
2609 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002610 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002611 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002612 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002613 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002614 }
2615 break;
2616 }
2617 }
2618}
2619
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002620CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002621 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002622 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002623 CodeCompletionTUInfo &CCTUInfo,
2624 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002625 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2626 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002627}
2628
Douglas Gregor3545ff42009-09-21 16:56:56 +00002629/// \brief If possible, create a new code completion string for the given
2630/// result.
2631///
2632/// \returns Either a new, heap-allocated code completion string describing
2633/// how to use this result, or NULL to indicate that the string or name of the
2634/// result is all that is needed.
2635CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002636CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2637 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002638 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002639 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002640 CodeCompletionTUInfo &CCTUInfo,
2641 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002642 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002643
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002644 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002645 if (Kind == RK_Pattern) {
2646 Pattern->Priority = Priority;
2647 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002648
2649 if (Declaration) {
2650 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002651 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002652 // Provide code completion comment for self.GetterName where
2653 // GetterName is the getter method for a property with name
2654 // different from the property name (declared via a property
2655 // getter attribute.
2656 const NamedDecl *ND = Declaration;
2657 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2658 if (M->isPropertyAccessor())
2659 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2660 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002661 PDecl->getIdentifier() != M->getIdentifier()) {
2662 if (const RawComment *RC =
2663 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002664 Result.addBriefComment(RC->getBriefText(Ctx));
2665 Pattern->BriefComment = Result.getBriefComment();
2666 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002667 else if (const RawComment *RC =
2668 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2669 Result.addBriefComment(RC->getBriefText(Ctx));
2670 Pattern->BriefComment = Result.getBriefComment();
2671 }
2672 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002673 }
2674
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002675 return Pattern;
2676 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002677
Douglas Gregorf09935f2009-12-01 05:55:20 +00002678 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002679 Result.AddTypedTextChunk(Keyword);
2680 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002681 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002682
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002683 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002684 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002685 Result.AddTypedTextChunk(
2686 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002687
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002688 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002689 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002690
2691 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002692 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002693 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002694
2695 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2696 if (MI->isC99Varargs()) {
2697 --AEnd;
2698
2699 if (A == AEnd) {
2700 Result.AddPlaceholderChunk("...");
2701 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002702 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002703
Douglas Gregor0c505312011-07-30 08:17:44 +00002704 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002705 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002706 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002707
2708 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002709 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002710 if (MI->isC99Varargs())
2711 Arg += ", ...";
2712 else
2713 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002714 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002715 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002716 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002717
2718 // Non-variadic macros are simple.
2719 Result.AddPlaceholderChunk(
2720 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002721 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002722 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002723 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002724 }
2725
Douglas Gregorf64acca2010-05-25 21:41:55 +00002726 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002727 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002728 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002729
2730 if (IncludeBriefComments) {
2731 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002732 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002733 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002734 }
2735 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2736 if (OMD->isPropertyAccessor())
2737 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2738 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2739 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002740 }
2741
Douglas Gregor9eb77012009-11-07 00:00:49 +00002742 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002743 Result.AddTypedTextChunk(
2744 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002745 Result.AddTextChunk("::");
2746 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002747 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002748
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002749 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2750 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002751
Douglas Gregorc3425b12015-07-07 06:20:19 +00002752 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002753
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002754 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002755 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002756 Ctx, Policy);
2757 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002758 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002759 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002760 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002761 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002762 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002763 }
2764
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002765 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002766 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002767 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002768 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002769 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002770
Douglas Gregor3545ff42009-09-21 16:56:56 +00002771 // Figure out which template parameters are deduced (or have default
2772 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002773 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002774 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002775 unsigned LastDeducibleArgument;
2776 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2777 --LastDeducibleArgument) {
2778 if (!Deduced[LastDeducibleArgument - 1]) {
2779 // C++0x: Figure out if the template argument has a default. If so,
2780 // the user doesn't need to type this argument.
2781 // FIXME: We need to abstract template parameters better!
2782 bool HasDefaultArg = false;
2783 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002784 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002785 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2786 HasDefaultArg = TTP->hasDefaultArgument();
2787 else if (NonTypeTemplateParmDecl *NTTP
2788 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2789 HasDefaultArg = NTTP->hasDefaultArgument();
2790 else {
2791 assert(isa<TemplateTemplateParmDecl>(Param));
2792 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002793 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002794 }
2795
2796 if (!HasDefaultArg)
2797 break;
2798 }
2799 }
2800
2801 if (LastDeducibleArgument) {
2802 // Some of the function template arguments cannot be deduced from a
2803 // function call, so we introduce an explicit template argument list
2804 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002805 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002806 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002807 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002808 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002809 }
2810
2811 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002812 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002813 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002814 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002815 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002816 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002817 }
2818
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002819 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002820 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002821 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002822 Result.AddTypedTextChunk(
2823 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002824 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002825 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002826 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002827 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002828 }
2829
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002830 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002831 Selector Sel = Method->getSelector();
2832 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002833 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002834 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002835 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002836 }
2837
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002838 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002839 SelName += ':';
2840 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002841 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002842 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002843 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002844
2845 // If there is only one parameter, and we're past it, add an empty
2846 // typed-text chunk since there is nothing to type.
2847 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002848 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002849 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002850 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002851 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2852 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002853 P != PEnd; (void)++P, ++Idx) {
2854 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002855 std::string Keyword;
2856 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002857 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002858 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002859 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002860 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002861 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002862 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002863 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002864 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002865 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002866
2867 // If we're before the starting parameter, skip the placeholder.
2868 if (Idx < StartParameter)
2869 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002870
2871 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002872 QualType ParamType = (*P)->getType();
2873 Optional<ArrayRef<QualType>> ObjCSubsts;
2874 if (!CCContext.getBaseType().isNull())
2875 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2876
2877 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2878 Arg = FormatFunctionParameter(Policy, *P, true,
2879 /*SuppressBlock=*/false,
2880 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002881 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002882 if (ObjCSubsts)
2883 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2884 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002885 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002886 ParamType);
2887 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002888 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002889 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002890 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002891 }
2892
Douglas Gregor400f5972010-08-31 05:13:43 +00002893 if (Method->isVariadic() && (P + 1) == PEnd)
2894 Arg += ", ...";
2895
Douglas Gregor95887f92010-07-08 23:20:03 +00002896 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002897 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002898 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002899 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002900 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002901 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002902 }
2903
Douglas Gregor04c5f972009-12-23 00:21:46 +00002904 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002905 if (Method->param_size() == 0) {
2906 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002907 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002908 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002909 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002910 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002911 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002912 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002913
Richard Smith20e883e2015-04-29 23:20:19 +00002914 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002915 }
2916
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002917 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002918 }
2919
Douglas Gregorf09935f2009-12-01 05:55:20 +00002920 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002921 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002922 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002923
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002924 Result.AddTypedTextChunk(
2925 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002926 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002927}
2928
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002929/// \brief Add function overload parameter chunks to the given code completion
2930/// string.
2931static void AddOverloadParameterChunks(ASTContext &Context,
2932 const PrintingPolicy &Policy,
2933 const FunctionDecl *Function,
2934 const FunctionProtoType *Prototype,
2935 CodeCompletionBuilder &Result,
2936 unsigned CurrentArg,
2937 unsigned Start = 0,
2938 bool InOptional = false) {
2939 bool FirstParameter = true;
2940 unsigned NumParams = Function ? Function->getNumParams()
2941 : Prototype->getNumParams();
2942
2943 for (unsigned P = Start; P != NumParams; ++P) {
2944 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2945 // When we see an optional default argument, put that argument and
2946 // the remaining default arguments into a new, optional string.
2947 CodeCompletionBuilder Opt(Result.getAllocator(),
2948 Result.getCodeCompletionTUInfo());
2949 if (!FirstParameter)
2950 Opt.AddChunk(CodeCompletionString::CK_Comma);
2951 // Optional sections are nested.
2952 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2953 CurrentArg, P, /*InOptional=*/true);
2954 Result.AddOptionalChunk(Opt.TakeString());
2955 return;
2956 }
2957
2958 if (FirstParameter)
2959 FirstParameter = false;
2960 else
2961 Result.AddChunk(CodeCompletionString::CK_Comma);
2962
2963 InOptional = false;
2964
2965 // Format the placeholder string.
2966 std::string Placeholder;
2967 if (Function)
Richard Smith20e883e2015-04-29 23:20:19 +00002968 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002969 else
2970 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2971
2972 if (P == CurrentArg)
2973 Result.AddCurrentParameterChunk(
2974 Result.getAllocator().CopyString(Placeholder));
2975 else
2976 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2977 }
2978
2979 if (Prototype && Prototype->isVariadic()) {
2980 CodeCompletionBuilder Opt(Result.getAllocator(),
2981 Result.getCodeCompletionTUInfo());
2982 if (!FirstParameter)
2983 Opt.AddChunk(CodeCompletionString::CK_Comma);
2984
2985 if (CurrentArg < NumParams)
2986 Opt.AddPlaceholderChunk("...");
2987 else
2988 Opt.AddCurrentParameterChunk("...");
2989
2990 Result.AddOptionalChunk(Opt.TakeString());
2991 }
2992}
2993
Douglas Gregorf0f51982009-09-23 00:34:09 +00002994CodeCompletionString *
2995CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002996 unsigned CurrentArg, Sema &S,
2997 CodeCompletionAllocator &Allocator,
2998 CodeCompletionTUInfo &CCTUInfo,
2999 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00003000 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00003001
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003002 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003003 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00003004 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003005 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00003006 = dyn_cast<FunctionProtoType>(getFunctionType());
3007 if (!FDecl && !Proto) {
3008 // Function without a prototype. Just give the return type and a
3009 // highlighted ellipsis.
3010 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003011 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3012 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003013 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3014 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3015 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003016 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003017 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003018
3019 if (FDecl) {
3020 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3021 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3022 FDecl->getParamDecl(CurrentArg)))
3023 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00003024 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003025 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003026 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3027 } else {
3028 Result.AddResultTypeChunk(
3029 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00003030 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003031 }
Alp Toker314cc812014-01-25 16:55:45 +00003032
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003033 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003034 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3035 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003036 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003037
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003038 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003039}
3040
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003041unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003042 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00003043 bool PreferredTypeIsPointer) {
3044 unsigned Priority = CCP_Macro;
3045
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003046 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3047 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3048 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00003049 Priority = CCP_Constant;
3050 if (PreferredTypeIsPointer)
3051 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003052 }
3053 // Treat "YES", "NO", "true", and "false" as constants.
3054 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3055 MacroName.equals("true") || MacroName.equals("false"))
3056 Priority = CCP_Constant;
3057 // Treat "bool" as a type.
3058 else if (MacroName.equals("bool"))
3059 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3060
Douglas Gregor6e240332010-08-16 16:18:59 +00003061
3062 return Priority;
3063}
3064
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003065CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003066 if (!D)
3067 return CXCursor_UnexposedDecl;
3068
3069 switch (D->getKind()) {
3070 case Decl::Enum: return CXCursor_EnumDecl;
3071 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3072 case Decl::Field: return CXCursor_FieldDecl;
3073 case Decl::Function:
3074 return CXCursor_FunctionDecl;
3075 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3076 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003077 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003078
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003079 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003080 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3081 case Decl::ObjCMethod:
3082 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3083 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3084 case Decl::CXXMethod: return CXCursor_CXXMethod;
3085 case Decl::CXXConstructor: return CXCursor_Constructor;
3086 case Decl::CXXDestructor: return CXCursor_Destructor;
3087 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3088 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003089 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003090 case Decl::ParmVar: return CXCursor_ParmDecl;
3091 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003092 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003093 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003094 case Decl::Var: return CXCursor_VarDecl;
3095 case Decl::Namespace: return CXCursor_Namespace;
3096 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3097 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3098 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3099 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3100 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3101 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003102 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003103 case Decl::ClassTemplatePartialSpecialization:
3104 return CXCursor_ClassTemplatePartialSpecialization;
3105 case Decl::UsingDirective: return CXCursor_UsingDirective;
Olivier Goffart81978012016-06-09 16:15:55 +00003106 case Decl::StaticAssert: return CXCursor_StaticAssert;
Olivier Goffartd211c642016-11-04 06:29:27 +00003107 case Decl::Friend: return CXCursor_FriendDecl;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003108 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003109
3110 case Decl::Using:
3111 case Decl::UnresolvedUsingValue:
3112 case Decl::UnresolvedUsingTypename:
3113 return CXCursor_UsingDeclaration;
3114
Douglas Gregor4cd65962011-06-03 23:08:58 +00003115 case Decl::ObjCPropertyImpl:
3116 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3117 case ObjCPropertyImplDecl::Dynamic:
3118 return CXCursor_ObjCDynamicDecl;
3119
3120 case ObjCPropertyImplDecl::Synthesize:
3121 return CXCursor_ObjCSynthesizeDecl;
3122 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003123
3124 case Decl::Import:
3125 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003126
3127 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3128
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003129 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003130 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003131 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003132 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003133 case TTK_Struct: return CXCursor_StructDecl;
3134 case TTK_Class: return CXCursor_ClassDecl;
3135 case TTK_Union: return CXCursor_UnionDecl;
3136 case TTK_Enum: return CXCursor_EnumDecl;
3137 }
3138 }
3139 }
3140
3141 return CXCursor_UnexposedDecl;
3142}
3143
Douglas Gregor55b037b2010-07-08 20:55:51 +00003144static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003145 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003146 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003147 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003148
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003149 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003150
Douglas Gregor9eb77012009-11-07 00:00:49 +00003151 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3152 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003153 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003154 auto MD = PP.getMacroDefinition(M->first);
3155 if (IncludeUndefined || MD) {
3156 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003157 if (MI->isUsedForHeaderGuard())
3158 continue;
3159
Douglas Gregor8cb17462012-10-09 16:01:50 +00003160 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003161 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003162 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003163 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003164 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003165 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003166
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003167 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003168
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003169}
3170
Douglas Gregorce0e8562010-08-23 21:54:33 +00003171static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3172 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003173 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003174
3175 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003176
Douglas Gregorce0e8562010-08-23 21:54:33 +00003177 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3178 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003179 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003180 Results.AddResult(Result("__func__", CCP_Constant));
3181 Results.ExitScope();
3182}
3183
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003184static void HandleCodeCompleteResults(Sema *S,
3185 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003186 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003187 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003188 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003189 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003190 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003191}
3192
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003193static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3194 Sema::ParserCompletionContext PCC) {
3195 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003196 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003197 return CodeCompletionContext::CCC_TopLevel;
3198
John McCallfaf5fb42010-08-26 23:41:50 +00003199 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003200 return CodeCompletionContext::CCC_ClassStructUnion;
3201
John McCallfaf5fb42010-08-26 23:41:50 +00003202 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003203 return CodeCompletionContext::CCC_ObjCInterface;
3204
John McCallfaf5fb42010-08-26 23:41:50 +00003205 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003206 return CodeCompletionContext::CCC_ObjCImplementation;
3207
John McCallfaf5fb42010-08-26 23:41:50 +00003208 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003209 return CodeCompletionContext::CCC_ObjCIvarList;
3210
John McCallfaf5fb42010-08-26 23:41:50 +00003211 case Sema::PCC_Template:
3212 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003213 if (S.CurContext->isFileContext())
3214 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003215 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003216 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003217 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003218
John McCallfaf5fb42010-08-26 23:41:50 +00003219 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003220 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003221
John McCallfaf5fb42010-08-26 23:41:50 +00003222 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003223 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3224 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003225 return CodeCompletionContext::CCC_ParenthesizedExpression;
3226 else
3227 return CodeCompletionContext::CCC_Expression;
3228
3229 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003230 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003231 return CodeCompletionContext::CCC_Expression;
3232
John McCallfaf5fb42010-08-26 23:41:50 +00003233 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003234 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003235
John McCallfaf5fb42010-08-26 23:41:50 +00003236 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003237 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003238
3239 case Sema::PCC_ParenthesizedExpression:
3240 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003241
3242 case Sema::PCC_LocalDeclarationSpecifiers:
3243 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003244 }
David Blaikie8a40f702012-01-17 06:56:22 +00003245
3246 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003247}
3248
Douglas Gregorac322ec2010-08-27 21:18:54 +00003249/// \brief If we're in a C++ virtual member function, add completion results
3250/// that invoke the functions we override, since it's common to invoke the
3251/// overridden function as well as adding new functionality.
3252///
3253/// \param S The semantic analysis object for which we are generating results.
3254///
3255/// \param InContext This context in which the nested-name-specifier preceding
3256/// the code-completion point
3257static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3258 ResultBuilder &Results) {
3259 // Look through blocks.
3260 DeclContext *CurContext = S.CurContext;
3261 while (isa<BlockDecl>(CurContext))
3262 CurContext = CurContext->getParent();
3263
3264
3265 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3266 if (!Method || !Method->isVirtual())
3267 return;
3268
3269 // We need to have names for all of the parameters, if we're going to
3270 // generate a forwarding call.
David Majnemer59f77922016-06-24 04:05:48 +00003271 for (auto P : Method->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003272 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003273 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003274
Douglas Gregor75acd922011-09-27 23:30:47 +00003275 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003276 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3277 MEnd = Method->end_overridden_methods();
3278 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003279 CodeCompletionBuilder Builder(Results.getAllocator(),
3280 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003281 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003282 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3283 continue;
3284
3285 // If we need a nested-name-specifier, add one now.
3286 if (!InContext) {
3287 NestedNameSpecifier *NNS
3288 = getRequiredQualification(S.Context, CurContext,
3289 Overridden->getDeclContext());
3290 if (NNS) {
3291 std::string Str;
3292 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003293 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003294 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003295 }
3296 } else if (!InContext->Equals(Overridden->getDeclContext()))
3297 continue;
3298
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003299 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003300 Overridden->getNameAsString()));
3301 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003302 bool FirstParam = true;
David Majnemer59f77922016-06-24 04:05:48 +00003303 for (auto P : Method->parameters()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003304 if (FirstParam)
3305 FirstParam = false;
3306 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003307 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003308
Aaron Ballman43b68be2014-03-07 17:50:17 +00003309 Builder.AddPlaceholderChunk(
3310 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003311 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003312 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3313 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003314 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003315 CXCursor_CXXMethod,
3316 CXAvailability_Available,
3317 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003318 Results.Ignore(Overridden);
3319 }
3320}
3321
Douglas Gregor07f43572012-01-29 18:15:03 +00003322void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3323 ModuleIdPath Path) {
3324 typedef CodeCompletionResult Result;
3325 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003326 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003327 CodeCompletionContext::CCC_Other);
3328 Results.EnterNewScope();
3329
3330 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003331 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003332 typedef CodeCompletionResult Result;
3333 if (Path.empty()) {
3334 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003335 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003336 PP.getHeaderSearchInfo().collectAllModules(Modules);
3337 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3338 Builder.AddTypedTextChunk(
3339 Builder.getAllocator().CopyString(Modules[I]->Name));
3340 Results.AddResult(Result(Builder.TakeString(),
3341 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003342 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003343 Modules[I]->isAvailable()
3344 ? CXAvailability_Available
3345 : CXAvailability_NotAvailable));
3346 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003347 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003348 // Load the named module.
3349 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3350 Module::AllVisible,
3351 /*IsInclusionDirective=*/false);
3352 // Enumerate submodules.
3353 if (Mod) {
3354 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3355 SubEnd = Mod->submodule_end();
3356 Sub != SubEnd; ++Sub) {
3357
3358 Builder.AddTypedTextChunk(
3359 Builder.getAllocator().CopyString((*Sub)->Name));
3360 Results.AddResult(Result(Builder.TakeString(),
3361 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003362 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003363 (*Sub)->isAvailable()
3364 ? CXAvailability_Available
3365 : CXAvailability_NotAvailable));
3366 }
3367 }
3368 }
3369 Results.ExitScope();
3370 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3371 Results.data(),Results.size());
3372}
3373
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003374void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003375 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003376 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003377 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003378 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003379 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003380
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003381 // Determine how to filter results, e.g., so that the names of
3382 // values (functions, enumerators, function templates, etc.) are
3383 // only allowed where we can have an expression.
3384 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003385 case PCC_Namespace:
3386 case PCC_Class:
3387 case PCC_ObjCInterface:
3388 case PCC_ObjCImplementation:
3389 case PCC_ObjCInstanceVariableList:
3390 case PCC_Template:
3391 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003392 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003393 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003394 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3395 break;
3396
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003397 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003398 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003399 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003400 case PCC_ForInit:
3401 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003402 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003403 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3404 else
3405 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003406
David Blaikiebbafb8a2012-03-11 07:00:24 +00003407 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003408 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003409 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003410
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003411 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003412 // Unfiltered
3413 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003414 }
3415
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003416 // If we are in a C++ non-static member function, check the qualifiers on
3417 // the member function to filter/prioritize the results list.
3418 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3419 if (CurMethod->isInstance())
3420 Results.setObjectTypeQualifiers(
3421 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3422
Douglas Gregorc580c522010-01-14 01:09:38 +00003423 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003424 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3425 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003426
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003427 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003428 Results.ExitScope();
3429
Douglas Gregorce0e8562010-08-23 21:54:33 +00003430 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003431 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003432 case PCC_Expression:
3433 case PCC_Statement:
3434 case PCC_RecoveryInFunction:
3435 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003436 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003437 break;
3438
3439 case PCC_Namespace:
3440 case PCC_Class:
3441 case PCC_ObjCInterface:
3442 case PCC_ObjCImplementation:
3443 case PCC_ObjCInstanceVariableList:
3444 case PCC_Template:
3445 case PCC_MemberTemplate:
3446 case PCC_ForInit:
3447 case PCC_Condition:
3448 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003449 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003450 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003451 }
3452
Douglas Gregor9eb77012009-11-07 00:00:49 +00003453 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003454 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003455
Douglas Gregor50832e02010-09-20 22:39:41 +00003456 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003457 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003458}
3459
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003460static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3461 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003462 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003463 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003464 bool IsSuper,
3465 ResultBuilder &Results);
3466
3467void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3468 bool AllowNonIdentifiers,
3469 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003470 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003471 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003472 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003473 AllowNestedNameSpecifiers
3474 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3475 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003476 Results.EnterNewScope();
3477
3478 // Type qualifiers can come after names.
3479 Results.AddResult(Result("const"));
3480 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003481 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003482 Results.AddResult(Result("restrict"));
3483
David Blaikiebbafb8a2012-03-11 07:00:24 +00003484 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003485 if (AllowNonIdentifiers) {
3486 Results.AddResult(Result("operator"));
3487 }
3488
3489 // Add nested-name-specifiers.
3490 if (AllowNestedNameSpecifiers) {
3491 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003492 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003493 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3494 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3495 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003496 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003497 }
3498 }
3499 Results.ExitScope();
3500
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003501 // If we're in a context where we might have an expression (rather than a
3502 // declaration), and what we've seen so far is an Objective-C type that could
3503 // be a receiver of a class message, this may be a class message send with
3504 // the initial opening bracket '[' missing. Add appropriate completions.
3505 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003506 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003507 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003508 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3509 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003510 !DS.isTypeAltiVecVector() &&
3511 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003512 (S->getFlags() & Scope::DeclScope) != 0 &&
3513 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3514 Scope::FunctionPrototypeScope |
3515 Scope::AtCatchScope)) == 0) {
3516 ParsedType T = DS.getRepAsType();
3517 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003518 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003519 }
3520
Douglas Gregor56ccce02010-08-24 04:59:56 +00003521 // Note that we intentionally suppress macro results here, since we do not
3522 // encourage using macros to produce the names of entities.
3523
Douglas Gregor0ac41382010-09-23 23:01:17 +00003524 HandleCodeCompleteResults(this, CodeCompleter,
3525 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003526 Results.data(), Results.size());
3527}
3528
Douglas Gregor68762e72010-08-23 21:17:50 +00003529struct Sema::CodeCompleteExpressionData {
3530 CodeCompleteExpressionData(QualType PreferredType = QualType())
3531 : PreferredType(PreferredType), IntegralConstantExpression(false),
3532 ObjCCollection(false) { }
3533
3534 QualType PreferredType;
3535 bool IntegralConstantExpression;
3536 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003537 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003538};
3539
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003540/// \brief Perform code-completion in an expression context when we know what
3541/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003542void Sema::CodeCompleteExpression(Scope *S,
3543 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003544 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003545 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003546 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003547 if (Data.ObjCCollection)
3548 Results.setFilter(&ResultBuilder::IsObjCCollection);
3549 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003550 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003551 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003552 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3553 else
3554 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003555
3556 if (!Data.PreferredType.isNull())
3557 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3558
3559 // Ignore any declarations that we were told that we don't care about.
3560 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3561 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003562
3563 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003564 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3565 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003566
3567 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003568 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003569 Results.ExitScope();
3570
Douglas Gregor55b037b2010-07-08 20:55:51 +00003571 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003572 if (!Data.PreferredType.isNull())
3573 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3574 || Data.PreferredType->isMemberPointerType()
3575 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003576
Douglas Gregorce0e8562010-08-23 21:54:33 +00003577 if (S->getFnParent() &&
3578 !Data.ObjCCollection &&
3579 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003580 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003581
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003582 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003583 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003584 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003585 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3586 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003587 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003588}
3589
Douglas Gregoreda7e542010-09-18 01:28:11 +00003590void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3591 if (E.isInvalid())
3592 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003593 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003594 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003595}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003596
Douglas Gregorb888acf2010-12-09 23:01:55 +00003597/// \brief The set of properties that have already been added, referenced by
3598/// property name.
3599typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3600
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003601/// \brief Retrieve the container definition, if any?
3602static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3603 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3604 if (Interface->hasDefinition())
3605 return Interface->getDefinition();
3606
3607 return Interface;
3608 }
3609
3610 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3611 if (Protocol->hasDefinition())
3612 return Protocol->getDefinition();
3613
3614 return Protocol;
3615 }
3616 return Container;
3617}
3618
Alex Lorenzbaef8022016-11-09 13:43:18 +00003619/// \brief Adds a block invocation code completion result for the given block
3620/// declaration \p BD.
3621static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3622 CodeCompletionBuilder &Builder,
3623 const NamedDecl *BD,
3624 const FunctionTypeLoc &BlockLoc,
3625 const FunctionProtoTypeLoc &BlockProtoLoc) {
3626 Builder.AddResultTypeChunk(
3627 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3628 Policy, Builder.getAllocator()));
3629
3630 AddTypedNameChunk(Context, Policy, BD, Builder);
3631 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3632
3633 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3634 Builder.AddPlaceholderChunk("...");
3635 } else {
3636 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3637 if (I)
3638 Builder.AddChunk(CodeCompletionString::CK_Comma);
3639
3640 // Format the placeholder string.
3641 std::string PlaceholderStr =
3642 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3643
3644 if (I == N - 1 && BlockProtoLoc &&
3645 BlockProtoLoc.getTypePtr()->isVariadic())
3646 PlaceholderStr += ", ...";
3647
3648 // Add the placeholder string.
3649 Builder.AddPlaceholderChunk(
3650 Builder.getAllocator().CopyString(PlaceholderStr));
3651 }
3652 }
3653
3654 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3655}
3656
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003657static void AddObjCProperties(
3658 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3659 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3660 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3661 bool IsBaseExprStatement = false, bool IsClassProperty = false) {
John McCall276321a2010-08-25 06:19:51 +00003662 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003663
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003664 // Retrieve the definition.
3665 Container = getContainerDef(Container);
3666
Douglas Gregor9291bad2009-11-18 01:29:26 +00003667 // Add properties in this container.
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003668 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003669 if (!AddedProperties.insert(P->getIdentifier()).second)
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003670 return;
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003671
Alex Lorenzbaef8022016-11-09 13:43:18 +00003672 // FIXME: Provide block invocation completion for non-statement
3673 // expressions.
3674 if (!P->getType().getTypePtr()->isBlockPointerType() ||
3675 !IsBaseExprStatement) {
3676 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3677 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003678 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003679 }
3680
3681 // Block setter and invocation completion is provided only when we are able
3682 // to find the FunctionProtoTypeLoc with parameter names for the block.
3683 FunctionTypeLoc BlockLoc;
3684 FunctionProtoTypeLoc BlockProtoLoc;
3685 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3686 BlockProtoLoc);
3687 if (!BlockLoc) {
3688 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3689 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003690 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003691 }
3692
3693 // The default completion result for block properties should be the block
3694 // invocation completion when the base expression is a statement.
3695 CodeCompletionBuilder Builder(Results.getAllocator(),
3696 Results.getCodeCompletionTUInfo());
3697 AddObjCBlockCall(Container->getASTContext(),
3698 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3699 BlockLoc, BlockProtoLoc);
3700 Results.MaybeAddResult(
3701 Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3702 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003703
3704 // Provide additional block setter completion iff the base expression is a
Alex Lorenzbaef8022016-11-09 13:43:18 +00003705 // statement and the block property is mutable.
3706 if (!P->isReadOnly()) {
3707 CodeCompletionBuilder Builder(Results.getAllocator(),
3708 Results.getCodeCompletionTUInfo());
3709 AddResultTypeChunk(Container->getASTContext(),
3710 getCompletionPrintingPolicy(Results.getSema()), P,
3711 CCContext.getBaseType(), Builder);
3712 Builder.AddTypedTextChunk(
3713 Results.getAllocator().CopyString(P->getName()));
3714 Builder.AddChunk(CodeCompletionString::CK_Equal);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003715
Alex Lorenzbaef8022016-11-09 13:43:18 +00003716 std::string PlaceholderStr = formatBlockPlaceholder(
3717 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3718 BlockProtoLoc, /*SuppressBlockName=*/true);
3719 // Add the placeholder string.
3720 Builder.AddPlaceholderChunk(
3721 Builder.getAllocator().CopyString(PlaceholderStr));
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003722
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003723 // When completing blocks properties that return void the default
3724 // property completion result should show up before the setter,
3725 // otherwise the setter completion should show up before the default
3726 // property completion, as we normally want to use the result of the
3727 // call.
Alex Lorenzbaef8022016-11-09 13:43:18 +00003728 Results.MaybeAddResult(
3729 Result(Builder.TakeString(), P,
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003730 Results.getBasePriority(P) +
3731 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3732 ? CCD_BlockPropertySetter
3733 : -CCD_BlockPropertySetter)),
Alex Lorenzbaef8022016-11-09 13:43:18 +00003734 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003735 }
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003736 };
3737
3738 if (IsClassProperty) {
3739 for (const auto *P : Container->class_properties())
3740 AddProperty(P);
3741 } else {
3742 for (const auto *P : Container->instance_properties())
3743 AddProperty(P);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003744 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003745
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003746 // Add nullary methods or implicit class properties
Douglas Gregor95147142011-05-05 15:50:42 +00003747 if (AllowNullaryMethods) {
3748 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003749 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003750 // Adds a method result
3751 const auto AddMethod = [&](const ObjCMethodDecl *M) {
3752 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3753 if (!Name)
3754 return;
3755 if (!AddedProperties.insert(Name).second)
3756 return;
3757 CodeCompletionBuilder Builder(Results.getAllocator(),
3758 Results.getCodeCompletionTUInfo());
3759 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3760 Builder.AddTypedTextChunk(
3761 Results.getAllocator().CopyString(Name->getName()));
3762 Results.MaybeAddResult(
3763 Result(Builder.TakeString(), M,
3764 CCP_MemberDeclaration + CCD_MethodAsProperty),
3765 CurContext);
3766 };
3767
3768 if (IsClassProperty) {
3769 for (const auto *M : Container->methods()) {
3770 // Gather the class method that can be used as implicit property
3771 // getters. Methods with arguments or methods that return void aren't
3772 // added to the results as they can't be used as a getter.
3773 if (!M->getSelector().isUnarySelector() ||
3774 M->getReturnType()->isVoidType() || M->isInstanceMethod())
3775 continue;
3776 AddMethod(M);
3777 }
3778 } else {
3779 for (auto *M : Container->methods()) {
3780 if (M->getSelector().isUnarySelector())
3781 AddMethod(M);
3782 }
Douglas Gregor95147142011-05-05 15:50:42 +00003783 }
3784 }
Douglas Gregor95147142011-05-05 15:50:42 +00003785
Douglas Gregor9291bad2009-11-18 01:29:26 +00003786 // Add properties in referenced protocols.
3787 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003788 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003789 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003790 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003791 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003792 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003793 if (AllowCategories) {
3794 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003795 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003796 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003797 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003798 IsBaseExprStatement, IsClassProperty);
Douglas Gregor5d649882009-11-18 22:32:06 +00003799 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003800
Douglas Gregor9291bad2009-11-18 01:29:26 +00003801 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003802 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003803 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003804 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003805 IsBaseExprStatement, IsClassProperty);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003806
Douglas Gregor9291bad2009-11-18 01:29:26 +00003807 // Look in the superclass.
3808 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003809 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003810 AllowNullaryMethods, CurContext, AddedProperties,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003811 Results, IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003812 } else if (const ObjCCategoryDecl *Category
3813 = dyn_cast<ObjCCategoryDecl>(Container)) {
3814 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003815 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003816 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003817 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003818 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003819 }
3820}
3821
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003822void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003823 SourceLocation OpLoc, bool IsArrow,
3824 bool IsBaseExprStatement) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003825 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003826 return;
3827
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003828 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3829 if (ConvertedBase.isInvalid())
3830 return;
3831 Base = ConvertedBase.get();
3832
John McCall276321a2010-08-25 06:19:51 +00003833 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003834
Douglas Gregor2436e712009-09-17 21:32:03 +00003835 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003836
3837 if (IsArrow) {
3838 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3839 BaseType = Ptr->getPointeeType();
3840 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003841 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003842 else
3843 return;
3844 }
3845
Douglas Gregor21325842011-07-07 16:03:39 +00003846 enum CodeCompletionContext::Kind contextKind;
3847
3848 if (IsArrow) {
3849 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3850 }
3851 else {
3852 if (BaseType->isObjCObjectPointerType() ||
3853 BaseType->isObjCObjectOrInterfaceType()) {
3854 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3855 }
3856 else {
3857 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3858 }
3859 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003860
3861 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003862 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003863 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003864 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003865 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003866 Results.EnterNewScope();
3867 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003868 // Indicate that we are performing a member access, and the cv-qualifiers
3869 // for the base object type.
3870 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3871
Douglas Gregor9291bad2009-11-18 01:29:26 +00003872 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003873 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003874 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003875 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3876 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003877
David Blaikiebbafb8a2012-03-11 07:00:24 +00003878 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003879 if (!Results.empty()) {
3880 // The "template" keyword can follow "->" or "." in the grammar.
3881 // However, we only want to suggest the template keyword if something
3882 // is dependent.
3883 bool IsDependent = BaseType->isDependentType();
3884 if (!IsDependent) {
3885 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003886 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003887 IsDependent = Ctx->isDependentContext();
3888 break;
3889 }
3890 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003891
Douglas Gregor9291bad2009-11-18 01:29:26 +00003892 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003893 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003894 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003895 }
Alex Lorenz06cfa992016-10-12 11:40:15 +00003896 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003897 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003898 AddedPropertiesSet AddedProperties;
Alex Lorenz06cfa992016-10-12 11:40:15 +00003899
3900 if (const ObjCObjectPointerType *ObjCPtr =
3901 BaseType->getAsObjCInterfacePointerType()) {
3902 // Add property results based on our interface.
3903 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3904 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
3905 /*AllowNullaryMethods=*/true, CurContext,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003906 AddedProperties, Results, IsBaseExprStatement);
Alex Lorenz06cfa992016-10-12 11:40:15 +00003907 }
3908
Douglas Gregor9291bad2009-11-18 01:29:26 +00003909 // Add properties from the protocols in a qualified interface.
Alex Lorenz06cfa992016-10-12 11:40:15 +00003910 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003911 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003912 CurContext, AddedProperties, Results,
3913 IsBaseExprStatement);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003914 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003915 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003916 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003917 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003918 if (const ObjCObjectPointerType *ObjCPtr
3919 = BaseType->getAs<ObjCObjectPointerType>())
3920 Class = ObjCPtr->getInterfaceDecl();
3921 else
John McCall8b07ec22010-05-15 11:32:37 +00003922 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003923
3924 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003925 if (Class) {
3926 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3927 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003928 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3929 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003930 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003931 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003932
3933 // FIXME: How do we cope with isa?
3934
3935 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003936
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003937 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003938 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003939 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003940 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003941}
3942
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003943void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
3944 IdentifierInfo &ClassName,
3945 SourceLocation ClassNameLoc,
3946 bool IsBaseExprStatement) {
3947 IdentifierInfo *ClassNamePtr = &ClassName;
3948 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
3949 if (!IFace)
3950 return;
3951 CodeCompletionContext CCContext(
3952 CodeCompletionContext::CCC_ObjCPropertyAccess);
3953 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3954 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
3955 &ResultBuilder::IsMember);
3956 Results.EnterNewScope();
3957 AddedPropertiesSet AddedProperties;
3958 AddObjCProperties(CCContext, IFace, true,
3959 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
3960 Results, IsBaseExprStatement,
3961 /*IsClassProperty=*/true);
3962 Results.ExitScope();
3963 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3964 Results.data(), Results.size());
3965}
3966
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003967void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3968 if (!CodeCompleter)
3969 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003970
3971 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003972 enum CodeCompletionContext::Kind ContextKind
3973 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003974 switch ((DeclSpec::TST)TagSpec) {
3975 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003976 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003977 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003978 break;
3979
3980 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003981 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003982 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003983 break;
3984
3985 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003986 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003987 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003988 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003989 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003990 break;
3991
3992 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003993 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003994 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003995
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3997 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003998 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003999
4000 // First pass: look for tags.
4001 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00004002 LookupVisibleDecls(S, LookupTagName, Consumer,
4003 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00004004
Douglas Gregor39982192010-08-15 06:18:01 +00004005 if (CodeCompleter->includeGlobals()) {
4006 // Second pass: look for nested name specifiers.
4007 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4008 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4009 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004010
Douglas Gregor0ac41382010-09-23 23:01:17 +00004011 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004012 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004013}
4014
Douglas Gregor28c78432010-08-27 17:35:51 +00004015void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004016 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004017 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004018 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00004019 Results.EnterNewScope();
4020 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4021 Results.AddResult("const");
4022 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4023 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004024 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00004025 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4026 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00004027 if (getLangOpts().C11 &&
4028 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4029 Results.AddResult("_Atomic");
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004030 if (getLangOpts().MSVCCompat &&
4031 !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4032 Results.AddResult("__unaligned");
Douglas Gregor28c78432010-08-27 17:35:51 +00004033 Results.ExitScope();
4034 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004035 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00004036 Results.data(), Results.size());
4037}
4038
Benjamin Kramer72dae622016-02-18 15:30:24 +00004039void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4040 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4041}
4042
Douglas Gregord328d572009-09-21 18:10:23 +00004043void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00004044 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00004045 return;
John McCall5939b162011-08-06 07:30:58 +00004046
John McCallaab3e412010-08-25 08:40:02 +00004047 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00004048 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4049 if (!type->isEnumeralType()) {
4050 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00004051 Data.IntegralConstantExpression = true;
4052 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00004053 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00004054 }
Douglas Gregord328d572009-09-21 18:10:23 +00004055
4056 // Code-complete the cases of a switch statement over an enumeration type
4057 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00004058 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004059 if (EnumDecl *Def = Enum->getDefinition())
4060 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00004061
4062 // Determine which enumerators we have already seen in the switch statement.
4063 // FIXME: Ideally, we would also be able to look *past* the code-completion
4064 // token, in case we are code-completing in the middle of the switch and not
4065 // at the end. However, we aren't able to do so at the moment.
4066 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00004067 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00004068 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4069 SC = SC->getNextSwitchCase()) {
4070 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4071 if (!Case)
4072 continue;
4073
4074 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4075 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4076 if (EnumConstantDecl *Enumerator
4077 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4078 // We look into the AST of the case statement to determine which
4079 // enumerator was named. Alternatively, we could compute the value of
4080 // the integral constant expression, then compare it against the
4081 // values of each enumerator. However, value-based approach would not
4082 // work as well with C++ templates where enumerators declared within a
4083 // template are type- and value-dependent.
4084 EnumeratorsSeen.insert(Enumerator);
4085
Douglas Gregorf2510672009-09-21 19:57:38 +00004086 // If this is a qualified-id, keep track of the nested-name-specifier
4087 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00004088 //
4089 // switch (TagD.getKind()) {
4090 // case TagDecl::TK_enum:
4091 // break;
4092 // case XXX
4093 //
Douglas Gregorf2510672009-09-21 19:57:38 +00004094 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00004095 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4096 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004097 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00004098 }
4099 }
4100
David Blaikiebbafb8a2012-03-11 07:00:24 +00004101 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00004102 // If there are no prior enumerators in C++, check whether we have to
4103 // qualify the names of the enumerators that we suggest, because they
4104 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00004105 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00004106 }
4107
Douglas Gregord328d572009-09-21 18:10:23 +00004108 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004109 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004110 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004111 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00004112 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004113 for (auto *E : Enum->enumerators()) {
4114 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00004115 continue;
4116
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004117 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00004118 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00004119 }
4120 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00004121
Douglas Gregor21325842011-07-07 16:03:39 +00004122 //We need to make sure we're setting the right context,
4123 //so only say we include macros if the code completer says we do
4124 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4125 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00004126 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00004127 kind = CodeCompletionContext::CCC_OtherWithMacros;
4128 }
4129
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004130 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00004131 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004132 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00004133}
4134
Robert Wilhelm16e94b92013-08-09 18:02:13 +00004135static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004136 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004137 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004138
4139 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004140 if (!Args[I])
4141 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004142
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004143 return false;
4144}
4145
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004146typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4147
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004148static void mergeCandidatesWithResults(Sema &SemaRef,
4149 SmallVectorImpl<ResultCandidate> &Results,
4150 OverloadCandidateSet &CandidateSet,
4151 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004152 if (!CandidateSet.empty()) {
4153 // Sort the overload candidate set by placing the best overloads first.
4154 std::stable_sort(
4155 CandidateSet.begin(), CandidateSet.end(),
4156 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4157 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
4158 });
4159
4160 // Add the remaining viable overload candidates as code-completion results.
4161 for (auto &Candidate : CandidateSet)
4162 if (Candidate.Viable)
4163 Results.push_back(ResultCandidate(Candidate.Function));
4164 }
4165}
4166
4167/// \brief Get the type of the Nth parameter from a given set of overload
4168/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004169static QualType getParamType(Sema &SemaRef,
4170 ArrayRef<ResultCandidate> Candidates,
4171 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004172
4173 // Given the overloads 'Candidates' for a function call matching all arguments
4174 // up to N, return the type of the Nth parameter if it is the same for all
4175 // overload candidates.
4176 QualType ParamType;
4177 for (auto &Candidate : Candidates) {
4178 if (auto FType = Candidate.getFunctionType())
4179 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4180 if (N < Proto->getNumParams()) {
4181 if (ParamType.isNull())
4182 ParamType = Proto->getParamType(N);
4183 else if (!SemaRef.Context.hasSameUnqualifiedType(
4184 ParamType.getNonReferenceType(),
4185 Proto->getParamType(N).getNonReferenceType()))
4186 // Otherwise return a default-constructed QualType.
4187 return QualType();
4188 }
4189 }
4190
4191 return ParamType;
4192}
4193
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004194static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4195 MutableArrayRef<ResultCandidate> Candidates,
4196 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004197 bool CompleteExpressionWithCurrentArg = true) {
4198 QualType ParamType;
4199 if (CompleteExpressionWithCurrentArg)
4200 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4201
4202 if (ParamType.isNull())
4203 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4204 else
4205 SemaRef.CodeCompleteExpression(S, ParamType);
4206
4207 if (!Candidates.empty())
4208 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4209 Candidates.data(),
4210 Candidates.size());
4211}
4212
4213void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004214 if (!CodeCompleter)
4215 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004216
4217 // When we're code-completing for a call, we fall back to ordinary
4218 // name code-completion whenever we can't produce specific
4219 // results. We may want to revisit this strategy in the future,
4220 // e.g., by merging the two kinds of results.
4221
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004222 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004223
Douglas Gregorcabea402009-09-22 15:41:20 +00004224 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004225 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4226 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004227 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004228 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004229 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004230
John McCall57500772009-12-16 12:17:52 +00004231 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004232 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004233 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004234
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004235 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004236
John McCall57500772009-12-16 12:17:52 +00004237 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004238 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004239 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004240 /*PartialOverloading=*/true);
4241 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4242 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4243 if (UME->hasExplicitTemplateArgs()) {
4244 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4245 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004246 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004247 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4248 ArgExprs.append(Args.begin(), Args.end());
4249 UnresolvedSet<8> Decls;
4250 Decls.append(UME->decls_begin(), UME->decls_end());
4251 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4252 /*SuppressUsedConversions=*/false,
4253 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004254 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004255 FunctionDecl *FD = nullptr;
4256 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4257 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4258 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4259 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004260 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004261 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004262 !FD->getType()->getAs<FunctionProtoType>())
4263 Results.push_back(ResultCandidate(FD));
4264 else
4265 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4266 Args, CandidateSet,
4267 /*SuppressUsedConversions=*/false,
4268 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004269
4270 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4271 // If expression's type is CXXRecordDecl, it may overload the function
4272 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004273 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004274 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004275 DeclarationName OpName = Context.DeclarationNames
4276 .getCXXOperatorName(OO_Call);
4277 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4278 LookupQualifiedName(R, DC);
4279 R.suppressDiagnostics();
4280 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4281 ArgExprs.append(Args.begin(), Args.end());
4282 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4283 /*ExplicitArgs=*/nullptr,
4284 /*SuppressUsedConversions=*/false,
4285 /*PartialOverloading=*/true);
4286 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004287 } else {
4288 // Lastly we check whether expression's type is function pointer or
4289 // function.
4290 QualType T = NakedFn->getType();
4291 if (!T->getPointeeType().isNull())
4292 T = T->getPointeeType();
4293
4294 if (auto FP = T->getAs<FunctionProtoType>()) {
4295 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004296 /*PartialOverloading=*/true) ||
4297 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004298 Results.push_back(ResultCandidate(FP));
4299 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004300 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004301 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004302 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004303 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004304
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004305 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4306 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4307 !CandidateSet.empty());
4308}
4309
4310void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4311 ArrayRef<Expr *> Args) {
4312 if (!CodeCompleter)
4313 return;
4314
4315 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004316 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004317 return;
4318
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004319 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4320 if (!RD) {
4321 CodeCompleteExpression(S, Type);
4322 return;
4323 }
4324
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004325 // FIXME: Provide support for member initializers.
4326 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004327
4328 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4329
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004330 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004331 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4332 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4333 Args, CandidateSet,
4334 /*SuppressUsedConversions=*/false,
4335 /*PartialOverloading=*/true);
4336 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4337 AddTemplateOverloadCandidate(FTD,
4338 DeclAccessPair::make(FTD, C->getAccess()),
4339 /*ExplicitTemplateArgs=*/nullptr,
4340 Args, CandidateSet,
4341 /*SuppressUsedConversions=*/false,
4342 /*PartialOverloading=*/true);
4343 }
4344 }
4345
4346 SmallVector<ResultCandidate, 8> Results;
4347 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4348 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004349}
4350
John McCall48871652010-08-21 09:40:31 +00004351void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4352 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004353 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004354 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004355 return;
4356 }
4357
4358 CodeCompleteExpression(S, VD->getType());
4359}
4360
4361void Sema::CodeCompleteReturn(Scope *S) {
4362 QualType ResultType;
4363 if (isa<BlockDecl>(CurContext)) {
4364 if (BlockScopeInfo *BSI = getCurBlock())
4365 ResultType = BSI->ReturnType;
4366 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004367 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004368 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004369 ResultType = Method->getReturnType();
4370
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004371 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004372 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004373 else
4374 CodeCompleteExpression(S, ResultType);
4375}
4376
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004377void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004378 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004379 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004380 mapCodeCompletionContext(*this, PCC_Statement));
4381 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4382 Results.EnterNewScope();
4383
4384 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4385 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4386 CodeCompleter->includeGlobals());
4387
4388 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4389
4390 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004391 CodeCompletionBuilder Builder(Results.getAllocator(),
4392 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004393 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004394 if (Results.includeCodePatterns()) {
4395 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4396 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4397 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4398 Builder.AddPlaceholderChunk("statements");
4399 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4400 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4401 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004402 Results.AddResult(Builder.TakeString());
4403
4404 // "else if" block
4405 Builder.AddTypedTextChunk("else");
4406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4407 Builder.AddTextChunk("if");
4408 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4409 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004410 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004411 Builder.AddPlaceholderChunk("condition");
4412 else
4413 Builder.AddPlaceholderChunk("expression");
4414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004415 if (Results.includeCodePatterns()) {
4416 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4417 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4418 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4419 Builder.AddPlaceholderChunk("statements");
4420 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4421 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4422 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004423 Results.AddResult(Builder.TakeString());
4424
4425 Results.ExitScope();
4426
4427 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004428 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004429
4430 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004431 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004432
4433 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4434 Results.data(),Results.size());
4435}
4436
Richard Trieu2bd04012011-09-09 02:00:50 +00004437void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004438 if (LHS)
4439 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4440 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004441 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004442}
4443
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004444void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004445 bool EnteringContext) {
4446 if (!SS.getScopeRep() || !CodeCompleter)
4447 return;
4448
Douglas Gregor3545ff42009-09-21 16:56:56 +00004449 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4450 if (!Ctx)
4451 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004452
4453 // Try to instantiate any non-dependent declaration contexts before
4454 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004455 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004456 return;
4457
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004458 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004459 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004460 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004461 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004462
Douglas Gregor3545ff42009-09-21 16:56:56 +00004463 // The "template" keyword can follow "::" in the grammar, but only
4464 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004465 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004466 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004467 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004468
4469 // Add calls to overridden virtual functions, if there are any.
4470 //
4471 // FIXME: This isn't wonderful, because we don't know whether we're actually
4472 // in a context that permits expressions. This is a general issue with
4473 // qualified-id completions.
4474 if (!EnteringContext)
4475 MaybeAddOverrideCalls(*this, Ctx, Results);
4476 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004477
Douglas Gregorac322ec2010-08-27 21:18:54 +00004478 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4479 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4480
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004481 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004482 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004483 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004484}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004485
4486void Sema::CodeCompleteUsing(Scope *S) {
4487 if (!CodeCompleter)
4488 return;
4489
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004490 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004491 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004492 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4493 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004494 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004495
4496 // If we aren't in class scope, we could see the "namespace" keyword.
4497 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004498 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004499
4500 // After "using", we can see anything that would start a
4501 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004502 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004503 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4504 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004505 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004506
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004507 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004508 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004509 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004510}
4511
4512void Sema::CodeCompleteUsingDirective(Scope *S) {
4513 if (!CodeCompleter)
4514 return;
4515
Douglas Gregor3545ff42009-09-21 16:56:56 +00004516 // After "using namespace", we expect to see a namespace name or namespace
4517 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004518 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004519 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004520 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004521 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004522 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004523 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004524 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4525 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004526 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004527 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004528 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004529 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004530}
4531
4532void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4533 if (!CodeCompleter)
4534 return;
4535
Ted Kremenekc37877d2013-10-08 17:08:03 +00004536 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004537 if (!S->getParent())
4538 Ctx = Context.getTranslationUnitDecl();
4539
Douglas Gregor0ac41382010-09-23 23:01:17 +00004540 bool SuppressedGlobalResults
4541 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4542
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004543 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004544 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004545 SuppressedGlobalResults
4546 ? CodeCompletionContext::CCC_Namespace
4547 : CodeCompletionContext::CCC_Other,
4548 &ResultBuilder::IsNamespace);
4549
4550 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004551 // We only want to see those namespaces that have already been defined
4552 // within this scope, because its likely that the user is creating an
4553 // extended namespace declaration. Keep track of the most recent
4554 // definition of each namespace.
4555 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4556 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4557 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4558 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004559 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004560
4561 // Add the most recent definition (or extended definition) of each
4562 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004563 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004564 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004565 NS = OrigToLatest.begin(),
4566 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004567 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004568 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004569 NS->second, Results.getBasePriority(NS->second),
4570 nullptr),
4571 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004572 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004573 }
4574
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004575 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004576 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004577 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004578}
4579
4580void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4581 if (!CodeCompleter)
4582 return;
4583
Douglas Gregor3545ff42009-09-21 16:56:56 +00004584 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004585 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004586 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004587 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004588 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004589 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004590 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4591 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004592 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004593 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004594 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004595}
4596
Douglas Gregorc811ede2009-09-18 20:05:18 +00004597void Sema::CodeCompleteOperatorName(Scope *S) {
4598 if (!CodeCompleter)
4599 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004600
John McCall276321a2010-08-25 06:19:51 +00004601 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004602 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004603 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004604 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004605 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004606 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004607
Douglas Gregor3545ff42009-09-21 16:56:56 +00004608 // Add the names of overloadable operators.
4609#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4610 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004611 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004612#include "clang/Basic/OperatorKinds.def"
4613
4614 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004615 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004616 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004617 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4618 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004619
4620 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004621 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004622 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004623
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004624 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004625 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004626 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004627}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004628
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004629void Sema::CodeCompleteConstructorInitializer(
4630 Decl *ConstructorD,
4631 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004632 if (!ConstructorD)
4633 return;
4634
4635 AdjustDeclIfTemplate(ConstructorD);
4636
4637 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004638 if (!Constructor)
4639 return;
4640
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004641 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004642 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004643 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004644 Results.EnterNewScope();
4645
4646 // Fill in any already-initialized fields or base classes.
4647 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4648 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004649 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004650 if (Initializers[I]->isBaseInitializer())
4651 InitializedBases.insert(
4652 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4653 else
Francois Pichetd583da02010-12-04 09:14:42 +00004654 InitializedFields.insert(cast<FieldDecl>(
4655 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004656 }
4657
4658 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004659 CodeCompletionBuilder Builder(Results.getAllocator(),
4660 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004661 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004662 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004663 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004664 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004665 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4666 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004667 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004668 = !Initializers.empty() &&
4669 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004670 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004671 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004672 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004673 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004674
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004675 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004676 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004677 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004678 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4679 Builder.AddPlaceholderChunk("args");
4680 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4681 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004682 SawLastInitializer? CCP_NextInitializer
4683 : CCP_MemberDeclaration));
4684 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004685 }
4686
4687 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004688 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004689 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4690 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004691 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004692 = !Initializers.empty() &&
4693 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004694 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004695 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004696 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004697 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004698
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004699 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004700 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004701 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004702 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4703 Builder.AddPlaceholderChunk("args");
4704 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4705 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004706 SawLastInitializer? CCP_NextInitializer
4707 : CCP_MemberDeclaration));
4708 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004709 }
4710
4711 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004712 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004713 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4714 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004715 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004716 = !Initializers.empty() &&
4717 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004718 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004719 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004720 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004721
4722 if (!Field->getDeclName())
4723 continue;
4724
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004725 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004726 Field->getIdentifier()->getName()));
4727 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4728 Builder.AddPlaceholderChunk("args");
4729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4730 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004731 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004732 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004733 CXCursor_MemberRef,
4734 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004735 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004736 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004737 }
4738 Results.ExitScope();
4739
Douglas Gregor0ac41382010-09-23 23:01:17 +00004740 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004741 Results.data(), Results.size());
4742}
4743
Douglas Gregord8c61782012-02-15 15:34:24 +00004744/// \brief Determine whether this scope denotes a namespace.
4745static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004746 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004747 if (!DC)
4748 return false;
4749
4750 return DC->isFileContext();
4751}
4752
4753void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4754 bool AfterAmpersand) {
4755 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004756 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004757 CodeCompletionContext::CCC_Other);
4758 Results.EnterNewScope();
4759
4760 // Note what has already been captured.
4761 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4762 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004763 for (const auto &C : Intro.Captures) {
4764 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004765 IncludedThis = true;
4766 continue;
4767 }
4768
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004769 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004770 }
4771
4772 // Look for other capturable variables.
4773 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004774 for (const auto *D : S->decls()) {
4775 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004776 if (!Var ||
4777 !Var->hasLocalStorage() ||
4778 Var->hasAttr<BlocksAttr>())
4779 continue;
4780
David Blaikie82e95a32014-11-19 07:49:47 +00004781 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004782 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004783 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004784 }
4785 }
4786
4787 // Add 'this', if it would be valid.
4788 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4789 addThisCompletion(*this, Results);
4790
4791 Results.ExitScope();
4792
4793 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4794 Results.data(), Results.size());
4795}
4796
James Dennett596e4752012-06-14 03:11:41 +00004797/// Macro that optionally prepends an "@" to the string literal passed in via
4798/// Keyword, depending on whether NeedAt is true or false.
4799#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4800
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004801static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004802 ResultBuilder &Results,
4803 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004804 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004805 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004806 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004807
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004808 CodeCompletionBuilder Builder(Results.getAllocator(),
4809 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004810 if (LangOpts.ObjC2) {
4811 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004812 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004813 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4814 Builder.AddPlaceholderChunk("property");
4815 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004816
4817 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004818 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004819 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4820 Builder.AddPlaceholderChunk("property");
4821 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004822 }
4823}
4824
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004825static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004826 ResultBuilder &Results,
4827 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004828 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004829
4830 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004831 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004832
4833 if (LangOpts.ObjC2) {
4834 // @property
James Dennett596e4752012-06-14 03:11:41 +00004835 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004836
4837 // @required
James Dennett596e4752012-06-14 03:11:41 +00004838 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004839
4840 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004841 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004842 }
4843}
4844
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004845static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004846 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004847 CodeCompletionBuilder Builder(Results.getAllocator(),
4848 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004849
4850 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004851 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4853 Builder.AddPlaceholderChunk("name");
4854 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004855
Douglas Gregorf4c33342010-05-28 00:22:41 +00004856 if (Results.includeCodePatterns()) {
4857 // @interface name
4858 // FIXME: Could introduce the whole pattern, including superclasses and
4859 // such.
James Dennett596e4752012-06-14 03:11:41 +00004860 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4862 Builder.AddPlaceholderChunk("class");
4863 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004864
Douglas Gregorf4c33342010-05-28 00:22:41 +00004865 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004866 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4868 Builder.AddPlaceholderChunk("protocol");
4869 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004870
4871 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004872 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004873 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4874 Builder.AddPlaceholderChunk("class");
4875 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004876 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004877
4878 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004879 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004880 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4881 Builder.AddPlaceholderChunk("alias");
4882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4883 Builder.AddPlaceholderChunk("class");
4884 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004885
4886 if (Results.getSema().getLangOpts().Modules) {
4887 // @import name
4888 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4889 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4890 Builder.AddPlaceholderChunk("module");
4891 Results.AddResult(Result(Builder.TakeString()));
4892 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004893}
4894
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004895void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004896 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004897 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004898 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004899 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004900 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004901 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004902 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004903 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004904 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004905 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004906 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004907 HandleCodeCompleteResults(this, CodeCompleter,
4908 CodeCompletionContext::CCC_Other,
4909 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004910}
4911
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004912static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004913 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004914 CodeCompletionBuilder Builder(Results.getAllocator(),
4915 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004916
4917 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004918 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004919 if (Results.getSema().getLangOpts().CPlusPlus ||
4920 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004921 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004922 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004923 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004924 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4925 Builder.AddPlaceholderChunk("type-name");
4926 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4927 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004928
4929 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004930 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004931 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004932 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4933 Builder.AddPlaceholderChunk("protocol-name");
4934 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4935 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004936
4937 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004938 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004939 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004940 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4941 Builder.AddPlaceholderChunk("selector");
4942 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4943 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004944
4945 // @"string"
4946 Builder.AddResultTypeChunk("NSString *");
4947 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4948 Builder.AddPlaceholderChunk("string");
4949 Builder.AddTextChunk("\"");
4950 Results.AddResult(Result(Builder.TakeString()));
4951
Douglas Gregor951de302012-07-17 23:24:47 +00004952 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004953 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004954 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004955 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004956 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4957 Results.AddResult(Result(Builder.TakeString()));
4958
Douglas Gregor951de302012-07-17 23:24:47 +00004959 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004960 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004961 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004962 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004963 Builder.AddChunk(CodeCompletionString::CK_Colon);
4964 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4965 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004966 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4967 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004968
Douglas Gregor951de302012-07-17 23:24:47 +00004969 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004970 Builder.AddResultTypeChunk("id");
4971 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004972 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004973 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4974 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004975}
4976
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004977static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004978 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004979 CodeCompletionBuilder Builder(Results.getAllocator(),
4980 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004981
Douglas Gregorf4c33342010-05-28 00:22:41 +00004982 if (Results.includeCodePatterns()) {
4983 // @try { statements } @catch ( declaration ) { statements } @finally
4984 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004985 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004986 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4987 Builder.AddPlaceholderChunk("statements");
4988 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4989 Builder.AddTextChunk("@catch");
4990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4991 Builder.AddPlaceholderChunk("parameter");
4992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4993 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4994 Builder.AddPlaceholderChunk("statements");
4995 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4996 Builder.AddTextChunk("@finally");
4997 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4998 Builder.AddPlaceholderChunk("statements");
4999 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5000 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005001 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005002
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005003 // @throw
James Dennett596e4752012-06-14 03:11:41 +00005004 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005005 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5006 Builder.AddPlaceholderChunk("expression");
5007 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005008
Douglas Gregorf4c33342010-05-28 00:22:41 +00005009 if (Results.includeCodePatterns()) {
5010 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00005011 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005012 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5013 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5014 Builder.AddPlaceholderChunk("expression");
5015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5016 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5017 Builder.AddPlaceholderChunk("statements");
5018 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5019 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005020 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005021}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005022
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005023static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00005024 ResultBuilder &Results,
5025 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005026 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00005027 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5028 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5029 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005030 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00005031 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005032}
5033
5034void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005035 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005036 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005037 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00005038 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005039 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00005040 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005041 HandleCodeCompleteResults(this, CodeCompleter,
5042 CodeCompletionContext::CCC_Other,
5043 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00005044}
5045
5046void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005047 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005048 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005049 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00005050 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005051 AddObjCStatementResults(Results, false);
5052 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005053 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005054 HandleCodeCompleteResults(this, CodeCompleter,
5055 CodeCompletionContext::CCC_Other,
5056 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005057}
5058
5059void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005060 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005061 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005062 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005063 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005064 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005065 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005066 HandleCodeCompleteResults(this, CodeCompleter,
5067 CodeCompletionContext::CCC_Other,
5068 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005069}
5070
Douglas Gregore6078da2009-11-19 00:14:45 +00005071/// \brief Determine whether the addition of the given flag to an Objective-C
5072/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00005073static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00005074 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00005075 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00005076 return true;
5077
Bill Wendling44426052012-12-20 19:22:21 +00005078 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00005079
5080 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00005081 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5082 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00005083 return true;
5084
Jordan Rose53cb2f32012-08-20 20:01:13 +00005085 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00005086 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00005087 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00005088 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00005089 ObjCDeclSpec::DQ_PR_retain |
5090 ObjCDeclSpec::DQ_PR_strong |
5091 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00005092 if (AssignCopyRetMask &&
5093 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00005094 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00005095 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00005096 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00005097 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5098 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00005099 return true;
5100
5101 return false;
5102}
5103
Douglas Gregor36029f42009-11-18 23:08:07 +00005104void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00005105 if (!CodeCompleter)
5106 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005107
Bill Wendling44426052012-12-20 19:22:21 +00005108 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00005109
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005110 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005111 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005112 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00005113 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00005114 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00005115 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00005116 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00005117 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00005118 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00005119 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5120 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00005121 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00005122 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00005123 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00005124 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00005125 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00005126 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00005127 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00005128 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00005129 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00005130 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00005131 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00005132 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00005133
5134 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00005135 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00005136 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00005137 Results.AddResult(CodeCompletionResult("weak"));
5138
Bill Wendling44426052012-12-20 19:22:21 +00005139 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005140 CodeCompletionBuilder Setter(Results.getAllocator(),
5141 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005142 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005143 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005144 Setter.AddPlaceholderChunk("method");
5145 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005146 }
Bill Wendling44426052012-12-20 19:22:21 +00005147 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005148 CodeCompletionBuilder Getter(Results.getAllocator(),
5149 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005150 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005151 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005152 Getter.AddPlaceholderChunk("method");
5153 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005154 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005155 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5156 Results.AddResult(CodeCompletionResult("nonnull"));
5157 Results.AddResult(CodeCompletionResult("nullable"));
5158 Results.AddResult(CodeCompletionResult("null_unspecified"));
5159 Results.AddResult(CodeCompletionResult("null_resettable"));
5160 }
Steve Naroff936354c2009-10-08 21:55:05 +00005161 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005162 HandleCodeCompleteResults(this, CodeCompleter,
5163 CodeCompletionContext::CCC_Other,
5164 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00005165}
Steve Naroffeae65032009-11-07 02:08:14 +00005166
James Dennettf1243872012-06-17 05:33:25 +00005167/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00005168/// via code completion.
5169enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00005170 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5171 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5172 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005173};
5174
Douglas Gregor67c692c2010-08-26 15:07:07 +00005175static bool isAcceptableObjCSelector(Selector Sel,
5176 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005177 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005178 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005179 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00005180 if (NumSelIdents > Sel.getNumArgs())
5181 return false;
5182
5183 switch (WantKind) {
5184 case MK_Any: break;
5185 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5186 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5187 }
5188
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005189 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5190 return false;
5191
Douglas Gregor67c692c2010-08-26 15:07:07 +00005192 for (unsigned I = 0; I != NumSelIdents; ++I)
5193 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5194 return false;
5195
5196 return true;
5197}
5198
Douglas Gregorc8537c52009-11-19 07:41:15 +00005199static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5200 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005201 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005202 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005203 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005204 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005205}
Douglas Gregor1154e272010-09-16 16:06:31 +00005206
5207namespace {
5208 /// \brief A set of selectors, which is used to avoid introducing multiple
5209 /// completions with the same selector into the result set.
5210 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5211}
5212
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005213/// \brief Add all of the Objective-C methods in the given Objective-C
5214/// container to the set of results.
5215///
5216/// The container will be a class, protocol, category, or implementation of
5217/// any of the above. This mether will recurse to include methods from
5218/// the superclasses of classes along with their categories, protocols, and
5219/// implementations.
5220///
5221/// \param Container the container in which we'll look to find methods.
5222///
James Dennett596e4752012-06-14 03:11:41 +00005223/// \param WantInstanceMethods Whether to add instance methods (only); if
5224/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005225///
5226/// \param CurContext the context in which we're performing the lookup that
5227/// finds methods.
5228///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005229/// \param AllowSameLength Whether we allow a method to be added to the list
5230/// when it has the same number of parameters as we have selector identifiers.
5231///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005232/// \param Results the structure into which we'll add results.
5233static void AddObjCMethods(ObjCContainerDecl *Container,
5234 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00005235 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005236 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005237 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00005238 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005239 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00005240 ResultBuilder &Results,
5241 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00005242 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005243 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005244 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5245 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005246 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005247 // The instance methods on the root class can be messaged via the
5248 // metaclass.
5249 if (M->isInstanceMethod() == WantInstanceMethods ||
5250 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005251 // Check whether the selector identifiers we've been given are a
5252 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005253 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005254 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005255
David Blaikie82e95a32014-11-19 07:49:47 +00005256 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005257 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005258
5259 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005260 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005261 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005262 if (!InOriginalClass)
5263 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005264 Results.MaybeAddResult(R, CurContext);
5265 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005266 }
5267
Douglas Gregorf37c9492010-09-16 15:34:59 +00005268 // Visit the protocols of protocols.
5269 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005270 if (Protocol->hasDefinition()) {
5271 const ObjCList<ObjCProtocolDecl> &Protocols
5272 = Protocol->getReferencedProtocols();
5273 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5274 E = Protocols.end();
5275 I != E; ++I)
5276 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005277 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005278 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005279 }
5280
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005281 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005282 return;
5283
5284 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005285 for (auto *I : IFace->protocols())
5286 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005287 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005288
5289 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005290 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005291 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005292 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005293 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005294
5295 // Add a categories protocol methods.
5296 const ObjCList<ObjCProtocolDecl> &Protocols
5297 = CatDecl->getReferencedProtocols();
5298 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5299 E = Protocols.end();
5300 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005301 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005302 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005303 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005304
5305 // Add methods in category implementations.
5306 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005307 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005308 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005309 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005310 }
5311
5312 // Add methods in superclass.
5313 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005314 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005315 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005316 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005317
5318 // Add methods in our implementation, if any.
5319 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005320 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005321 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005322 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005323}
5324
5325
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005326void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005327 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005328 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005329 if (!Class) {
5330 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005331 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005332 Class = Category->getClassInterface();
5333
5334 if (!Class)
5335 return;
5336 }
5337
5338 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005339 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005340 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005341 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005342 Results.EnterNewScope();
5343
Douglas Gregor1154e272010-09-16 16:06:31 +00005344 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005345 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005346 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005347 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005348 HandleCodeCompleteResults(this, CodeCompleter,
5349 CodeCompletionContext::CCC_Other,
5350 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005351}
5352
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005353void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005354 // Try to find the interface where setters might live.
5355 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005356 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005357 if (!Class) {
5358 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005359 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005360 Class = Category->getClassInterface();
5361
5362 if (!Class)
5363 return;
5364 }
5365
5366 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005367 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005368 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005369 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005370 Results.EnterNewScope();
5371
Douglas Gregor1154e272010-09-16 16:06:31 +00005372 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005373 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005374 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005375
5376 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005377 HandleCodeCompleteResults(this, CodeCompleter,
5378 CodeCompletionContext::CCC_Other,
5379 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005380}
5381
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005382void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5383 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005384 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005385 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005386 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005387 Results.EnterNewScope();
5388
5389 // Add context-sensitive, Objective-C parameter-passing keywords.
5390 bool AddedInOut = false;
5391 if ((DS.getObjCDeclQualifier() &
5392 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5393 Results.AddResult("in");
5394 Results.AddResult("inout");
5395 AddedInOut = true;
5396 }
5397 if ((DS.getObjCDeclQualifier() &
5398 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5399 Results.AddResult("out");
5400 if (!AddedInOut)
5401 Results.AddResult("inout");
5402 }
5403 if ((DS.getObjCDeclQualifier() &
5404 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5405 ObjCDeclSpec::DQ_Oneway)) == 0) {
5406 Results.AddResult("bycopy");
5407 Results.AddResult("byref");
5408 Results.AddResult("oneway");
5409 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005410 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5411 Results.AddResult("nonnull");
5412 Results.AddResult("nullable");
5413 Results.AddResult("null_unspecified");
5414 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005415
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005416 // If we're completing the return type of an Objective-C method and the
5417 // identifier IBAction refers to a macro, provide a completion item for
5418 // an action, e.g.,
5419 // IBAction)<#selector#>:(id)sender
5420 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005421 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005422 CodeCompletionBuilder Builder(Results.getAllocator(),
5423 Results.getCodeCompletionTUInfo(),
5424 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005425 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005426 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005427 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005428 Builder.AddChunk(CodeCompletionString::CK_Colon);
5429 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005430 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005431 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005432 Builder.AddTextChunk("sender");
5433 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5434 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005435
5436 // If we're completing the return type, provide 'instancetype'.
5437 if (!IsParameter) {
5438 Results.AddResult(CodeCompletionResult("instancetype"));
5439 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005440
Douglas Gregor99fa2642010-08-24 01:06:58 +00005441 // Add various builtin type names and specifiers.
5442 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5443 Results.ExitScope();
5444
5445 // Add the various type names
5446 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5447 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5448 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5449 CodeCompleter->includeGlobals());
5450
5451 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005452 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005453
5454 HandleCodeCompleteResults(this, CodeCompleter,
5455 CodeCompletionContext::CCC_Type,
5456 Results.data(), Results.size());
5457}
5458
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005459/// \brief When we have an expression with type "id", we may assume
5460/// that it has some more-specific class type based on knowledge of
5461/// common uses of Objective-C. This routine returns that class type,
5462/// or NULL if no better result could be determined.
5463static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005464 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005465 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005466 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005467
5468 Selector Sel = Msg->getSelector();
5469 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005470 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005471
5472 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5473 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005474 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005475
5476 ObjCMethodDecl *Method = Msg->getMethodDecl();
5477 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005478 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005479
5480 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005481 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005482 switch (Msg->getReceiverKind()) {
5483 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005484 if (const ObjCObjectType *ObjType
5485 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5486 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005487 break;
5488
5489 case ObjCMessageExpr::Instance: {
5490 QualType T = Msg->getInstanceReceiver()->getType();
5491 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5492 IFace = Ptr->getInterfaceDecl();
5493 break;
5494 }
5495
5496 case ObjCMessageExpr::SuperInstance:
5497 case ObjCMessageExpr::SuperClass:
5498 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005499 }
5500
5501 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005502 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005503
5504 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5505 if (Method->isInstanceMethod())
5506 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5507 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005508 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005509 .Case("autorelease", IFace)
5510 .Case("copy", IFace)
5511 .Case("copyWithZone", IFace)
5512 .Case("mutableCopy", IFace)
5513 .Case("mutableCopyWithZone", IFace)
5514 .Case("awakeFromCoder", IFace)
5515 .Case("replacementObjectFromCoder", IFace)
5516 .Case("class", IFace)
5517 .Case("classForCoder", IFace)
5518 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005519 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005520
5521 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5522 .Case("new", IFace)
5523 .Case("alloc", IFace)
5524 .Case("allocWithZone", IFace)
5525 .Case("class", IFace)
5526 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005527 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005528}
5529
Douglas Gregor6fc04132010-08-27 15:10:57 +00005530// Add a special completion for a message send to "super", which fills in the
5531// most likely case of forwarding all of our arguments to the superclass
5532// function.
5533///
5534/// \param S The semantic analysis object.
5535///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005536/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005537/// the "super" keyword. Otherwise, we just need to provide the arguments.
5538///
5539/// \param SelIdents The identifiers in the selector that have already been
5540/// provided as arguments for a send to "super".
5541///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005542/// \param Results The set of results to augment.
5543///
5544/// \returns the Objective-C method declaration that would be invoked by
5545/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005546static ObjCMethodDecl *AddSuperSendCompletion(
5547 Sema &S, bool NeedSuperKeyword,
5548 ArrayRef<IdentifierInfo *> SelIdents,
5549 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005550 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5551 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005552 return nullptr;
5553
Douglas Gregor6fc04132010-08-27 15:10:57 +00005554 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5555 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005556 return nullptr;
5557
Douglas Gregor6fc04132010-08-27 15:10:57 +00005558 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005559 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005560 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5561 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005562 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5563 CurMethod->isInstanceMethod());
5564
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005565 // Check in categories or class extensions.
5566 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005567 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005568 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005569 CurMethod->isInstanceMethod())))
5570 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005571 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005572 }
5573 }
5574
Douglas Gregor6fc04132010-08-27 15:10:57 +00005575 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005576 return nullptr;
5577
Douglas Gregor6fc04132010-08-27 15:10:57 +00005578 // Check whether the superclass method has the same signature.
5579 if (CurMethod->param_size() != SuperMethod->param_size() ||
5580 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005581 return nullptr;
5582
Douglas Gregor6fc04132010-08-27 15:10:57 +00005583 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5584 CurPEnd = CurMethod->param_end(),
5585 SuperP = SuperMethod->param_begin();
5586 CurP != CurPEnd; ++CurP, ++SuperP) {
5587 // Make sure the parameter types are compatible.
5588 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5589 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005590 return nullptr;
5591
Douglas Gregor6fc04132010-08-27 15:10:57 +00005592 // Make sure we have a parameter name to forward!
5593 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005594 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005595 }
5596
5597 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005598 CodeCompletionBuilder Builder(Results.getAllocator(),
5599 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005600
5601 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005602 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5603 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005604 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005605
5606 // If we need the "super" keyword, add it (plus some spacing).
5607 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005608 Builder.AddTypedTextChunk("super");
5609 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005610 }
5611
5612 Selector Sel = CurMethod->getSelector();
5613 if (Sel.isUnarySelector()) {
5614 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005615 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005616 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005617 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005618 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005619 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005620 } else {
5621 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5622 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005623 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005624 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005625
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005626 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005627 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005628 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005629 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005630 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005631 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005632 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005633 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005634 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005635 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005636 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005637 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005638 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005639 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005640 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005641 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005642 }
5643 }
5644 }
5645
Douglas Gregor78254c82012-03-27 23:34:16 +00005646 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5647 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005648 return SuperMethod;
5649}
5650
Douglas Gregora817a192010-05-27 23:06:34 +00005651void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005652 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005653 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005654 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005655 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005656 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005657 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5658 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005659
Douglas Gregora817a192010-05-27 23:06:34 +00005660 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5661 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005662 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5663 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005664
5665 // If we are in an Objective-C method inside a class that has a superclass,
5666 // add "super" as an option.
5667 if (ObjCMethodDecl *Method = getCurMethodDecl())
5668 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005669 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005670 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005671
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005672 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005673 }
Douglas Gregora817a192010-05-27 23:06:34 +00005674
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005675 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005676 addThisCompletion(*this, Results);
5677
Douglas Gregora817a192010-05-27 23:06:34 +00005678 Results.ExitScope();
5679
5680 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005681 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005682 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005683 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005684
5685}
5686
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005687void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005688 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005689 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005690 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005691 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5692 // Figure out which interface we're in.
5693 CDecl = CurMethod->getClassInterface();
5694 if (!CDecl)
5695 return;
5696
5697 // Find the superclass of this class.
5698 CDecl = CDecl->getSuperClass();
5699 if (!CDecl)
5700 return;
5701
5702 if (CurMethod->isInstanceMethod()) {
5703 // We are inside an instance method, which means that the message
5704 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005705 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005706 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005707 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005708 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005709 }
5710
5711 // Fall through to send to the superclass in CDecl.
5712 } else {
5713 // "super" may be the name of a type or variable. Figure out which
5714 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005715 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005716 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5717 LookupOrdinaryName);
5718 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5719 // "super" names an interface. Use it.
5720 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005721 if (const ObjCObjectType *Iface
5722 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5723 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005724 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5725 // "super" names an unresolved type; we can't be more specific.
5726 } else {
5727 // Assume that "super" names some kind of value and parse that way.
5728 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005729 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005730 UnqualifiedId id;
5731 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005732 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5733 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005734 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005735 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005736 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005737 }
5738
5739 // Fall through
5740 }
5741
John McCallba7bf592010-08-24 05:47:05 +00005742 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005743 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005744 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005745 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005746 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005747 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005748}
5749
Douglas Gregor74661272010-09-21 00:03:25 +00005750/// \brief Given a set of code-completion results for the argument of a message
5751/// send, determine the preferred type (if any) for that argument expression.
5752static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5753 unsigned NumSelIdents) {
5754 typedef CodeCompletionResult Result;
5755 ASTContext &Context = Results.getSema().Context;
5756
5757 QualType PreferredType;
5758 unsigned BestPriority = CCP_Unlikely * 2;
5759 Result *ResultsData = Results.data();
5760 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5761 Result &R = ResultsData[I];
5762 if (R.Kind == Result::RK_Declaration &&
5763 isa<ObjCMethodDecl>(R.Declaration)) {
5764 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005765 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005766 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005767 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005768 ->getType();
5769 if (R.Priority < BestPriority || PreferredType.isNull()) {
5770 BestPriority = R.Priority;
5771 PreferredType = MyPreferredType;
5772 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5773 MyPreferredType)) {
5774 PreferredType = QualType();
5775 }
5776 }
5777 }
5778 }
5779 }
5780
5781 return PreferredType;
5782}
5783
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005784static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5785 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005786 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005787 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005788 bool IsSuper,
5789 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005790 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005791 ObjCInterfaceDecl *CDecl = nullptr;
5792
Douglas Gregor8ce33212009-11-17 17:59:40 +00005793 // If the given name refers to an interface type, retrieve the
5794 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005795 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005796 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005797 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005798 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5799 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005800 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005801
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005802 // Add all of the factory methods in this Objective-C class, its protocols,
5803 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005804 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005805
Douglas Gregor6fc04132010-08-27 15:10:57 +00005806 // If this is a send-to-super, try to add the special "super" send
5807 // completion.
5808 if (IsSuper) {
5809 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005810 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005811 Results.Ignore(SuperMethod);
5812 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005813
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005814 // If we're inside an Objective-C method definition, prefer its selector to
5815 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005816 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005817 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005818
Douglas Gregor1154e272010-09-16 16:06:31 +00005819 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005820 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005821 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005822 SemaRef.CurContext, Selectors, AtArgumentExpression,
5823 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005824 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005825 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005826
Douglas Gregord720daf2010-04-06 17:30:22 +00005827 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005828 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005829 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005830 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005831 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005832 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005833 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005834 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005835 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005836
5837 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005838 }
5839 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005840
5841 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5842 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005843 M != MEnd; ++M) {
5844 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005845 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005846 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005847 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005848 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005849
Nico Weber2e0c8f72014-12-27 03:58:08 +00005850 Result R(MethList->getMethod(),
5851 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005852 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005853 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005854 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005855 }
5856 }
5857 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005858
5859 Results.ExitScope();
5860}
Douglas Gregor6285f752010-04-06 16:40:00 +00005861
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005862void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005863 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005864 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005865 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005866
5867 QualType T = this->GetTypeFromParser(Receiver);
5868
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005869 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005870 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005871 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005872 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005873
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005874 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005875 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005876
5877 // If we're actually at the argument expression (rather than prior to the
5878 // selector), we're actually performing code completion for an expression.
5879 // Determine whether we have a single, best method. If so, we can
5880 // code-complete the expression using the corresponding parameter type as
5881 // our preferred type, improving completion results.
5882 if (AtArgumentExpression) {
5883 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005884 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005885 if (PreferredType.isNull())
5886 CodeCompleteOrdinaryName(S, PCC_Expression);
5887 else
5888 CodeCompleteExpression(S, PreferredType);
5889 return;
5890 }
5891
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005892 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005893 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005894 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005895}
5896
Richard Trieu2bd04012011-09-09 02:00:50 +00005897void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005898 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005899 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005900 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005901 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005902
5903 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005904
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005905 // If necessary, apply function/array conversion to the receiver.
5906 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005907 if (RecExpr) {
5908 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5909 if (Conv.isInvalid()) // conversion failed. bail.
5910 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005911 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005912 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005913 QualType ReceiverType = RecExpr? RecExpr->getType()
5914 : Super? Context.getObjCObjectPointerType(
5915 Context.getObjCInterfaceType(Super))
5916 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005917
Douglas Gregordc520b02010-11-08 21:12:30 +00005918 // If we're messaging an expression with type "id" or "Class", check
5919 // whether we know something special about the receiver that allows
5920 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005921 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005922 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5923 if (ReceiverType->isObjCClassType())
5924 return CodeCompleteObjCClassMessage(S,
5925 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005926 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005927 AtArgumentExpression, Super);
5928
5929 ReceiverType = Context.getObjCObjectPointerType(
5930 Context.getObjCInterfaceType(IFace));
5931 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005932 } else if (RecExpr && getLangOpts().CPlusPlus) {
5933 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5934 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005935 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005936 ReceiverType = RecExpr->getType();
5937 }
5938 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005939
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005940 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005941 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005942 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005943 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005944 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005945
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005946 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005947
Douglas Gregor6fc04132010-08-27 15:10:57 +00005948 // If this is a send-to-super, try to add the special "super" send
5949 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005950 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005951 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005952 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005953 Results.Ignore(SuperMethod);
5954 }
5955
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005956 // If we're inside an Objective-C method definition, prefer its selector to
5957 // others.
5958 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5959 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005960
Douglas Gregor1154e272010-09-16 16:06:31 +00005961 // Keep track of the selectors we've already added.
5962 VisitedSelectorSet Selectors;
5963
Douglas Gregora3329fa2009-11-18 00:06:18 +00005964 // Handle messages to Class. This really isn't a message to an instance
5965 // method, so we treat it the same way we would treat a message send to a
5966 // class method.
5967 if (ReceiverType->isObjCClassType() ||
5968 ReceiverType->isObjCQualifiedClassType()) {
5969 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5970 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005971 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005972 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005973 }
5974 }
5975 // Handle messages to a qualified ID ("id<foo>").
5976 else if (const ObjCObjectPointerType *QualID
5977 = ReceiverType->getAsObjCQualifiedIdType()) {
5978 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005979 for (auto *I : QualID->quals())
5980 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005981 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005982 }
5983 // Handle messages to a pointer to interface type.
5984 else if (const ObjCObjectPointerType *IFacePtr
5985 = ReceiverType->getAsObjCInterfacePointerType()) {
5986 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005987 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005988 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005989 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005990
5991 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005992 for (auto *I : IFacePtr->quals())
5993 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005994 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005995 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005996 // Handle messages to "id".
5997 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005998 // We're messaging "id", so provide all instance methods we know
5999 // about as code-completion results.
6000
6001 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006002 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00006003 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00006004 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6005 I != N; ++I) {
6006 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006007 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00006008 continue;
6009
Sebastian Redl75d8a322010-08-02 23:18:59 +00006010 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00006011 }
6012 }
6013
Sebastian Redl75d8a322010-08-02 23:18:59 +00006014 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6015 MEnd = MethodPool.end();
6016 M != MEnd; ++M) {
6017 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00006018 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006019 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00006020 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00006021 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00006022
Nico Weber2e0c8f72014-12-27 03:58:08 +00006023 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00006024 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00006025
Nico Weber2e0c8f72014-12-27 03:58:08 +00006026 Result R(MethList->getMethod(),
6027 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006028 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006029 R.AllParametersAreInformative = false;
6030 Results.MaybeAddResult(R, CurContext);
6031 }
6032 }
6033 }
Steve Naroffeae65032009-11-07 02:08:14 +00006034 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00006035
6036
6037 // If we're actually at the argument expression (rather than prior to the
6038 // selector), we're actually performing code completion for an expression.
6039 // Determine whether we have a single, best method. If so, we can
6040 // code-complete the expression using the corresponding parameter type as
6041 // our preferred type, improving completion results.
6042 if (AtArgumentExpression) {
6043 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006044 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006045 if (PreferredType.isNull())
6046 CodeCompleteOrdinaryName(S, PCC_Expression);
6047 else
6048 CodeCompleteExpression(S, PreferredType);
6049 return;
6050 }
6051
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006052 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006053 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006054 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006055}
Douglas Gregorbaf69612009-11-18 04:19:12 +00006056
Douglas Gregor68762e72010-08-23 21:17:50 +00006057void Sema::CodeCompleteObjCForCollection(Scope *S,
6058 DeclGroupPtrTy IterationVar) {
6059 CodeCompleteExpressionData Data;
6060 Data.ObjCCollection = true;
6061
6062 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00006063 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00006064 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6065 if (*I)
6066 Data.IgnoreDecls.push_back(*I);
6067 }
6068 }
6069
6070 CodeCompleteExpression(S, Data);
6071}
6072
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006073void Sema::CodeCompleteObjCSelector(Scope *S,
6074 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00006075 // If we have an external source, load the entire class method
6076 // pool from the AST file.
6077 if (ExternalSource) {
6078 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6079 I != N; ++I) {
6080 Selector Sel = ExternalSource->GetExternalSelector(I);
6081 if (Sel.isNull() || MethodPool.count(Sel))
6082 continue;
6083
6084 ReadMethodPool(Sel);
6085 }
6086 }
6087
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006088 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006089 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006090 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00006091 Results.EnterNewScope();
6092 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6093 MEnd = MethodPool.end();
6094 M != MEnd; ++M) {
6095
6096 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006097 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00006098 continue;
6099
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006100 CodeCompletionBuilder Builder(Results.getAllocator(),
6101 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006102 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006103 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006104 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006105 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006106 continue;
6107 }
6108
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006109 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00006110 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006111 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006112 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006113 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006114 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006115 Accumulator.clear();
6116 }
6117 }
6118
Benjamin Kramer632500c2011-07-26 16:59:25 +00006119 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006120 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00006121 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006122 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006123 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006124 }
6125 Results.ExitScope();
6126
6127 HandleCodeCompleteResults(this, CodeCompleter,
6128 CodeCompletionContext::CCC_SelectorName,
6129 Results.data(), Results.size());
6130}
6131
Douglas Gregorbaf69612009-11-18 04:19:12 +00006132/// \brief Add all of the protocol declarations that we find in the given
6133/// (translation unit) context.
6134static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006135 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00006136 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006137 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00006138
Aaron Ballman629afae2014-03-07 19:56:05 +00006139 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00006140 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006141 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00006142 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00006143 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6144 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006145 }
6146}
6147
Craig Topper883dd332015-12-24 23:58:11 +00006148void Sema::CodeCompleteObjCProtocolReferences(
6149 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006150 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006151 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006152 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006153
Chandler Carruthede11632016-11-04 06:06:50 +00006154 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006155 Results.EnterNewScope();
6156
6157 // Tell the result set to ignore all of the protocols we have
6158 // already seen.
6159 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00006160 for (const IdentifierLocPair &Pair : Protocols)
6161 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6162 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00006163 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006164
Douglas Gregora3b23b02010-12-09 21:44:02 +00006165 // Add all protocols.
6166 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6167 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006168
Douglas Gregora3b23b02010-12-09 21:44:02 +00006169 Results.ExitScope();
6170 }
6171
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006172 HandleCodeCompleteResults(this, CodeCompleter,
6173 CodeCompletionContext::CCC_ObjCProtocolName,
6174 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006175}
6176
6177void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006178 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006179 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006180 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006181
Chandler Carruthede11632016-11-04 06:06:50 +00006182 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006183 Results.EnterNewScope();
6184
6185 // Add all protocols.
6186 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6187 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006188
Douglas Gregora3b23b02010-12-09 21:44:02 +00006189 Results.ExitScope();
6190 }
6191
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006192 HandleCodeCompleteResults(this, CodeCompleter,
6193 CodeCompletionContext::CCC_ObjCProtocolName,
6194 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00006195}
Douglas Gregor49c22a72009-11-18 16:26:39 +00006196
6197/// \brief Add all of the Objective-C interface declarations that we find in
6198/// the given (translation unit) context.
6199static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6200 bool OnlyForwardDeclarations,
6201 bool OnlyUnimplemented,
6202 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006203 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00006204
Aaron Ballman629afae2014-03-07 19:56:05 +00006205 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00006206 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006207 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00006208 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00006209 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00006210 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6211 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006212 }
6213}
6214
6215void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006216 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006217 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006218 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006219 Results.EnterNewScope();
6220
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006221 if (CodeCompleter->includeGlobals()) {
6222 // Add all classes.
6223 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6224 false, Results);
6225 }
6226
Douglas Gregor49c22a72009-11-18 16:26:39 +00006227 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006228
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006229 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006230 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006231 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006232}
6233
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006234void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6235 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006236 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006237 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006238 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006239 Results.EnterNewScope();
6240
6241 // Make sure that we ignore the class we're currently defining.
6242 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006243 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006244 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006245 Results.Ignore(CurClass);
6246
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006247 if (CodeCompleter->includeGlobals()) {
6248 // Add all classes.
6249 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6250 false, Results);
6251 }
6252
Douglas Gregor49c22a72009-11-18 16:26:39 +00006253 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006254
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006255 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006256 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006257 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006258}
6259
6260void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006261 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006262 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006263 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006264 Results.EnterNewScope();
6265
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006266 if (CodeCompleter->includeGlobals()) {
6267 // Add all unimplemented classes.
6268 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6269 true, Results);
6270 }
6271
Douglas Gregor49c22a72009-11-18 16:26:39 +00006272 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006273
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006274 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006275 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006276 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006277}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006278
6279void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006280 IdentifierInfo *ClassName,
6281 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006282 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006283
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006284 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006285 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006286 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006287
6288 // Ignore any categories we find that have already been implemented by this
6289 // interface.
6290 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6291 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006292 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006293 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006294 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006295 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006296 }
6297
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006298 // Add all of the categories we know about.
6299 Results.EnterNewScope();
6300 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006301 for (const auto *D : TU->decls())
6302 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006303 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006304 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6305 nullptr),
6306 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006307 Results.ExitScope();
6308
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006309 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006310 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006311 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006312}
6313
6314void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006315 IdentifierInfo *ClassName,
6316 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006317 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006318
6319 // Find the corresponding interface. If we couldn't find the interface, the
6320 // program itself is ill-formed. However, we'll try to be helpful still by
6321 // providing the list of all of the categories we know about.
6322 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006323 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006324 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6325 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006326 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006327
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006328 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006329 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006330 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006331
6332 // Add all of the categories that have have corresponding interface
6333 // declarations in this class and any of its superclasses, except for
6334 // already-implemented categories in the class itself.
6335 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6336 Results.EnterNewScope();
6337 bool IgnoreImplemented = true;
6338 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006339 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006340 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006341 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006342 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6343 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006344 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006345
6346 Class = Class->getSuperClass();
6347 IgnoreImplemented = false;
6348 }
6349 Results.ExitScope();
6350
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006351 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006352 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006353 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006354}
Douglas Gregor5d649882009-11-18 22:32:06 +00006355
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006356void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006357 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006358 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006359 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006360 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006361
6362 // Figure out where this @synthesize lives.
6363 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006364 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006365 if (!Container ||
6366 (!isa<ObjCImplementationDecl>(Container) &&
6367 !isa<ObjCCategoryImplDecl>(Container)))
6368 return;
6369
6370 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006371 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006372 for (const auto *D : Container->decls())
6373 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006374 Results.Ignore(PropertyImpl->getPropertyDecl());
6375
6376 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006377 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006378 Results.EnterNewScope();
6379 if (ObjCImplementationDecl *ClassImpl
6380 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006381 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006382 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006383 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006384 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006385 AddObjCProperties(CCContext,
6386 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006387 false, /*AllowNullaryMethods=*/false, CurContext,
6388 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006389 Results.ExitScope();
6390
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006391 HandleCodeCompleteResults(this, CodeCompleter,
6392 CodeCompletionContext::CCC_Other,
6393 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006394}
6395
6396void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006397 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006398 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006399 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006400 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006401 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006402
6403 // Figure out where this @synthesize lives.
6404 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006405 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006406 if (!Container ||
6407 (!isa<ObjCImplementationDecl>(Container) &&
6408 !isa<ObjCCategoryImplDecl>(Container)))
6409 return;
6410
6411 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006412 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006413 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006414 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006415 Class = ClassImpl->getClassInterface();
6416 else
6417 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6418 ->getClassInterface();
6419
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006420 // Determine the type of the property we're synthesizing.
6421 QualType PropertyType = Context.getObjCIdType();
6422 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006423 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6424 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006425 PropertyType
6426 = Property->getType().getNonReferenceType().getUnqualifiedType();
6427
6428 // Give preference to ivars
6429 Results.setPreferredType(PropertyType);
6430 }
6431 }
6432
Douglas Gregor5d649882009-11-18 22:32:06 +00006433 // Add all of the instance variables in this class and its superclasses.
6434 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006435 bool SawSimilarlyNamedIvar = false;
6436 std::string NameWithPrefix;
6437 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006438 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006439 std::string NameWithSuffix = PropertyName->getName().str();
6440 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006441 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006442 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6443 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006444 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6445 CurContext, nullptr, false);
6446
Douglas Gregor331faa02011-04-18 14:13:53 +00006447 // Determine whether we've seen an ivar with a name similar to the
6448 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006449 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006450 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006451 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006452 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006453
6454 // Reduce the priority of this result by one, to give it a slight
6455 // advantage over other results whose names don't match so closely.
6456 if (Results.size() &&
6457 Results.data()[Results.size() - 1].Kind
6458 == CodeCompletionResult::RK_Declaration &&
6459 Results.data()[Results.size() - 1].Declaration == Ivar)
6460 Results.data()[Results.size() - 1].Priority--;
6461 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006462 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006463 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006464
6465 if (!SawSimilarlyNamedIvar) {
6466 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006467 // an ivar of the appropriate type.
6468 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006469 typedef CodeCompletionResult Result;
6470 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006471 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6472 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006473
Douglas Gregor75acd922011-09-27 23:30:47 +00006474 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006475 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006476 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006477 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6478 Results.AddResult(Result(Builder.TakeString(), Priority,
6479 CXCursor_ObjCIvarDecl));
6480 }
6481
Douglas Gregor5d649882009-11-18 22:32:06 +00006482 Results.ExitScope();
6483
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006484 HandleCodeCompleteResults(this, CodeCompleter,
6485 CodeCompletionContext::CCC_Other,
6486 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006487}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006488
Douglas Gregor416b5752010-08-25 01:08:01 +00006489// Mapping from selectors to the methods that implement that selector, along
6490// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006491typedef llvm::DenseMap<
6492 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006493
6494/// \brief Find all of the methods that reside in the given container
6495/// (and its superclasses, protocols, etc.) that meet the given
6496/// criteria. Insert those methods into the map of known methods,
6497/// indexed by selector so they can be easily found.
6498static void FindImplementableMethods(ASTContext &Context,
6499 ObjCContainerDecl *Container,
6500 bool WantInstanceMethods,
6501 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006502 KnownMethodsMap &KnownMethods,
6503 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006504 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006505 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006506 if (!IFace->hasDefinition())
6507 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006508
6509 IFace = IFace->getDefinition();
6510 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006511
Douglas Gregor636a61e2010-04-07 00:21:17 +00006512 const ObjCList<ObjCProtocolDecl> &Protocols
6513 = IFace->getReferencedProtocols();
6514 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006515 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006516 I != E; ++I)
6517 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006518 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006519
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006520 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006521 for (auto *Cat : IFace->visible_categories()) {
6522 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006523 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006524 }
6525
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006526 // Visit the superclass.
6527 if (IFace->getSuperClass())
6528 FindImplementableMethods(Context, IFace->getSuperClass(),
6529 WantInstanceMethods, ReturnType,
6530 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006531 }
6532
6533 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6534 // Recurse into protocols.
6535 const ObjCList<ObjCProtocolDecl> &Protocols
6536 = Category->getReferencedProtocols();
6537 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006538 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006539 I != E; ++I)
6540 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006541 KnownMethods, InOriginalClass);
6542
6543 // If this category is the original class, jump to the interface.
6544 if (InOriginalClass && Category->getClassInterface())
6545 FindImplementableMethods(Context, Category->getClassInterface(),
6546 WantInstanceMethods, ReturnType, KnownMethods,
6547 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006548 }
6549
6550 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006551 // Make sure we have a definition; that's what we'll walk.
6552 if (!Protocol->hasDefinition())
6553 return;
6554 Protocol = Protocol->getDefinition();
6555 Container = Protocol;
6556
6557 // Recurse into protocols.
6558 const ObjCList<ObjCProtocolDecl> &Protocols
6559 = Protocol->getReferencedProtocols();
6560 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6561 E = Protocols.end();
6562 I != E; ++I)
6563 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6564 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006565 }
6566
6567 // Add methods in this container. This operation occurs last because
6568 // we want the methods from this container to override any methods
6569 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006570 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006571 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006572 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006573 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006574 continue;
6575
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006576 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006577 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006578 }
6579 }
6580}
6581
Douglas Gregor669a25a2011-02-17 00:22:45 +00006582/// \brief Add the parenthesized return or parameter type chunk to a code
6583/// completion string.
6584static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006585 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006586 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006587 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006588 CodeCompletionBuilder &Builder) {
6589 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006590 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006591 if (!Quals.empty())
6592 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006593 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006594 Builder.getAllocator()));
6595 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6596}
6597
6598/// \brief Determine whether the given class is or inherits from a class by
6599/// the given name.
6600static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006601 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006602 if (!Class)
6603 return false;
6604
6605 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6606 return true;
6607
6608 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6609}
6610
6611/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6612/// Key-Value Observing (KVO).
6613static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6614 bool IsInstanceMethod,
6615 QualType ReturnType,
6616 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006617 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006618 ResultBuilder &Results) {
6619 IdentifierInfo *PropName = Property->getIdentifier();
6620 if (!PropName || PropName->getLength() == 0)
6621 return;
6622
Douglas Gregor75acd922011-09-27 23:30:47 +00006623 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6624
Douglas Gregor669a25a2011-02-17 00:22:45 +00006625 // Builder that will create each code completion.
6626 typedef CodeCompletionResult Result;
6627 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006628 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006629
6630 // The selector table.
6631 SelectorTable &Selectors = Context.Selectors;
6632
6633 // The property name, copied into the code completion allocation region
6634 // on demand.
6635 struct KeyHolder {
6636 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006637 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006638 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006639
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006640 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006641 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6642
Douglas Gregor669a25a2011-02-17 00:22:45 +00006643 operator const char *() {
6644 if (CopiedKey)
6645 return CopiedKey;
6646
6647 return CopiedKey = Allocator.CopyString(Key);
6648 }
6649 } Key(Allocator, PropName->getName());
6650
6651 // The uppercased name of the property name.
6652 std::string UpperKey = PropName->getName();
6653 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006654 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006655
6656 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6657 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6658 Property->getType());
6659 bool ReturnTypeMatchesVoid
6660 = ReturnType.isNull() || ReturnType->isVoidType();
6661
6662 // Add the normal accessor -(type)key.
6663 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006664 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006665 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6666 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006667 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6668 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006669
6670 Builder.AddTypedTextChunk(Key);
6671 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6672 CXCursor_ObjCInstanceMethodDecl));
6673 }
6674
6675 // If we have an integral or boolean property (or the user has provided
6676 // an integral or boolean return type), add the accessor -(type)isKey.
6677 if (IsInstanceMethod &&
6678 ((!ReturnType.isNull() &&
6679 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6680 (ReturnType.isNull() &&
6681 (Property->getType()->isIntegerType() ||
6682 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006683 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006684 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006685 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6686 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006687 if (ReturnType.isNull()) {
6688 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6689 Builder.AddTextChunk("BOOL");
6690 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6691 }
6692
6693 Builder.AddTypedTextChunk(
6694 Allocator.CopyString(SelectorId->getName()));
6695 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6696 CXCursor_ObjCInstanceMethodDecl));
6697 }
6698 }
6699
6700 // Add the normal mutator.
6701 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6702 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006703 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006704 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006705 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006706 if (ReturnType.isNull()) {
6707 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6708 Builder.AddTextChunk("void");
6709 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6710 }
6711
6712 Builder.AddTypedTextChunk(
6713 Allocator.CopyString(SelectorId->getName()));
6714 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006715 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6716 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006717 Builder.AddTextChunk(Key);
6718 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6719 CXCursor_ObjCInstanceMethodDecl));
6720 }
6721 }
6722
6723 // Indexed and unordered accessors
6724 unsigned IndexedGetterPriority = CCP_CodePattern;
6725 unsigned IndexedSetterPriority = CCP_CodePattern;
6726 unsigned UnorderedGetterPriority = CCP_CodePattern;
6727 unsigned UnorderedSetterPriority = CCP_CodePattern;
6728 if (const ObjCObjectPointerType *ObjCPointer
6729 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6730 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6731 // If this interface type is not provably derived from a known
6732 // collection, penalize the corresponding completions.
6733 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6734 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6735 if (!InheritsFromClassNamed(IFace, "NSArray"))
6736 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6737 }
6738
6739 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6740 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6741 if (!InheritsFromClassNamed(IFace, "NSSet"))
6742 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6743 }
6744 }
6745 } else {
6746 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6747 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6748 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6749 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6750 }
6751
6752 // Add -(NSUInteger)countOf<key>
6753 if (IsInstanceMethod &&
6754 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006755 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006756 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006757 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6758 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006759 if (ReturnType.isNull()) {
6760 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6761 Builder.AddTextChunk("NSUInteger");
6762 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6763 }
6764
6765 Builder.AddTypedTextChunk(
6766 Allocator.CopyString(SelectorId->getName()));
6767 Results.AddResult(Result(Builder.TakeString(),
6768 std::min(IndexedGetterPriority,
6769 UnorderedGetterPriority),
6770 CXCursor_ObjCInstanceMethodDecl));
6771 }
6772 }
6773
6774 // Indexed getters
6775 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6776 if (IsInstanceMethod &&
6777 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006778 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006779 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006780 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006781 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006782 if (ReturnType.isNull()) {
6783 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6784 Builder.AddTextChunk("id");
6785 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6786 }
6787
6788 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6790 Builder.AddTextChunk("NSUInteger");
6791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6792 Builder.AddTextChunk("index");
6793 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6794 CXCursor_ObjCInstanceMethodDecl));
6795 }
6796 }
6797
6798 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6799 if (IsInstanceMethod &&
6800 (ReturnType.isNull() ||
6801 (ReturnType->isObjCObjectPointerType() &&
6802 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6803 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6804 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006805 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006806 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006807 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006808 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006809 if (ReturnType.isNull()) {
6810 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6811 Builder.AddTextChunk("NSArray *");
6812 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6813 }
6814
6815 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6816 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6817 Builder.AddTextChunk("NSIndexSet *");
6818 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6819 Builder.AddTextChunk("indexes");
6820 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6821 CXCursor_ObjCInstanceMethodDecl));
6822 }
6823 }
6824
6825 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6826 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006827 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006828 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006829 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006830 &Context.Idents.get("range")
6831 };
6832
David Blaikie82e95a32014-11-19 07:49:47 +00006833 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006834 if (ReturnType.isNull()) {
6835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6836 Builder.AddTextChunk("void");
6837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6838 }
6839
6840 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6841 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6842 Builder.AddPlaceholderChunk("object-type");
6843 Builder.AddTextChunk(" **");
6844 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6845 Builder.AddTextChunk("buffer");
6846 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6847 Builder.AddTypedTextChunk("range:");
6848 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6849 Builder.AddTextChunk("NSRange");
6850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6851 Builder.AddTextChunk("inRange");
6852 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6853 CXCursor_ObjCInstanceMethodDecl));
6854 }
6855 }
6856
6857 // Mutable indexed accessors
6858
6859 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6860 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006861 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006862 IdentifierInfo *SelectorIds[2] = {
6863 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006864 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006865 };
6866
David Blaikie82e95a32014-11-19 07:49:47 +00006867 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006868 if (ReturnType.isNull()) {
6869 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6870 Builder.AddTextChunk("void");
6871 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6872 }
6873
6874 Builder.AddTypedTextChunk("insertObject:");
6875 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6876 Builder.AddPlaceholderChunk("object-type");
6877 Builder.AddTextChunk(" *");
6878 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6879 Builder.AddTextChunk("object");
6880 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6881 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6882 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6883 Builder.AddPlaceholderChunk("NSUInteger");
6884 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6885 Builder.AddTextChunk("index");
6886 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6887 CXCursor_ObjCInstanceMethodDecl));
6888 }
6889 }
6890
6891 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6892 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006893 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006894 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006895 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006896 &Context.Idents.get("atIndexes")
6897 };
6898
David Blaikie82e95a32014-11-19 07:49:47 +00006899 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006900 if (ReturnType.isNull()) {
6901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6902 Builder.AddTextChunk("void");
6903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6904 }
6905
6906 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6907 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6908 Builder.AddTextChunk("NSArray *");
6909 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6910 Builder.AddTextChunk("array");
6911 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6912 Builder.AddTypedTextChunk("atIndexes:");
6913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6914 Builder.AddPlaceholderChunk("NSIndexSet *");
6915 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6916 Builder.AddTextChunk("indexes");
6917 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6918 CXCursor_ObjCInstanceMethodDecl));
6919 }
6920 }
6921
6922 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6923 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006924 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006925 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006926 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006927 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006928 if (ReturnType.isNull()) {
6929 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6930 Builder.AddTextChunk("void");
6931 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6932 }
6933
6934 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6936 Builder.AddTextChunk("NSUInteger");
6937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6938 Builder.AddTextChunk("index");
6939 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6940 CXCursor_ObjCInstanceMethodDecl));
6941 }
6942 }
6943
6944 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6945 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006946 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006947 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006948 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006949 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006950 if (ReturnType.isNull()) {
6951 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6952 Builder.AddTextChunk("void");
6953 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6954 }
6955
6956 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6958 Builder.AddTextChunk("NSIndexSet *");
6959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6960 Builder.AddTextChunk("indexes");
6961 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6962 CXCursor_ObjCInstanceMethodDecl));
6963 }
6964 }
6965
6966 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6967 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006968 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006969 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006970 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006971 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006972 &Context.Idents.get("withObject")
6973 };
6974
David Blaikie82e95a32014-11-19 07:49:47 +00006975 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006976 if (ReturnType.isNull()) {
6977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6978 Builder.AddTextChunk("void");
6979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6980 }
6981
6982 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6983 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6984 Builder.AddPlaceholderChunk("NSUInteger");
6985 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6986 Builder.AddTextChunk("index");
6987 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6988 Builder.AddTypedTextChunk("withObject:");
6989 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6990 Builder.AddTextChunk("id");
6991 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6992 Builder.AddTextChunk("object");
6993 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6994 CXCursor_ObjCInstanceMethodDecl));
6995 }
6996 }
6997
6998 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6999 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007000 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007001 = (Twine("replace") + UpperKey + "AtIndexes").str();
7002 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007003 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007004 &Context.Idents.get(SelectorName1),
7005 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007006 };
7007
David Blaikie82e95a32014-11-19 07:49:47 +00007008 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007009 if (ReturnType.isNull()) {
7010 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7011 Builder.AddTextChunk("void");
7012 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7013 }
7014
7015 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7017 Builder.AddPlaceholderChunk("NSIndexSet *");
7018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7019 Builder.AddTextChunk("indexes");
7020 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7021 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7023 Builder.AddTextChunk("NSArray *");
7024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7025 Builder.AddTextChunk("array");
7026 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7027 CXCursor_ObjCInstanceMethodDecl));
7028 }
7029 }
7030
7031 // Unordered getters
7032 // - (NSEnumerator *)enumeratorOfKey
7033 if (IsInstanceMethod &&
7034 (ReturnType.isNull() ||
7035 (ReturnType->isObjCObjectPointerType() &&
7036 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7037 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7038 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007039 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007040 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007041 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7042 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007043 if (ReturnType.isNull()) {
7044 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7045 Builder.AddTextChunk("NSEnumerator *");
7046 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7047 }
7048
7049 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7050 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7051 CXCursor_ObjCInstanceMethodDecl));
7052 }
7053 }
7054
7055 // - (type *)memberOfKey:(type *)object
7056 if (IsInstanceMethod &&
7057 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007058 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007059 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007060 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007061 if (ReturnType.isNull()) {
7062 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7063 Builder.AddPlaceholderChunk("object-type");
7064 Builder.AddTextChunk(" *");
7065 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7066 }
7067
7068 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7069 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7070 if (ReturnType.isNull()) {
7071 Builder.AddPlaceholderChunk("object-type");
7072 Builder.AddTextChunk(" *");
7073 } else {
7074 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00007075 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00007076 Builder.getAllocator()));
7077 }
7078 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7079 Builder.AddTextChunk("object");
7080 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7081 CXCursor_ObjCInstanceMethodDecl));
7082 }
7083 }
7084
7085 // Mutable unordered accessors
7086 // - (void)addKeyObject:(type *)object
7087 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007088 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007089 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007090 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007091 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007092 if (ReturnType.isNull()) {
7093 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7094 Builder.AddTextChunk("void");
7095 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7096 }
7097
7098 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7100 Builder.AddPlaceholderChunk("object-type");
7101 Builder.AddTextChunk(" *");
7102 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7103 Builder.AddTextChunk("object");
7104 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7105 CXCursor_ObjCInstanceMethodDecl));
7106 }
7107 }
7108
7109 // - (void)addKey:(NSSet *)objects
7110 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007111 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007112 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007113 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007114 if (ReturnType.isNull()) {
7115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7116 Builder.AddTextChunk("void");
7117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7118 }
7119
7120 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7121 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7122 Builder.AddTextChunk("NSSet *");
7123 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7124 Builder.AddTextChunk("objects");
7125 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7126 CXCursor_ObjCInstanceMethodDecl));
7127 }
7128 }
7129
7130 // - (void)removeKeyObject:(type *)object
7131 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007132 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007133 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007134 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007135 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007136 if (ReturnType.isNull()) {
7137 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7138 Builder.AddTextChunk("void");
7139 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7140 }
7141
7142 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7143 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7144 Builder.AddPlaceholderChunk("object-type");
7145 Builder.AddTextChunk(" *");
7146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7147 Builder.AddTextChunk("object");
7148 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7149 CXCursor_ObjCInstanceMethodDecl));
7150 }
7151 }
7152
7153 // - (void)removeKey:(NSSet *)objects
7154 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007155 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007156 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007157 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007158 if (ReturnType.isNull()) {
7159 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7160 Builder.AddTextChunk("void");
7161 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7162 }
7163
7164 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7165 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7166 Builder.AddTextChunk("NSSet *");
7167 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7168 Builder.AddTextChunk("objects");
7169 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7170 CXCursor_ObjCInstanceMethodDecl));
7171 }
7172 }
7173
7174 // - (void)intersectKey:(NSSet *)objects
7175 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007176 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007177 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007178 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007179 if (ReturnType.isNull()) {
7180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7181 Builder.AddTextChunk("void");
7182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7183 }
7184
7185 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7186 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7187 Builder.AddTextChunk("NSSet *");
7188 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7189 Builder.AddTextChunk("objects");
7190 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7191 CXCursor_ObjCInstanceMethodDecl));
7192 }
7193 }
7194
7195 // Key-Value Observing
7196 // + (NSSet *)keyPathsForValuesAffectingKey
7197 if (!IsInstanceMethod &&
7198 (ReturnType.isNull() ||
7199 (ReturnType->isObjCObjectPointerType() &&
7200 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7201 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7202 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007203 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007204 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007205 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007206 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7207 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007208 if (ReturnType.isNull()) {
7209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Alex Lorenz71ecb072016-12-08 16:49:05 +00007210 Builder.AddTextChunk("NSSet<NSString *> *");
Douglas Gregor669a25a2011-02-17 00:22:45 +00007211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7212 }
7213
7214 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7215 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007216 CXCursor_ObjCClassMethodDecl));
7217 }
7218 }
7219
7220 // + (BOOL)automaticallyNotifiesObserversForKey
7221 if (!IsInstanceMethod &&
7222 (ReturnType.isNull() ||
7223 ReturnType->isIntegerType() ||
7224 ReturnType->isBooleanType())) {
7225 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007226 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007227 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007228 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7229 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007230 if (ReturnType.isNull()) {
7231 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7232 Builder.AddTextChunk("BOOL");
7233 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7234 }
7235
7236 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7237 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7238 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007239 }
7240 }
7241}
7242
Douglas Gregor636a61e2010-04-07 00:21:17 +00007243void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7244 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007245 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007246 // Determine the return type of the method we're declaring, if
7247 // provided.
7248 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007249 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007250 if (CurContext->isObjCContainer()) {
7251 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7252 IDecl = cast<Decl>(OCD);
7253 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007254 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007255 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007256 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007257 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007258 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7259 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007260 IsInImplementation = true;
7261 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007262 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007263 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007264 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007265 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007266 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007267 }
7268
7269 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007270 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007271 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007272 }
7273
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007274 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007275 HandleCodeCompleteResults(this, CodeCompleter,
7276 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007277 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007278 return;
7279 }
7280
7281 // Find all of the methods that we could declare/implement here.
7282 KnownMethodsMap KnownMethods;
7283 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007284 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007285
Douglas Gregor636a61e2010-04-07 00:21:17 +00007286 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007287 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007288 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007289 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007290 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007291 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007292 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007293 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7294 MEnd = KnownMethods.end();
7295 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007296 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007297 CodeCompletionBuilder Builder(Results.getAllocator(),
7298 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007299
7300 // If the result type was not already provided, add it to the
7301 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007302 if (ReturnType.isNull()) {
7303 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7304 AttributedType::stripOuterNullability(ResTy);
7305 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007306 Method->getObjCDeclQualifier(), Context, Policy,
7307 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007308 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007309
7310 Selector Sel = Method->getSelector();
7311
7312 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007313 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007314 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007315
7316 // Add parameters to the pattern.
7317 unsigned I = 0;
7318 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7319 PEnd = Method->param_end();
7320 P != PEnd; (void)++P, ++I) {
7321 // Add the part of the selector name.
7322 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007323 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007324 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007325 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7326 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007327 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007328 } else
7329 break;
7330
7331 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007332 QualType ParamType;
7333 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7334 ParamType = (*P)->getType();
7335 else
7336 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007337 ParamType = ParamType.substObjCTypeArgs(Context, {},
7338 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007339 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007340 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007341 (*P)->getObjCDeclQualifier(),
7342 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007343 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007344
7345 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007346 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007347 }
7348
7349 if (Method->isVariadic()) {
7350 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007351 Builder.AddChunk(CodeCompletionString::CK_Comma);
7352 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007353 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007354
Douglas Gregord37c59d2010-05-28 00:57:46 +00007355 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007356 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007357 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7358 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7359 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007360 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007361 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007362 Builder.AddTextChunk("return");
7363 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7364 Builder.AddPlaceholderChunk("expression");
7365 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007366 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007367 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007368
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007369 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7370 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007371 }
7372
Douglas Gregor416b5752010-08-25 01:08:01 +00007373 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007374 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007375 Priority += CCD_InBaseClass;
7376
Douglas Gregor78254c82012-03-27 23:34:16 +00007377 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007378 }
7379
Douglas Gregor669a25a2011-02-17 00:22:45 +00007380 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7381 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007382 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007383 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007384 Containers.push_back(SearchDecl);
7385
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007386 VisitedSelectorSet KnownSelectors;
7387 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7388 MEnd = KnownMethods.end();
7389 M != MEnd; ++M)
7390 KnownSelectors.insert(M->first);
7391
7392
Douglas Gregor669a25a2011-02-17 00:22:45 +00007393 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7394 if (!IFace)
7395 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7396 IFace = Category->getClassInterface();
7397
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007398 if (IFace)
7399 for (auto *Cat : IFace->visible_categories())
7400 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007401
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007402 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007403 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007404 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007405 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007406 }
7407
Douglas Gregor636a61e2010-04-07 00:21:17 +00007408 Results.ExitScope();
7409
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007410 HandleCodeCompleteResults(this, CodeCompleter,
7411 CodeCompletionContext::CCC_Other,
7412 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007413}
Douglas Gregor95887f92010-07-08 23:20:03 +00007414
7415void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7416 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007417 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007418 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007419 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007420 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007421 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007422 if (ExternalSource) {
7423 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7424 I != N; ++I) {
7425 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007426 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007427 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007428
7429 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007430 }
7431 }
7432
7433 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007434 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007435 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007436 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007437 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007438
7439 if (ReturnTy)
7440 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007441
Douglas Gregor95887f92010-07-08 23:20:03 +00007442 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007443 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7444 MEnd = MethodPool.end();
7445 M != MEnd; ++M) {
7446 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7447 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007448 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007449 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007450 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007451 continue;
7452
Douglas Gregor45879692010-07-08 23:37:41 +00007453 if (AtParameterName) {
7454 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007455 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007456 if (NumSelIdents &&
7457 NumSelIdents <= MethList->getMethod()->param_size()) {
7458 ParmVarDecl *Param =
7459 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007460 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007461 CodeCompletionBuilder Builder(Results.getAllocator(),
7462 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007463 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007464 Param->getIdentifier()->getName()));
7465 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007466 }
7467 }
7468
7469 continue;
7470 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007471
Nico Weber2e0c8f72014-12-27 03:58:08 +00007472 Result R(MethList->getMethod(),
7473 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007474 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007475 R.AllParametersAreInformative = false;
7476 R.DeclaringEntity = true;
7477 Results.MaybeAddResult(R, CurContext);
7478 }
7479 }
7480
7481 Results.ExitScope();
Alex Lorenz847fda12017-01-03 11:56:40 +00007482
7483 if (!AtParameterName && !SelIdents.empty() &&
7484 SelIdents.front()->getName().startswith("init")) {
7485 for (const auto &M : PP.macros()) {
7486 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7487 continue;
7488 Results.EnterNewScope();
7489 CodeCompletionBuilder Builder(Results.getAllocator(),
7490 Results.getCodeCompletionTUInfo());
7491 Builder.AddTypedTextChunk(
7492 Builder.getAllocator().CopyString(M.first->getName()));
7493 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7494 CXCursor_MacroDefinition));
7495 Results.ExitScope();
7496 }
7497 }
7498
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007499 HandleCodeCompleteResults(this, CodeCompleter,
7500 CodeCompletionContext::CCC_Other,
7501 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007502}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007503
Douglas Gregorec00a262010-08-24 22:20:20 +00007504void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007505 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007506 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007507 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007508 Results.EnterNewScope();
7509
7510 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007511 CodeCompletionBuilder Builder(Results.getAllocator(),
7512 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007513 Builder.AddTypedTextChunk("if");
7514 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7515 Builder.AddPlaceholderChunk("condition");
7516 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007517
7518 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007519 Builder.AddTypedTextChunk("ifdef");
7520 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7521 Builder.AddPlaceholderChunk("macro");
7522 Results.AddResult(Builder.TakeString());
7523
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007524 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007525 Builder.AddTypedTextChunk("ifndef");
7526 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7527 Builder.AddPlaceholderChunk("macro");
7528 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007529
7530 if (InConditional) {
7531 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007532 Builder.AddTypedTextChunk("elif");
7533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7534 Builder.AddPlaceholderChunk("condition");
7535 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007536
7537 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007538 Builder.AddTypedTextChunk("else");
7539 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007540
7541 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007542 Builder.AddTypedTextChunk("endif");
7543 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007544 }
7545
7546 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007547 Builder.AddTypedTextChunk("include");
7548 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7549 Builder.AddTextChunk("\"");
7550 Builder.AddPlaceholderChunk("header");
7551 Builder.AddTextChunk("\"");
7552 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007553
7554 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007555 Builder.AddTypedTextChunk("include");
7556 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7557 Builder.AddTextChunk("<");
7558 Builder.AddPlaceholderChunk("header");
7559 Builder.AddTextChunk(">");
7560 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007561
7562 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007563 Builder.AddTypedTextChunk("define");
7564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7565 Builder.AddPlaceholderChunk("macro");
7566 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007567
7568 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007569 Builder.AddTypedTextChunk("define");
7570 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7571 Builder.AddPlaceholderChunk("macro");
7572 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7573 Builder.AddPlaceholderChunk("args");
7574 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7575 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007576
7577 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007578 Builder.AddTypedTextChunk("undef");
7579 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7580 Builder.AddPlaceholderChunk("macro");
7581 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007582
7583 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007584 Builder.AddTypedTextChunk("line");
7585 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7586 Builder.AddPlaceholderChunk("number");
7587 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007588
7589 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007590 Builder.AddTypedTextChunk("line");
7591 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7592 Builder.AddPlaceholderChunk("number");
7593 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7594 Builder.AddTextChunk("\"");
7595 Builder.AddPlaceholderChunk("filename");
7596 Builder.AddTextChunk("\"");
7597 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007598
7599 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007600 Builder.AddTypedTextChunk("error");
7601 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7602 Builder.AddPlaceholderChunk("message");
7603 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007604
7605 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007606 Builder.AddTypedTextChunk("pragma");
7607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7608 Builder.AddPlaceholderChunk("arguments");
7609 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007610
David Blaikiebbafb8a2012-03-11 07:00:24 +00007611 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007612 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007613 Builder.AddTypedTextChunk("import");
7614 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7615 Builder.AddTextChunk("\"");
7616 Builder.AddPlaceholderChunk("header");
7617 Builder.AddTextChunk("\"");
7618 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007619
7620 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007621 Builder.AddTypedTextChunk("import");
7622 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7623 Builder.AddTextChunk("<");
7624 Builder.AddPlaceholderChunk("header");
7625 Builder.AddTextChunk(">");
7626 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007627 }
7628
7629 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007630 Builder.AddTypedTextChunk("include_next");
7631 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7632 Builder.AddTextChunk("\"");
7633 Builder.AddPlaceholderChunk("header");
7634 Builder.AddTextChunk("\"");
7635 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007636
7637 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007638 Builder.AddTypedTextChunk("include_next");
7639 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7640 Builder.AddTextChunk("<");
7641 Builder.AddPlaceholderChunk("header");
7642 Builder.AddTextChunk(">");
7643 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007644
7645 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007646 Builder.AddTypedTextChunk("warning");
7647 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7648 Builder.AddPlaceholderChunk("message");
7649 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007650
7651 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7652 // completions for them. And __include_macros is a Clang-internal extension
7653 // that we don't want to encourage anyone to use.
7654
7655 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7656 Results.ExitScope();
7657
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007658 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007659 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007660 Results.data(), Results.size());
7661}
7662
7663void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007664 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007665 S->getFnParent()? Sema::PCC_RecoveryInFunction
7666 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007667}
7668
Douglas Gregorec00a262010-08-24 22:20:20 +00007669void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007670 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007671 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007672 IsDefinition? CodeCompletionContext::CCC_MacroName
7673 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007674 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7675 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007676 CodeCompletionBuilder Builder(Results.getAllocator(),
7677 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007678 Results.EnterNewScope();
7679 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7680 MEnd = PP.macro_end();
7681 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007682 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007683 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007684 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7685 CCP_CodePattern,
7686 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007687 }
7688 Results.ExitScope();
7689 } else if (IsDefinition) {
7690 // FIXME: Can we detect when the user just wrote an include guard above?
7691 }
7692
Douglas Gregor0ac41382010-09-23 23:01:17 +00007693 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007694 Results.data(), Results.size());
7695}
7696
Douglas Gregorec00a262010-08-24 22:20:20 +00007697void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007698 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007699 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007700 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007701
7702 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007703 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007704
7705 // defined (<macro>)
7706 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007707 CodeCompletionBuilder Builder(Results.getAllocator(),
7708 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007709 Builder.AddTypedTextChunk("defined");
7710 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7711 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7712 Builder.AddPlaceholderChunk("macro");
7713 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7714 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007715 Results.ExitScope();
7716
7717 HandleCodeCompleteResults(this, CodeCompleter,
7718 CodeCompletionContext::CCC_PreprocessorExpression,
7719 Results.data(), Results.size());
7720}
7721
7722void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7723 IdentifierInfo *Macro,
7724 MacroInfo *MacroInfo,
7725 unsigned Argument) {
7726 // FIXME: In the future, we could provide "overload" results, much like we
7727 // do for function calls.
7728
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007729 // Now just ignore this. There will be another code-completion callback
7730 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007731}
7732
Douglas Gregor11583702010-08-25 17:04:25 +00007733void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007734 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007735 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007736 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007737}
7738
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007739void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007740 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007741 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007742 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7743 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007744 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7745 CodeCompletionDeclConsumer Consumer(Builder,
7746 Context.getTranslationUnitDecl());
7747 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7748 Consumer);
7749 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007750
7751 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007752 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007753
7754 Results.clear();
7755 Results.insert(Results.end(),
7756 Builder.data(), Builder.data() + Builder.size());
7757}