blob: 6000fc666632da07677133ee66b50899dd638ba3 [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,
2215 bool SuppressBlock = false,
2216 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2217
Richard Smith20e883e2015-04-29 23:20:19 +00002218static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002219 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002220 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002221 bool SuppressBlock = false,
2222 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002223 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2224 if (Param->getType()->isDependentType() ||
2225 !Param->getType()->isBlockPointerType()) {
2226 // The argument for a dependent or non-block parameter is a placeholder
2227 // containing that parameter's type.
2228 std::string Result;
2229
Douglas Gregor981a0c42010-08-29 19:47:46 +00002230 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002231 Result = Param->getIdentifier()->getName();
2232
Douglas Gregor86b42682015-06-19 18:27:52 +00002233 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002234 if (ObjCSubsts)
2235 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2236 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002237 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002238 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2239 Type);
2240 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002241 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002242 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002243 } else {
2244 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002245 }
2246 return Result;
2247 }
Alex Lorenza1951202016-10-18 10:35:27 +00002248
Douglas Gregore90dd002010-08-24 16:15:59 +00002249 // The argument for a block pointer parameter is a block literal with
2250 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002251 FunctionTypeLoc Block;
2252 FunctionProtoTypeLoc BlockProto;
Alex Lorenza1951202016-10-18 10:35:27 +00002253 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2254 SuppressBlock);
Douglas Gregore90dd002010-08-24 16:15:59 +00002255
2256 if (!Block) {
2257 // We were unable to find a FunctionProtoTypeLoc with parameter names
2258 // for the block; just use the parameter type as a placeholder.
2259 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002260 if (!ObjCMethodParam && Param->getIdentifier())
2261 Result = Param->getIdentifier()->getName();
2262
Douglas Gregor86b42682015-06-19 18:27:52 +00002263 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002264
2265 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002266 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2267 Type);
2268 Result += Type.getAsString(Policy) + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002269 if (Param->getIdentifier())
2270 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002271 } else {
2272 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002273 }
2274
2275 return Result;
2276 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002277
Douglas Gregore90dd002010-08-24 16:15:59 +00002278 // We have the function prototype behind the block pointer type, as it was
2279 // written in the source.
Alex Lorenz920ae142016-10-18 10:38:58 +00002280 return formatBlockPlaceholder(Policy, Param, Block, BlockProto, SuppressBlock,
2281 ObjCSubsts);
2282}
2283
2284/// \brief Returns a placeholder string that corresponds to an Objective-C block
2285/// declaration.
2286///
2287/// \param BlockDecl A declaration with an Objective-C block type.
2288///
2289/// \param Block The most relevant type location for that block type.
2290///
2291/// \param SuppressBlockName Determines wether or not the name of the block
2292/// declaration is included in the resulting string.
2293static std::string
2294formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2295 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2296 bool SuppressBlock,
2297 Optional<ArrayRef<QualType>> ObjCSubsts) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002298 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002299 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002300 if (ObjCSubsts)
Alex Lorenz920ae142016-10-18 10:38:58 +00002301 ResultType =
2302 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2303 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002304 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002305 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002306
2307 // Format the parameter list.
2308 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002309 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002310 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002311 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002312 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002313 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002314 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002315 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002316 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002317 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002318 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002319 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002320 /*SuppressName=*/false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002321 /*SuppressBlock=*/true, ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002322
David Blaikie6adc78e2013-02-18 22:06:02 +00002323 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002324 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002325 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002326 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002327 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002328
Douglas Gregord793e7c2011-10-18 04:23:19 +00002329 if (SuppressBlock) {
2330 // Format as a parameter.
2331 Result = Result + " (^";
Alex Lorenz920ae142016-10-18 10:38:58 +00002332 if (BlockDecl->getIdentifier())
2333 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002334 Result += ")";
2335 Result += Params;
2336 } else {
2337 // Format as a block literal argument.
2338 Result = '^' + Result;
2339 Result += Params;
Alex Lorenz920ae142016-10-18 10:38:58 +00002340
2341 if (BlockDecl->getIdentifier())
2342 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002343 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002344
Douglas Gregore90dd002010-08-24 16:15:59 +00002345 return Result;
2346}
2347
Douglas Gregor3545ff42009-09-21 16:56:56 +00002348/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002349static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002350 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002351 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002352 CodeCompletionBuilder &Result,
2353 unsigned Start = 0,
2354 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002355 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002356
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002357 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002358 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002359
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002360 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002361 // When we see an optional default argument, put that argument and
2362 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002363 CodeCompletionBuilder Opt(Result.getAllocator(),
2364 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002365 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002366 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002367 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002368 Result.AddOptionalChunk(Opt.TakeString());
2369 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002370 }
2371
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002372 if (FirstParameter)
2373 FirstParameter = false;
2374 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002375 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002376
2377 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002378
2379 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002380 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2381
Douglas Gregor400f5972010-08-31 05:13:43 +00002382 if (Function->isVariadic() && P == N - 1)
2383 PlaceholderStr += ", ...";
2384
Douglas Gregor3545ff42009-09-21 16:56:56 +00002385 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002386 Result.AddPlaceholderChunk(
2387 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002388 }
Douglas Gregorba449032009-09-22 21:42:17 +00002389
2390 if (const FunctionProtoType *Proto
2391 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002392 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002393 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002394 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002395
Richard Smith20e883e2015-04-29 23:20:19 +00002396 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002397 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002398}
2399
2400/// \brief Add template parameter chunks to the given code completion string.
2401static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002402 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002403 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002404 CodeCompletionBuilder &Result,
2405 unsigned MaxParameters = 0,
2406 unsigned Start = 0,
2407 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002408 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002409
2410 // Prefer to take the template parameter names from the first declaration of
2411 // the template.
2412 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2413
Douglas Gregor3545ff42009-09-21 16:56:56 +00002414 TemplateParameterList *Params = Template->getTemplateParameters();
2415 TemplateParameterList::iterator PEnd = Params->end();
2416 if (MaxParameters)
2417 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002418 for (TemplateParameterList::iterator P = Params->begin() + Start;
2419 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002420 bool HasDefaultArg = false;
2421 std::string PlaceholderStr;
2422 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2423 if (TTP->wasDeclaredWithTypename())
2424 PlaceholderStr = "typename";
2425 else
2426 PlaceholderStr = "class";
2427
2428 if (TTP->getIdentifier()) {
2429 PlaceholderStr += ' ';
2430 PlaceholderStr += TTP->getIdentifier()->getName();
2431 }
2432
2433 HasDefaultArg = TTP->hasDefaultArgument();
2434 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002435 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002436 if (NTTP->getIdentifier())
2437 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002438 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002439 HasDefaultArg = NTTP->hasDefaultArgument();
2440 } else {
2441 assert(isa<TemplateTemplateParmDecl>(*P));
2442 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2443
2444 // Since putting the template argument list into the placeholder would
2445 // be very, very long, we just use an abbreviation.
2446 PlaceholderStr = "template<...> class";
2447 if (TTP->getIdentifier()) {
2448 PlaceholderStr += ' ';
2449 PlaceholderStr += TTP->getIdentifier()->getName();
2450 }
2451
2452 HasDefaultArg = TTP->hasDefaultArgument();
2453 }
2454
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002455 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002456 // When we see an optional default argument, put that argument and
2457 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002458 CodeCompletionBuilder Opt(Result.getAllocator(),
2459 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002460 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002461 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002462 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002463 P - Params->begin(), true);
2464 Result.AddOptionalChunk(Opt.TakeString());
2465 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002466 }
2467
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002468 InDefaultArg = false;
2469
Douglas Gregor3545ff42009-09-21 16:56:56 +00002470 if (FirstParameter)
2471 FirstParameter = false;
2472 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002473 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002474
2475 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002476 Result.AddPlaceholderChunk(
2477 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002478 }
2479}
2480
Douglas Gregorf2510672009-09-21 19:57:38 +00002481/// \brief Add a qualifier to the given code-completion string, if the
2482/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002483static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002484AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002485 NestedNameSpecifier *Qualifier,
2486 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002487 ASTContext &Context,
2488 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002489 if (!Qualifier)
2490 return;
2491
2492 std::string PrintedNNS;
2493 {
2494 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002495 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002496 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002497 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002498 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002499 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002500 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002501}
2502
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002503static void
2504AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002505 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002506 const FunctionProtoType *Proto
2507 = Function->getType()->getAs<FunctionProtoType>();
2508 if (!Proto || !Proto->getTypeQuals())
2509 return;
2510
Douglas Gregor304f9b02011-02-01 21:15:40 +00002511 // FIXME: Add ref-qualifier!
2512
2513 // Handle single qualifiers without copying
2514 if (Proto->getTypeQuals() == Qualifiers::Const) {
2515 Result.AddInformativeChunk(" const");
2516 return;
2517 }
2518
2519 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2520 Result.AddInformativeChunk(" volatile");
2521 return;
2522 }
2523
2524 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2525 Result.AddInformativeChunk(" restrict");
2526 return;
2527 }
2528
2529 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002530 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002531 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002532 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002533 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002534 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002535 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002536 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002537 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002538}
2539
Douglas Gregor0212fd72010-09-21 16:06:22 +00002540/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002541static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002542 const NamedDecl *ND,
2543 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002544 DeclarationName Name = ND->getDeclName();
2545 if (!Name)
2546 return;
2547
2548 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002549 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002550 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002551 switch (Name.getCXXOverloadedOperator()) {
2552 case OO_None:
2553 case OO_Conditional:
2554 case NUM_OVERLOADED_OPERATORS:
2555 OperatorName = "operator";
2556 break;
2557
2558#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2559 case OO_##Name: OperatorName = "operator" Spelling; break;
2560#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2561#include "clang/Basic/OperatorKinds.def"
2562
2563 case OO_New: OperatorName = "operator new"; break;
2564 case OO_Delete: OperatorName = "operator delete"; break;
2565 case OO_Array_New: OperatorName = "operator new[]"; break;
2566 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2567 case OO_Call: OperatorName = "operator()"; break;
2568 case OO_Subscript: OperatorName = "operator[]"; break;
2569 }
2570 Result.AddTypedTextChunk(OperatorName);
2571 break;
2572 }
2573
Douglas Gregor0212fd72010-09-21 16:06:22 +00002574 case DeclarationName::Identifier:
2575 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002576 case DeclarationName::CXXDestructorName:
2577 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002578 Result.AddTypedTextChunk(
2579 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002580 break;
2581
2582 case DeclarationName::CXXUsingDirective:
2583 case DeclarationName::ObjCZeroArgSelector:
2584 case DeclarationName::ObjCOneArgSelector:
2585 case DeclarationName::ObjCMultiArgSelector:
2586 break;
2587
2588 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002589 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002590 QualType Ty = Name.getCXXNameType();
2591 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2592 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2593 else if (const InjectedClassNameType *InjectedTy
2594 = Ty->getAs<InjectedClassNameType>())
2595 Record = InjectedTy->getDecl();
2596 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002597 Result.AddTypedTextChunk(
2598 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002599 break;
2600 }
2601
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002602 Result.AddTypedTextChunk(
2603 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002604 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002605 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002606 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002607 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002608 }
2609 break;
2610 }
2611 }
2612}
2613
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002614CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002615 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002616 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002617 CodeCompletionTUInfo &CCTUInfo,
2618 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002619 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2620 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002621}
2622
Douglas Gregor3545ff42009-09-21 16:56:56 +00002623/// \brief If possible, create a new code completion string for the given
2624/// result.
2625///
2626/// \returns Either a new, heap-allocated code completion string describing
2627/// how to use this result, or NULL to indicate that the string or name of the
2628/// result is all that is needed.
2629CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002630CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2631 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002632 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002633 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002634 CodeCompletionTUInfo &CCTUInfo,
2635 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002636 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002637
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002638 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002639 if (Kind == RK_Pattern) {
2640 Pattern->Priority = Priority;
2641 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002642
2643 if (Declaration) {
2644 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002645 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002646 // Provide code completion comment for self.GetterName where
2647 // GetterName is the getter method for a property with name
2648 // different from the property name (declared via a property
2649 // getter attribute.
2650 const NamedDecl *ND = Declaration;
2651 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2652 if (M->isPropertyAccessor())
2653 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2654 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002655 PDecl->getIdentifier() != M->getIdentifier()) {
2656 if (const RawComment *RC =
2657 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002658 Result.addBriefComment(RC->getBriefText(Ctx));
2659 Pattern->BriefComment = Result.getBriefComment();
2660 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002661 else if (const RawComment *RC =
2662 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2663 Result.addBriefComment(RC->getBriefText(Ctx));
2664 Pattern->BriefComment = Result.getBriefComment();
2665 }
2666 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002667 }
2668
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002669 return Pattern;
2670 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002671
Douglas Gregorf09935f2009-12-01 05:55:20 +00002672 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002673 Result.AddTypedTextChunk(Keyword);
2674 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002675 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002676
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002677 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002678 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002679 Result.AddTypedTextChunk(
2680 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002681
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002682 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002683 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002684
2685 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002686 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002687 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002688
2689 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2690 if (MI->isC99Varargs()) {
2691 --AEnd;
2692
2693 if (A == AEnd) {
2694 Result.AddPlaceholderChunk("...");
2695 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002696 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002697
Douglas Gregor0c505312011-07-30 08:17:44 +00002698 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002699 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002700 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002701
2702 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002703 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002704 if (MI->isC99Varargs())
2705 Arg += ", ...";
2706 else
2707 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002708 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002709 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002710 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002711
2712 // Non-variadic macros are simple.
2713 Result.AddPlaceholderChunk(
2714 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002715 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002716 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002717 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002718 }
2719
Douglas Gregorf64acca2010-05-25 21:41:55 +00002720 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002721 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002722 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002723
2724 if (IncludeBriefComments) {
2725 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002726 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002727 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002728 }
2729 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2730 if (OMD->isPropertyAccessor())
2731 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2732 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2733 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002734 }
2735
Douglas Gregor9eb77012009-11-07 00:00:49 +00002736 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002737 Result.AddTypedTextChunk(
2738 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002739 Result.AddTextChunk("::");
2740 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002741 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002742
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002743 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2744 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002745
Douglas Gregorc3425b12015-07-07 06:20:19 +00002746 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002747
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002748 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002749 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002750 Ctx, Policy);
2751 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002752 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002753 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002754 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002755 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002756 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002757 }
2758
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002759 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002760 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002761 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002762 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002763 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002764
Douglas Gregor3545ff42009-09-21 16:56:56 +00002765 // Figure out which template parameters are deduced (or have default
2766 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002767 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002768 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002769 unsigned LastDeducibleArgument;
2770 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2771 --LastDeducibleArgument) {
2772 if (!Deduced[LastDeducibleArgument - 1]) {
2773 // C++0x: Figure out if the template argument has a default. If so,
2774 // the user doesn't need to type this argument.
2775 // FIXME: We need to abstract template parameters better!
2776 bool HasDefaultArg = false;
2777 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002778 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002779 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2780 HasDefaultArg = TTP->hasDefaultArgument();
2781 else if (NonTypeTemplateParmDecl *NTTP
2782 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2783 HasDefaultArg = NTTP->hasDefaultArgument();
2784 else {
2785 assert(isa<TemplateTemplateParmDecl>(Param));
2786 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002787 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002788 }
2789
2790 if (!HasDefaultArg)
2791 break;
2792 }
2793 }
2794
2795 if (LastDeducibleArgument) {
2796 // Some of the function template arguments cannot be deduced from a
2797 // function call, so we introduce an explicit template argument list
2798 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002799 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002800 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002801 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002802 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002803 }
2804
2805 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002806 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002807 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002808 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002809 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002810 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002811 }
2812
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002813 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002814 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002815 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002816 Result.AddTypedTextChunk(
2817 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002818 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002819 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002820 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002821 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002822 }
2823
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002824 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002825 Selector Sel = Method->getSelector();
2826 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002827 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002828 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002829 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002830 }
2831
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002832 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002833 SelName += ':';
2834 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002835 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002836 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002837 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002838
2839 // If there is only one parameter, and we're past it, add an empty
2840 // typed-text chunk since there is nothing to type.
2841 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002842 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002843 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002844 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002845 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2846 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002847 P != PEnd; (void)++P, ++Idx) {
2848 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002849 std::string Keyword;
2850 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002851 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002852 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002853 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002854 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002855 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002856 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002857 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002858 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002859 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002860
2861 // If we're before the starting parameter, skip the placeholder.
2862 if (Idx < StartParameter)
2863 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002864
2865 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002866 QualType ParamType = (*P)->getType();
2867 Optional<ArrayRef<QualType>> ObjCSubsts;
2868 if (!CCContext.getBaseType().isNull())
2869 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2870
2871 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2872 Arg = FormatFunctionParameter(Policy, *P, true,
2873 /*SuppressBlock=*/false,
2874 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002875 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002876 if (ObjCSubsts)
2877 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2878 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002879 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002880 ParamType);
2881 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002882 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002883 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002884 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002885 }
2886
Douglas Gregor400f5972010-08-31 05:13:43 +00002887 if (Method->isVariadic() && (P + 1) == PEnd)
2888 Arg += ", ...";
2889
Douglas Gregor95887f92010-07-08 23:20:03 +00002890 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002891 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002892 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002893 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002894 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002895 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002896 }
2897
Douglas Gregor04c5f972009-12-23 00:21:46 +00002898 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002899 if (Method->param_size() == 0) {
2900 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002901 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002902 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002903 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002904 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002905 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002906 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002907
Richard Smith20e883e2015-04-29 23:20:19 +00002908 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002909 }
2910
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002911 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002912 }
2913
Douglas Gregorf09935f2009-12-01 05:55:20 +00002914 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002915 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002916 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002917
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002918 Result.AddTypedTextChunk(
2919 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002920 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002921}
2922
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002923/// \brief Add function overload parameter chunks to the given code completion
2924/// string.
2925static void AddOverloadParameterChunks(ASTContext &Context,
2926 const PrintingPolicy &Policy,
2927 const FunctionDecl *Function,
2928 const FunctionProtoType *Prototype,
2929 CodeCompletionBuilder &Result,
2930 unsigned CurrentArg,
2931 unsigned Start = 0,
2932 bool InOptional = false) {
2933 bool FirstParameter = true;
2934 unsigned NumParams = Function ? Function->getNumParams()
2935 : Prototype->getNumParams();
2936
2937 for (unsigned P = Start; P != NumParams; ++P) {
2938 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2939 // When we see an optional default argument, put that argument and
2940 // the remaining default arguments into a new, optional string.
2941 CodeCompletionBuilder Opt(Result.getAllocator(),
2942 Result.getCodeCompletionTUInfo());
2943 if (!FirstParameter)
2944 Opt.AddChunk(CodeCompletionString::CK_Comma);
2945 // Optional sections are nested.
2946 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2947 CurrentArg, P, /*InOptional=*/true);
2948 Result.AddOptionalChunk(Opt.TakeString());
2949 return;
2950 }
2951
2952 if (FirstParameter)
2953 FirstParameter = false;
2954 else
2955 Result.AddChunk(CodeCompletionString::CK_Comma);
2956
2957 InOptional = false;
2958
2959 // Format the placeholder string.
2960 std::string Placeholder;
2961 if (Function)
Richard Smith20e883e2015-04-29 23:20:19 +00002962 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002963 else
2964 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2965
2966 if (P == CurrentArg)
2967 Result.AddCurrentParameterChunk(
2968 Result.getAllocator().CopyString(Placeholder));
2969 else
2970 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2971 }
2972
2973 if (Prototype && Prototype->isVariadic()) {
2974 CodeCompletionBuilder Opt(Result.getAllocator(),
2975 Result.getCodeCompletionTUInfo());
2976 if (!FirstParameter)
2977 Opt.AddChunk(CodeCompletionString::CK_Comma);
2978
2979 if (CurrentArg < NumParams)
2980 Opt.AddPlaceholderChunk("...");
2981 else
2982 Opt.AddCurrentParameterChunk("...");
2983
2984 Result.AddOptionalChunk(Opt.TakeString());
2985 }
2986}
2987
Douglas Gregorf0f51982009-09-23 00:34:09 +00002988CodeCompletionString *
2989CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002990 unsigned CurrentArg, Sema &S,
2991 CodeCompletionAllocator &Allocator,
2992 CodeCompletionTUInfo &CCTUInfo,
2993 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002994 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002995
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002996 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002997 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002998 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002999 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00003000 = dyn_cast<FunctionProtoType>(getFunctionType());
3001 if (!FDecl && !Proto) {
3002 // Function without a prototype. Just give the return type and a
3003 // highlighted ellipsis.
3004 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003005 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3006 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003007 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3008 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3009 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003010 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003011 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003012
3013 if (FDecl) {
3014 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3015 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3016 FDecl->getParamDecl(CurrentArg)))
3017 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00003018 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003019 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003020 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3021 } else {
3022 Result.AddResultTypeChunk(
3023 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00003024 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003025 }
Alp Toker314cc812014-01-25 16:55:45 +00003026
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003027 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003028 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3029 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003030 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003031
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003032 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003033}
3034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003035unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003036 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00003037 bool PreferredTypeIsPointer) {
3038 unsigned Priority = CCP_Macro;
3039
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003040 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3041 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3042 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00003043 Priority = CCP_Constant;
3044 if (PreferredTypeIsPointer)
3045 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003046 }
3047 // Treat "YES", "NO", "true", and "false" as constants.
3048 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3049 MacroName.equals("true") || MacroName.equals("false"))
3050 Priority = CCP_Constant;
3051 // Treat "bool" as a type.
3052 else if (MacroName.equals("bool"))
3053 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3054
Douglas Gregor6e240332010-08-16 16:18:59 +00003055
3056 return Priority;
3057}
3058
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003059CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003060 if (!D)
3061 return CXCursor_UnexposedDecl;
3062
3063 switch (D->getKind()) {
3064 case Decl::Enum: return CXCursor_EnumDecl;
3065 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3066 case Decl::Field: return CXCursor_FieldDecl;
3067 case Decl::Function:
3068 return CXCursor_FunctionDecl;
3069 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3070 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003071 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003072
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003073 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003074 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3075 case Decl::ObjCMethod:
3076 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3077 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3078 case Decl::CXXMethod: return CXCursor_CXXMethod;
3079 case Decl::CXXConstructor: return CXCursor_Constructor;
3080 case Decl::CXXDestructor: return CXCursor_Destructor;
3081 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3082 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003083 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003084 case Decl::ParmVar: return CXCursor_ParmDecl;
3085 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003086 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003087 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003088 case Decl::Var: return CXCursor_VarDecl;
3089 case Decl::Namespace: return CXCursor_Namespace;
3090 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3091 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3092 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3093 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3094 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3095 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003096 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003097 case Decl::ClassTemplatePartialSpecialization:
3098 return CXCursor_ClassTemplatePartialSpecialization;
3099 case Decl::UsingDirective: return CXCursor_UsingDirective;
Olivier Goffart81978012016-06-09 16:15:55 +00003100 case Decl::StaticAssert: return CXCursor_StaticAssert;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003101 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003102
3103 case Decl::Using:
3104 case Decl::UnresolvedUsingValue:
3105 case Decl::UnresolvedUsingTypename:
3106 return CXCursor_UsingDeclaration;
3107
Douglas Gregor4cd65962011-06-03 23:08:58 +00003108 case Decl::ObjCPropertyImpl:
3109 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3110 case ObjCPropertyImplDecl::Dynamic:
3111 return CXCursor_ObjCDynamicDecl;
3112
3113 case ObjCPropertyImplDecl::Synthesize:
3114 return CXCursor_ObjCSynthesizeDecl;
3115 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003116
3117 case Decl::Import:
3118 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003119
3120 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3121
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003122 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003123 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003124 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003125 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003126 case TTK_Struct: return CXCursor_StructDecl;
3127 case TTK_Class: return CXCursor_ClassDecl;
3128 case TTK_Union: return CXCursor_UnionDecl;
3129 case TTK_Enum: return CXCursor_EnumDecl;
3130 }
3131 }
3132 }
3133
3134 return CXCursor_UnexposedDecl;
3135}
3136
Douglas Gregor55b037b2010-07-08 20:55:51 +00003137static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003138 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003139 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003140 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003141
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003142 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003143
Douglas Gregor9eb77012009-11-07 00:00:49 +00003144 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3145 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003146 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003147 auto MD = PP.getMacroDefinition(M->first);
3148 if (IncludeUndefined || MD) {
3149 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003150 if (MI->isUsedForHeaderGuard())
3151 continue;
3152
Douglas Gregor8cb17462012-10-09 16:01:50 +00003153 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003154 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003155 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003156 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003157 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003158 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003159
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003160 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003161
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003162}
3163
Douglas Gregorce0e8562010-08-23 21:54:33 +00003164static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3165 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003166 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003167
3168 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003169
Douglas Gregorce0e8562010-08-23 21:54:33 +00003170 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3171 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003172 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003173 Results.AddResult(Result("__func__", CCP_Constant));
3174 Results.ExitScope();
3175}
3176
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003177static void HandleCodeCompleteResults(Sema *S,
3178 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003179 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003180 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003181 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003182 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003183 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003184}
3185
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003186static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3187 Sema::ParserCompletionContext PCC) {
3188 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003189 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003190 return CodeCompletionContext::CCC_TopLevel;
3191
John McCallfaf5fb42010-08-26 23:41:50 +00003192 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003193 return CodeCompletionContext::CCC_ClassStructUnion;
3194
John McCallfaf5fb42010-08-26 23:41:50 +00003195 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003196 return CodeCompletionContext::CCC_ObjCInterface;
3197
John McCallfaf5fb42010-08-26 23:41:50 +00003198 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003199 return CodeCompletionContext::CCC_ObjCImplementation;
3200
John McCallfaf5fb42010-08-26 23:41:50 +00003201 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003202 return CodeCompletionContext::CCC_ObjCIvarList;
3203
John McCallfaf5fb42010-08-26 23:41:50 +00003204 case Sema::PCC_Template:
3205 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003206 if (S.CurContext->isFileContext())
3207 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003208 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003209 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003210 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003211
John McCallfaf5fb42010-08-26 23:41:50 +00003212 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003213 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003214
John McCallfaf5fb42010-08-26 23:41:50 +00003215 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003216 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3217 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003218 return CodeCompletionContext::CCC_ParenthesizedExpression;
3219 else
3220 return CodeCompletionContext::CCC_Expression;
3221
3222 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003223 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003224 return CodeCompletionContext::CCC_Expression;
3225
John McCallfaf5fb42010-08-26 23:41:50 +00003226 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003227 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003228
John McCallfaf5fb42010-08-26 23:41:50 +00003229 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003230 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003231
3232 case Sema::PCC_ParenthesizedExpression:
3233 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003234
3235 case Sema::PCC_LocalDeclarationSpecifiers:
3236 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003237 }
David Blaikie8a40f702012-01-17 06:56:22 +00003238
3239 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003240}
3241
Douglas Gregorac322ec2010-08-27 21:18:54 +00003242/// \brief If we're in a C++ virtual member function, add completion results
3243/// that invoke the functions we override, since it's common to invoke the
3244/// overridden function as well as adding new functionality.
3245///
3246/// \param S The semantic analysis object for which we are generating results.
3247///
3248/// \param InContext This context in which the nested-name-specifier preceding
3249/// the code-completion point
3250static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3251 ResultBuilder &Results) {
3252 // Look through blocks.
3253 DeclContext *CurContext = S.CurContext;
3254 while (isa<BlockDecl>(CurContext))
3255 CurContext = CurContext->getParent();
3256
3257
3258 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3259 if (!Method || !Method->isVirtual())
3260 return;
3261
3262 // We need to have names for all of the parameters, if we're going to
3263 // generate a forwarding call.
David Majnemer59f77922016-06-24 04:05:48 +00003264 for (auto P : Method->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003265 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003266 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003267
Douglas Gregor75acd922011-09-27 23:30:47 +00003268 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003269 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3270 MEnd = Method->end_overridden_methods();
3271 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003272 CodeCompletionBuilder Builder(Results.getAllocator(),
3273 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003274 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003275 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3276 continue;
3277
3278 // If we need a nested-name-specifier, add one now.
3279 if (!InContext) {
3280 NestedNameSpecifier *NNS
3281 = getRequiredQualification(S.Context, CurContext,
3282 Overridden->getDeclContext());
3283 if (NNS) {
3284 std::string Str;
3285 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003286 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003287 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003288 }
3289 } else if (!InContext->Equals(Overridden->getDeclContext()))
3290 continue;
3291
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003292 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003293 Overridden->getNameAsString()));
3294 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003295 bool FirstParam = true;
David Majnemer59f77922016-06-24 04:05:48 +00003296 for (auto P : Method->parameters()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003297 if (FirstParam)
3298 FirstParam = false;
3299 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003300 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003301
Aaron Ballman43b68be2014-03-07 17:50:17 +00003302 Builder.AddPlaceholderChunk(
3303 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003304 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003305 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3306 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003307 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003308 CXCursor_CXXMethod,
3309 CXAvailability_Available,
3310 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003311 Results.Ignore(Overridden);
3312 }
3313}
3314
Douglas Gregor07f43572012-01-29 18:15:03 +00003315void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3316 ModuleIdPath Path) {
3317 typedef CodeCompletionResult Result;
3318 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003319 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003320 CodeCompletionContext::CCC_Other);
3321 Results.EnterNewScope();
3322
3323 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003324 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003325 typedef CodeCompletionResult Result;
3326 if (Path.empty()) {
3327 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003328 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003329 PP.getHeaderSearchInfo().collectAllModules(Modules);
3330 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3331 Builder.AddTypedTextChunk(
3332 Builder.getAllocator().CopyString(Modules[I]->Name));
3333 Results.AddResult(Result(Builder.TakeString(),
3334 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003335 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003336 Modules[I]->isAvailable()
3337 ? CXAvailability_Available
3338 : CXAvailability_NotAvailable));
3339 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003340 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003341 // Load the named module.
3342 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3343 Module::AllVisible,
3344 /*IsInclusionDirective=*/false);
3345 // Enumerate submodules.
3346 if (Mod) {
3347 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3348 SubEnd = Mod->submodule_end();
3349 Sub != SubEnd; ++Sub) {
3350
3351 Builder.AddTypedTextChunk(
3352 Builder.getAllocator().CopyString((*Sub)->Name));
3353 Results.AddResult(Result(Builder.TakeString(),
3354 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003355 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003356 (*Sub)->isAvailable()
3357 ? CXAvailability_Available
3358 : CXAvailability_NotAvailable));
3359 }
3360 }
3361 }
3362 Results.ExitScope();
3363 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3364 Results.data(),Results.size());
3365}
3366
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003367void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003368 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003369 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003370 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003371 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003372 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003373
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003374 // Determine how to filter results, e.g., so that the names of
3375 // values (functions, enumerators, function templates, etc.) are
3376 // only allowed where we can have an expression.
3377 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003378 case PCC_Namespace:
3379 case PCC_Class:
3380 case PCC_ObjCInterface:
3381 case PCC_ObjCImplementation:
3382 case PCC_ObjCInstanceVariableList:
3383 case PCC_Template:
3384 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003385 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003386 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003387 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3388 break;
3389
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003390 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003391 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003392 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003393 case PCC_ForInit:
3394 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003395 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003396 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3397 else
3398 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003399
David Blaikiebbafb8a2012-03-11 07:00:24 +00003400 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003401 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003402 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003403
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003404 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003405 // Unfiltered
3406 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003407 }
3408
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003409 // If we are in a C++ non-static member function, check the qualifiers on
3410 // the member function to filter/prioritize the results list.
3411 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3412 if (CurMethod->isInstance())
3413 Results.setObjectTypeQualifiers(
3414 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3415
Douglas Gregorc580c522010-01-14 01:09:38 +00003416 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003417 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3418 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003419
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003420 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003421 Results.ExitScope();
3422
Douglas Gregorce0e8562010-08-23 21:54:33 +00003423 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003424 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003425 case PCC_Expression:
3426 case PCC_Statement:
3427 case PCC_RecoveryInFunction:
3428 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003429 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003430 break;
3431
3432 case PCC_Namespace:
3433 case PCC_Class:
3434 case PCC_ObjCInterface:
3435 case PCC_ObjCImplementation:
3436 case PCC_ObjCInstanceVariableList:
3437 case PCC_Template:
3438 case PCC_MemberTemplate:
3439 case PCC_ForInit:
3440 case PCC_Condition:
3441 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003442 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003443 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003444 }
3445
Douglas Gregor9eb77012009-11-07 00:00:49 +00003446 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003447 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003448
Douglas Gregor50832e02010-09-20 22:39:41 +00003449 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003450 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003451}
3452
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003453static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3454 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003455 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003456 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003457 bool IsSuper,
3458 ResultBuilder &Results);
3459
3460void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3461 bool AllowNonIdentifiers,
3462 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003463 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003464 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003465 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003466 AllowNestedNameSpecifiers
3467 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3468 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003469 Results.EnterNewScope();
3470
3471 // Type qualifiers can come after names.
3472 Results.AddResult(Result("const"));
3473 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003474 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003475 Results.AddResult(Result("restrict"));
3476
David Blaikiebbafb8a2012-03-11 07:00:24 +00003477 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003478 if (AllowNonIdentifiers) {
3479 Results.AddResult(Result("operator"));
3480 }
3481
3482 // Add nested-name-specifiers.
3483 if (AllowNestedNameSpecifiers) {
3484 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003485 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003486 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3487 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3488 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003489 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003490 }
3491 }
3492 Results.ExitScope();
3493
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003494 // If we're in a context where we might have an expression (rather than a
3495 // declaration), and what we've seen so far is an Objective-C type that could
3496 // be a receiver of a class message, this may be a class message send with
3497 // the initial opening bracket '[' missing. Add appropriate completions.
3498 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003499 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003500 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003501 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3502 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003503 !DS.isTypeAltiVecVector() &&
3504 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003505 (S->getFlags() & Scope::DeclScope) != 0 &&
3506 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3507 Scope::FunctionPrototypeScope |
3508 Scope::AtCatchScope)) == 0) {
3509 ParsedType T = DS.getRepAsType();
3510 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003511 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003512 }
3513
Douglas Gregor56ccce02010-08-24 04:59:56 +00003514 // Note that we intentionally suppress macro results here, since we do not
3515 // encourage using macros to produce the names of entities.
3516
Douglas Gregor0ac41382010-09-23 23:01:17 +00003517 HandleCodeCompleteResults(this, CodeCompleter,
3518 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003519 Results.data(), Results.size());
3520}
3521
Douglas Gregor68762e72010-08-23 21:17:50 +00003522struct Sema::CodeCompleteExpressionData {
3523 CodeCompleteExpressionData(QualType PreferredType = QualType())
3524 : PreferredType(PreferredType), IntegralConstantExpression(false),
3525 ObjCCollection(false) { }
3526
3527 QualType PreferredType;
3528 bool IntegralConstantExpression;
3529 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003530 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003531};
3532
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003533/// \brief Perform code-completion in an expression context when we know what
3534/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003535void Sema::CodeCompleteExpression(Scope *S,
3536 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003537 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003538 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003539 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003540 if (Data.ObjCCollection)
3541 Results.setFilter(&ResultBuilder::IsObjCCollection);
3542 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003543 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003544 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003545 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3546 else
3547 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003548
3549 if (!Data.PreferredType.isNull())
3550 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3551
3552 // Ignore any declarations that we were told that we don't care about.
3553 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3554 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003555
3556 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003557 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3558 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003559
3560 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003561 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003562 Results.ExitScope();
3563
Douglas Gregor55b037b2010-07-08 20:55:51 +00003564 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003565 if (!Data.PreferredType.isNull())
3566 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3567 || Data.PreferredType->isMemberPointerType()
3568 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003569
Douglas Gregorce0e8562010-08-23 21:54:33 +00003570 if (S->getFnParent() &&
3571 !Data.ObjCCollection &&
3572 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003573 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003574
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003575 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003576 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003577 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003578 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3579 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003580 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003581}
3582
Douglas Gregoreda7e542010-09-18 01:28:11 +00003583void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3584 if (E.isInvalid())
3585 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003586 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003587 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003588}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003589
Douglas Gregorb888acf2010-12-09 23:01:55 +00003590/// \brief The set of properties that have already been added, referenced by
3591/// property name.
3592typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3593
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003594/// \brief Retrieve the container definition, if any?
3595static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3596 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3597 if (Interface->hasDefinition())
3598 return Interface->getDefinition();
3599
3600 return Interface;
3601 }
3602
3603 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3604 if (Protocol->hasDefinition())
3605 return Protocol->getDefinition();
3606
3607 return Protocol;
3608 }
3609 return Container;
3610}
3611
Douglas Gregorc3425b12015-07-07 06:20:19 +00003612static void AddObjCProperties(const CodeCompletionContext &CCContext,
3613 ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003614 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003615 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003616 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003617 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003618 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003619 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003620
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003621 // Retrieve the definition.
3622 Container = getContainerDef(Container);
3623
Douglas Gregor9291bad2009-11-18 01:29:26 +00003624 // Add properties in this container.
Manman Rena7a8b1f2016-01-26 18:05:23 +00003625 for (const auto *P : Container->instance_properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003626 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003627 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003628 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003629
Douglas Gregor95147142011-05-05 15:50:42 +00003630 // Add nullary methods
3631 if (AllowNullaryMethods) {
3632 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003633 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003634 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003635 if (M->getSelector().isUnarySelector())
3636 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003637 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003638 CodeCompletionBuilder Builder(Results.getAllocator(),
3639 Results.getCodeCompletionTUInfo());
Douglas Gregorc3425b12015-07-07 06:20:19 +00003640 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3641 Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003642 Builder.AddTypedTextChunk(
3643 Results.getAllocator().CopyString(Name->getName()));
3644
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003645 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003646 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003647 CurContext);
3648 }
3649 }
3650 }
3651
3652
Douglas Gregor9291bad2009-11-18 01:29:26 +00003653 // Add properties in referenced protocols.
3654 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003655 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003656 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3657 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003658 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003659 if (AllowCategories) {
3660 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003661 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003662 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3663 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003664 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003665
Douglas Gregor9291bad2009-11-18 01:29:26 +00003666 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003667 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003668 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3669 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003670
3671 // Look in the superclass.
3672 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003673 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003674 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003675 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003676 } else if (const ObjCCategoryDecl *Category
3677 = dyn_cast<ObjCCategoryDecl>(Container)) {
3678 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003679 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003680 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3681 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003682 }
3683}
3684
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003685void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003686 SourceLocation OpLoc,
3687 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003688 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003689 return;
3690
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003691 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3692 if (ConvertedBase.isInvalid())
3693 return;
3694 Base = ConvertedBase.get();
3695
John McCall276321a2010-08-25 06:19:51 +00003696 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003697
Douglas Gregor2436e712009-09-17 21:32:03 +00003698 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003699
3700 if (IsArrow) {
3701 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3702 BaseType = Ptr->getPointeeType();
3703 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003704 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003705 else
3706 return;
3707 }
3708
Douglas Gregor21325842011-07-07 16:03:39 +00003709 enum CodeCompletionContext::Kind contextKind;
3710
3711 if (IsArrow) {
3712 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3713 }
3714 else {
3715 if (BaseType->isObjCObjectPointerType() ||
3716 BaseType->isObjCObjectOrInterfaceType()) {
3717 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3718 }
3719 else {
3720 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3721 }
3722 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003723
3724 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003725 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003726 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003727 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003728 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003729 Results.EnterNewScope();
3730 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003731 // Indicate that we are performing a member access, and the cv-qualifiers
3732 // for the base object type.
3733 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3734
Douglas Gregor9291bad2009-11-18 01:29:26 +00003735 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003736 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003737 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003738 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3739 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003740
David Blaikiebbafb8a2012-03-11 07:00:24 +00003741 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003742 if (!Results.empty()) {
3743 // The "template" keyword can follow "->" or "." in the grammar.
3744 // However, we only want to suggest the template keyword if something
3745 // is dependent.
3746 bool IsDependent = BaseType->isDependentType();
3747 if (!IsDependent) {
3748 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003749 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003750 IsDependent = Ctx->isDependentContext();
3751 break;
3752 }
3753 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003754
Douglas Gregor9291bad2009-11-18 01:29:26 +00003755 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003756 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003757 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003758 }
Alex Lorenz06cfa992016-10-12 11:40:15 +00003759 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003760 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003761 AddedPropertiesSet AddedProperties;
Alex Lorenz06cfa992016-10-12 11:40:15 +00003762
3763 if (const ObjCObjectPointerType *ObjCPtr =
3764 BaseType->getAsObjCInterfacePointerType()) {
3765 // Add property results based on our interface.
3766 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3767 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
3768 /*AllowNullaryMethods=*/true, CurContext,
3769 AddedProperties, Results);
3770 }
3771
Douglas Gregor9291bad2009-11-18 01:29:26 +00003772 // Add properties from the protocols in a qualified interface.
Alex Lorenz06cfa992016-10-12 11:40:15 +00003773 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003774 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3775 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003776 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003777 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003778 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003779 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003780 if (const ObjCObjectPointerType *ObjCPtr
3781 = BaseType->getAs<ObjCObjectPointerType>())
3782 Class = ObjCPtr->getInterfaceDecl();
3783 else
John McCall8b07ec22010-05-15 11:32:37 +00003784 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003785
3786 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003787 if (Class) {
3788 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3789 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003790 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3791 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003792 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003793 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003794
3795 // FIXME: How do we cope with isa?
3796
3797 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003798
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003799 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003800 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003801 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003802 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003803}
3804
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003805void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3806 if (!CodeCompleter)
3807 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003808
3809 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003810 enum CodeCompletionContext::Kind ContextKind
3811 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003812 switch ((DeclSpec::TST)TagSpec) {
3813 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003814 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003815 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003816 break;
3817
3818 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003819 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003820 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003821 break;
3822
3823 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003824 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003825 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003826 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003827 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003828 break;
3829
3830 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003831 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003832 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003833
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003834 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3835 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003836 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003837
3838 // First pass: look for tags.
3839 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003840 LookupVisibleDecls(S, LookupTagName, Consumer,
3841 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003842
Douglas Gregor39982192010-08-15 06:18:01 +00003843 if (CodeCompleter->includeGlobals()) {
3844 // Second pass: look for nested name specifiers.
3845 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3846 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3847 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003848
Douglas Gregor0ac41382010-09-23 23:01:17 +00003849 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003850 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003851}
3852
Douglas Gregor28c78432010-08-27 17:35:51 +00003853void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003854 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003855 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003856 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003857 Results.EnterNewScope();
3858 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3859 Results.AddResult("const");
3860 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3861 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003862 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003863 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3864 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003865 if (getLangOpts().C11 &&
3866 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3867 Results.AddResult("_Atomic");
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003868 if (getLangOpts().MSVCCompat &&
3869 !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
3870 Results.AddResult("__unaligned");
Douglas Gregor28c78432010-08-27 17:35:51 +00003871 Results.ExitScope();
3872 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003873 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003874 Results.data(), Results.size());
3875}
3876
Benjamin Kramer72dae622016-02-18 15:30:24 +00003877void Sema::CodeCompleteBracketDeclarator(Scope *S) {
3878 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
3879}
3880
Douglas Gregord328d572009-09-21 18:10:23 +00003881void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003882 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003883 return;
John McCall5939b162011-08-06 07:30:58 +00003884
John McCallaab3e412010-08-25 08:40:02 +00003885 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003886 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3887 if (!type->isEnumeralType()) {
3888 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003889 Data.IntegralConstantExpression = true;
3890 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003891 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003892 }
Douglas Gregord328d572009-09-21 18:10:23 +00003893
3894 // Code-complete the cases of a switch statement over an enumeration type
3895 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003896 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003897 if (EnumDecl *Def = Enum->getDefinition())
3898 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003899
3900 // Determine which enumerators we have already seen in the switch statement.
3901 // FIXME: Ideally, we would also be able to look *past* the code-completion
3902 // token, in case we are code-completing in the middle of the switch and not
3903 // at the end. However, we aren't able to do so at the moment.
3904 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003905 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003906 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3907 SC = SC->getNextSwitchCase()) {
3908 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3909 if (!Case)
3910 continue;
3911
3912 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3913 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3914 if (EnumConstantDecl *Enumerator
3915 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3916 // We look into the AST of the case statement to determine which
3917 // enumerator was named. Alternatively, we could compute the value of
3918 // the integral constant expression, then compare it against the
3919 // values of each enumerator. However, value-based approach would not
3920 // work as well with C++ templates where enumerators declared within a
3921 // template are type- and value-dependent.
3922 EnumeratorsSeen.insert(Enumerator);
3923
Douglas Gregorf2510672009-09-21 19:57:38 +00003924 // If this is a qualified-id, keep track of the nested-name-specifier
3925 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003926 //
3927 // switch (TagD.getKind()) {
3928 // case TagDecl::TK_enum:
3929 // break;
3930 // case XXX
3931 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003932 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003933 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3934 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003935 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003936 }
3937 }
3938
David Blaikiebbafb8a2012-03-11 07:00:24 +00003939 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003940 // If there are no prior enumerators in C++, check whether we have to
3941 // qualify the names of the enumerators that we suggest, because they
3942 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003943 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003944 }
3945
Douglas Gregord328d572009-09-21 18:10:23 +00003946 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003947 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003948 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003949 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003950 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003951 for (auto *E : Enum->enumerators()) {
3952 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003953 continue;
3954
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003955 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003956 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003957 }
3958 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003959
Douglas Gregor21325842011-07-07 16:03:39 +00003960 //We need to make sure we're setting the right context,
3961 //so only say we include macros if the code completer says we do
3962 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3963 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003964 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003965 kind = CodeCompletionContext::CCC_OtherWithMacros;
3966 }
3967
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003968 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003969 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003970 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003971}
3972
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003973static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003974 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003975 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003976
3977 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003978 if (!Args[I])
3979 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003980
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003981 return false;
3982}
3983
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003984typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3985
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003986static void mergeCandidatesWithResults(Sema &SemaRef,
3987 SmallVectorImpl<ResultCandidate> &Results,
3988 OverloadCandidateSet &CandidateSet,
3989 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003990 if (!CandidateSet.empty()) {
3991 // Sort the overload candidate set by placing the best overloads first.
3992 std::stable_sort(
3993 CandidateSet.begin(), CandidateSet.end(),
3994 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3995 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3996 });
3997
3998 // Add the remaining viable overload candidates as code-completion results.
3999 for (auto &Candidate : CandidateSet)
4000 if (Candidate.Viable)
4001 Results.push_back(ResultCandidate(Candidate.Function));
4002 }
4003}
4004
4005/// \brief Get the type of the Nth parameter from a given set of overload
4006/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004007static QualType getParamType(Sema &SemaRef,
4008 ArrayRef<ResultCandidate> Candidates,
4009 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004010
4011 // Given the overloads 'Candidates' for a function call matching all arguments
4012 // up to N, return the type of the Nth parameter if it is the same for all
4013 // overload candidates.
4014 QualType ParamType;
4015 for (auto &Candidate : Candidates) {
4016 if (auto FType = Candidate.getFunctionType())
4017 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4018 if (N < Proto->getNumParams()) {
4019 if (ParamType.isNull())
4020 ParamType = Proto->getParamType(N);
4021 else if (!SemaRef.Context.hasSameUnqualifiedType(
4022 ParamType.getNonReferenceType(),
4023 Proto->getParamType(N).getNonReferenceType()))
4024 // Otherwise return a default-constructed QualType.
4025 return QualType();
4026 }
4027 }
4028
4029 return ParamType;
4030}
4031
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004032static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4033 MutableArrayRef<ResultCandidate> Candidates,
4034 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004035 bool CompleteExpressionWithCurrentArg = true) {
4036 QualType ParamType;
4037 if (CompleteExpressionWithCurrentArg)
4038 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4039
4040 if (ParamType.isNull())
4041 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4042 else
4043 SemaRef.CodeCompleteExpression(S, ParamType);
4044
4045 if (!Candidates.empty())
4046 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4047 Candidates.data(),
4048 Candidates.size());
4049}
4050
4051void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004052 if (!CodeCompleter)
4053 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004054
4055 // When we're code-completing for a call, we fall back to ordinary
4056 // name code-completion whenever we can't produce specific
4057 // results. We may want to revisit this strategy in the future,
4058 // e.g., by merging the two kinds of results.
4059
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004060 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004061
Douglas Gregorcabea402009-09-22 15:41:20 +00004062 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004063 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4064 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004065 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004066 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004067 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004068
John McCall57500772009-12-16 12:17:52 +00004069 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004070 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004071 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004072
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004073 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004074
John McCall57500772009-12-16 12:17:52 +00004075 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004076 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004077 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004078 /*PartialOverloading=*/true);
4079 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4080 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4081 if (UME->hasExplicitTemplateArgs()) {
4082 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4083 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004084 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004085 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4086 ArgExprs.append(Args.begin(), Args.end());
4087 UnresolvedSet<8> Decls;
4088 Decls.append(UME->decls_begin(), UME->decls_end());
4089 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4090 /*SuppressUsedConversions=*/false,
4091 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004092 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004093 FunctionDecl *FD = nullptr;
4094 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4095 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4096 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4097 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004098 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004099 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004100 !FD->getType()->getAs<FunctionProtoType>())
4101 Results.push_back(ResultCandidate(FD));
4102 else
4103 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4104 Args, CandidateSet,
4105 /*SuppressUsedConversions=*/false,
4106 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004107
4108 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4109 // If expression's type is CXXRecordDecl, it may overload the function
4110 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004111 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004112 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004113 DeclarationName OpName = Context.DeclarationNames
4114 .getCXXOperatorName(OO_Call);
4115 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4116 LookupQualifiedName(R, DC);
4117 R.suppressDiagnostics();
4118 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4119 ArgExprs.append(Args.begin(), Args.end());
4120 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4121 /*ExplicitArgs=*/nullptr,
4122 /*SuppressUsedConversions=*/false,
4123 /*PartialOverloading=*/true);
4124 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004125 } else {
4126 // Lastly we check whether expression's type is function pointer or
4127 // function.
4128 QualType T = NakedFn->getType();
4129 if (!T->getPointeeType().isNull())
4130 T = T->getPointeeType();
4131
4132 if (auto FP = T->getAs<FunctionProtoType>()) {
4133 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004134 /*PartialOverloading=*/true) ||
4135 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004136 Results.push_back(ResultCandidate(FP));
4137 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004138 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004139 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004140 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004141 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004142
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004143 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4144 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4145 !CandidateSet.empty());
4146}
4147
4148void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4149 ArrayRef<Expr *> Args) {
4150 if (!CodeCompleter)
4151 return;
4152
4153 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004154 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004155 return;
4156
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004157 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4158 if (!RD) {
4159 CodeCompleteExpression(S, Type);
4160 return;
4161 }
4162
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004163 // FIXME: Provide support for member initializers.
4164 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004165
4166 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4167
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004168 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004169 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4170 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4171 Args, CandidateSet,
4172 /*SuppressUsedConversions=*/false,
4173 /*PartialOverloading=*/true);
4174 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4175 AddTemplateOverloadCandidate(FTD,
4176 DeclAccessPair::make(FTD, C->getAccess()),
4177 /*ExplicitTemplateArgs=*/nullptr,
4178 Args, CandidateSet,
4179 /*SuppressUsedConversions=*/false,
4180 /*PartialOverloading=*/true);
4181 }
4182 }
4183
4184 SmallVector<ResultCandidate, 8> Results;
4185 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4186 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004187}
4188
John McCall48871652010-08-21 09:40:31 +00004189void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4190 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004191 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004192 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004193 return;
4194 }
4195
4196 CodeCompleteExpression(S, VD->getType());
4197}
4198
4199void Sema::CodeCompleteReturn(Scope *S) {
4200 QualType ResultType;
4201 if (isa<BlockDecl>(CurContext)) {
4202 if (BlockScopeInfo *BSI = getCurBlock())
4203 ResultType = BSI->ReturnType;
4204 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004205 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004206 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004207 ResultType = Method->getReturnType();
4208
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004209 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004210 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004211 else
4212 CodeCompleteExpression(S, ResultType);
4213}
4214
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004215void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004216 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004217 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004218 mapCodeCompletionContext(*this, PCC_Statement));
4219 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4220 Results.EnterNewScope();
4221
4222 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4223 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4224 CodeCompleter->includeGlobals());
4225
4226 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4227
4228 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004229 CodeCompletionBuilder Builder(Results.getAllocator(),
4230 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004231 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004232 if (Results.includeCodePatterns()) {
4233 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4234 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4235 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4236 Builder.AddPlaceholderChunk("statements");
4237 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4238 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4239 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004240 Results.AddResult(Builder.TakeString());
4241
4242 // "else if" block
4243 Builder.AddTypedTextChunk("else");
4244 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4245 Builder.AddTextChunk("if");
4246 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4247 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004248 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004249 Builder.AddPlaceholderChunk("condition");
4250 else
4251 Builder.AddPlaceholderChunk("expression");
4252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004253 if (Results.includeCodePatterns()) {
4254 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4255 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4256 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4257 Builder.AddPlaceholderChunk("statements");
4258 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4259 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4260 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004261 Results.AddResult(Builder.TakeString());
4262
4263 Results.ExitScope();
4264
4265 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004266 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004267
4268 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004269 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004270
4271 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4272 Results.data(),Results.size());
4273}
4274
Richard Trieu2bd04012011-09-09 02:00:50 +00004275void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004276 if (LHS)
4277 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4278 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004279 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004280}
4281
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004282void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004283 bool EnteringContext) {
4284 if (!SS.getScopeRep() || !CodeCompleter)
4285 return;
4286
Douglas Gregor3545ff42009-09-21 16:56:56 +00004287 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4288 if (!Ctx)
4289 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004290
4291 // Try to instantiate any non-dependent declaration contexts before
4292 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004293 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004294 return;
4295
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004296 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004297 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004298 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004299 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004300
Douglas Gregor3545ff42009-09-21 16:56:56 +00004301 // The "template" keyword can follow "::" in the grammar, but only
4302 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004303 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004304 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004305 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004306
4307 // Add calls to overridden virtual functions, if there are any.
4308 //
4309 // FIXME: This isn't wonderful, because we don't know whether we're actually
4310 // in a context that permits expressions. This is a general issue with
4311 // qualified-id completions.
4312 if (!EnteringContext)
4313 MaybeAddOverrideCalls(*this, Ctx, Results);
4314 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004315
Douglas Gregorac322ec2010-08-27 21:18:54 +00004316 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4317 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4318
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004319 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004320 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004321 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004322}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004323
4324void Sema::CodeCompleteUsing(Scope *S) {
4325 if (!CodeCompleter)
4326 return;
4327
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004328 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004329 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004330 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4331 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004332 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004333
4334 // If we aren't in class scope, we could see the "namespace" keyword.
4335 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004336 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004337
4338 // After "using", we can see anything that would start a
4339 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004340 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004341 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4342 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004343 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004344
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004345 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004346 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004347 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004348}
4349
4350void Sema::CodeCompleteUsingDirective(Scope *S) {
4351 if (!CodeCompleter)
4352 return;
4353
Douglas Gregor3545ff42009-09-21 16:56:56 +00004354 // After "using namespace", we expect to see a namespace name or namespace
4355 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004356 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004357 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004358 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004359 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004360 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004361 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004362 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4363 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004364 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004365 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004366 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004367 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004368}
4369
4370void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4371 if (!CodeCompleter)
4372 return;
4373
Ted Kremenekc37877d2013-10-08 17:08:03 +00004374 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004375 if (!S->getParent())
4376 Ctx = Context.getTranslationUnitDecl();
4377
Douglas Gregor0ac41382010-09-23 23:01:17 +00004378 bool SuppressedGlobalResults
4379 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4380
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004381 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004382 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004383 SuppressedGlobalResults
4384 ? CodeCompletionContext::CCC_Namespace
4385 : CodeCompletionContext::CCC_Other,
4386 &ResultBuilder::IsNamespace);
4387
4388 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004389 // We only want to see those namespaces that have already been defined
4390 // within this scope, because its likely that the user is creating an
4391 // extended namespace declaration. Keep track of the most recent
4392 // definition of each namespace.
4393 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4394 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4395 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4396 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004397 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004398
4399 // Add the most recent definition (or extended definition) of each
4400 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004401 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004402 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004403 NS = OrigToLatest.begin(),
4404 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004405 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004406 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 NS->second, Results.getBasePriority(NS->second),
4408 nullptr),
4409 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004410 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004411 }
4412
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004413 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004414 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004415 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004416}
4417
4418void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4419 if (!CodeCompleter)
4420 return;
4421
Douglas Gregor3545ff42009-09-21 16:56:56 +00004422 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004423 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004424 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004425 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004426 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004427 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004428 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4429 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004430 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004431 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004432 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004433}
4434
Douglas Gregorc811ede2009-09-18 20:05:18 +00004435void Sema::CodeCompleteOperatorName(Scope *S) {
4436 if (!CodeCompleter)
4437 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004438
John McCall276321a2010-08-25 06:19:51 +00004439 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004440 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004441 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004442 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004443 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004444 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004445
Douglas Gregor3545ff42009-09-21 16:56:56 +00004446 // Add the names of overloadable operators.
4447#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4448 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004449 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004450#include "clang/Basic/OperatorKinds.def"
4451
4452 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004453 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004454 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004455 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4456 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004457
4458 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004459 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004460 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004461
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004462 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004463 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004464 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004465}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004466
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004467void Sema::CodeCompleteConstructorInitializer(
4468 Decl *ConstructorD,
4469 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004470 if (!ConstructorD)
4471 return;
4472
4473 AdjustDeclIfTemplate(ConstructorD);
4474
4475 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004476 if (!Constructor)
4477 return;
4478
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004479 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004480 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004481 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004482 Results.EnterNewScope();
4483
4484 // Fill in any already-initialized fields or base classes.
4485 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4486 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004487 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004488 if (Initializers[I]->isBaseInitializer())
4489 InitializedBases.insert(
4490 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4491 else
Francois Pichetd583da02010-12-04 09:14:42 +00004492 InitializedFields.insert(cast<FieldDecl>(
4493 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004494 }
4495
4496 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004497 CodeCompletionBuilder Builder(Results.getAllocator(),
4498 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004499 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004500 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004501 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004502 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004503 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4504 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004505 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004506 = !Initializers.empty() &&
4507 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004508 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004509 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004510 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004511 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004512
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004513 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004514 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004515 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004516 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4517 Builder.AddPlaceholderChunk("args");
4518 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4519 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004520 SawLastInitializer? CCP_NextInitializer
4521 : CCP_MemberDeclaration));
4522 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004523 }
4524
4525 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004526 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004527 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4528 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004529 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004530 = !Initializers.empty() &&
4531 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004532 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004533 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004534 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004535 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004536
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004537 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004538 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004539 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004540 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4541 Builder.AddPlaceholderChunk("args");
4542 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4543 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004544 SawLastInitializer? CCP_NextInitializer
4545 : CCP_MemberDeclaration));
4546 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004547 }
4548
4549 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004550 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004551 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4552 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004553 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004554 = !Initializers.empty() &&
4555 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004556 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004557 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004558 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004559
4560 if (!Field->getDeclName())
4561 continue;
4562
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004563 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004564 Field->getIdentifier()->getName()));
4565 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4566 Builder.AddPlaceholderChunk("args");
4567 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4568 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004569 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004570 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004571 CXCursor_MemberRef,
4572 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004573 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004574 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004575 }
4576 Results.ExitScope();
4577
Douglas Gregor0ac41382010-09-23 23:01:17 +00004578 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004579 Results.data(), Results.size());
4580}
4581
Douglas Gregord8c61782012-02-15 15:34:24 +00004582/// \brief Determine whether this scope denotes a namespace.
4583static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004584 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004585 if (!DC)
4586 return false;
4587
4588 return DC->isFileContext();
4589}
4590
4591void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4592 bool AfterAmpersand) {
4593 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004594 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004595 CodeCompletionContext::CCC_Other);
4596 Results.EnterNewScope();
4597
4598 // Note what has already been captured.
4599 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4600 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004601 for (const auto &C : Intro.Captures) {
4602 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004603 IncludedThis = true;
4604 continue;
4605 }
4606
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004607 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004608 }
4609
4610 // Look for other capturable variables.
4611 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004612 for (const auto *D : S->decls()) {
4613 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004614 if (!Var ||
4615 !Var->hasLocalStorage() ||
4616 Var->hasAttr<BlocksAttr>())
4617 continue;
4618
David Blaikie82e95a32014-11-19 07:49:47 +00004619 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004620 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004621 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004622 }
4623 }
4624
4625 // Add 'this', if it would be valid.
4626 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4627 addThisCompletion(*this, Results);
4628
4629 Results.ExitScope();
4630
4631 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4632 Results.data(), Results.size());
4633}
4634
James Dennett596e4752012-06-14 03:11:41 +00004635/// Macro that optionally prepends an "@" to the string literal passed in via
4636/// Keyword, depending on whether NeedAt is true or false.
4637#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4638
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004639static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004640 ResultBuilder &Results,
4641 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004642 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004643 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004644 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004645
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004646 CodeCompletionBuilder Builder(Results.getAllocator(),
4647 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004648 if (LangOpts.ObjC2) {
4649 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004650 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004651 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4652 Builder.AddPlaceholderChunk("property");
4653 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004654
4655 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004656 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004657 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4658 Builder.AddPlaceholderChunk("property");
4659 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004660 }
4661}
4662
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004663static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004664 ResultBuilder &Results,
4665 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004666 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004667
4668 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004669 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004670
4671 if (LangOpts.ObjC2) {
4672 // @property
James Dennett596e4752012-06-14 03:11:41 +00004673 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004674
4675 // @required
James Dennett596e4752012-06-14 03:11:41 +00004676 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004677
4678 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004679 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004680 }
4681}
4682
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004683static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004684 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004685 CodeCompletionBuilder Builder(Results.getAllocator(),
4686 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004687
4688 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004689 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004690 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4691 Builder.AddPlaceholderChunk("name");
4692 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004693
Douglas Gregorf4c33342010-05-28 00:22:41 +00004694 if (Results.includeCodePatterns()) {
4695 // @interface name
4696 // FIXME: Could introduce the whole pattern, including superclasses and
4697 // such.
James Dennett596e4752012-06-14 03:11:41 +00004698 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4700 Builder.AddPlaceholderChunk("class");
4701 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004702
Douglas Gregorf4c33342010-05-28 00:22:41 +00004703 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004704 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004705 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4706 Builder.AddPlaceholderChunk("protocol");
4707 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004708
4709 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004710 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4712 Builder.AddPlaceholderChunk("class");
4713 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004714 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004715
4716 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004717 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4719 Builder.AddPlaceholderChunk("alias");
4720 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4721 Builder.AddPlaceholderChunk("class");
4722 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004723
4724 if (Results.getSema().getLangOpts().Modules) {
4725 // @import name
4726 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4728 Builder.AddPlaceholderChunk("module");
4729 Results.AddResult(Result(Builder.TakeString()));
4730 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004731}
4732
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004733void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004734 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004735 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004736 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004737 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004738 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004739 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004740 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004741 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004742 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004743 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004744 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004745 HandleCodeCompleteResults(this, CodeCompleter,
4746 CodeCompletionContext::CCC_Other,
4747 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004748}
4749
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004750static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004751 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004752 CodeCompletionBuilder Builder(Results.getAllocator(),
4753 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004754
4755 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004756 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004757 if (Results.getSema().getLangOpts().CPlusPlus ||
4758 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004759 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004760 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004761 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004762 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4763 Builder.AddPlaceholderChunk("type-name");
4764 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4765 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004766
4767 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004768 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004769 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004770 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4771 Builder.AddPlaceholderChunk("protocol-name");
4772 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4773 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004774
4775 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004776 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004777 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004778 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4779 Builder.AddPlaceholderChunk("selector");
4780 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4781 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004782
4783 // @"string"
4784 Builder.AddResultTypeChunk("NSString *");
4785 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4786 Builder.AddPlaceholderChunk("string");
4787 Builder.AddTextChunk("\"");
4788 Results.AddResult(Result(Builder.TakeString()));
4789
Douglas Gregor951de302012-07-17 23:24:47 +00004790 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004791 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004792 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004793 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004794 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4795 Results.AddResult(Result(Builder.TakeString()));
4796
Douglas Gregor951de302012-07-17 23:24:47 +00004797 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004798 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004799 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004800 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004801 Builder.AddChunk(CodeCompletionString::CK_Colon);
4802 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4803 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004804 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4805 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004806
Douglas Gregor951de302012-07-17 23:24:47 +00004807 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004808 Builder.AddResultTypeChunk("id");
4809 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004810 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004811 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4812 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004813}
4814
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004815static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004816 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004817 CodeCompletionBuilder Builder(Results.getAllocator(),
4818 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004819
Douglas Gregorf4c33342010-05-28 00:22:41 +00004820 if (Results.includeCodePatterns()) {
4821 // @try { statements } @catch ( declaration ) { statements } @finally
4822 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004823 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004824 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4825 Builder.AddPlaceholderChunk("statements");
4826 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4827 Builder.AddTextChunk("@catch");
4828 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4829 Builder.AddPlaceholderChunk("parameter");
4830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4831 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4832 Builder.AddPlaceholderChunk("statements");
4833 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4834 Builder.AddTextChunk("@finally");
4835 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4836 Builder.AddPlaceholderChunk("statements");
4837 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4838 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004839 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004840
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004841 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004842 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004843 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4844 Builder.AddPlaceholderChunk("expression");
4845 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004846
Douglas Gregorf4c33342010-05-28 00:22:41 +00004847 if (Results.includeCodePatterns()) {
4848 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004849 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4851 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4852 Builder.AddPlaceholderChunk("expression");
4853 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4854 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4855 Builder.AddPlaceholderChunk("statements");
4856 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4857 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004858 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004859}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004860
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004861static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004862 ResultBuilder &Results,
4863 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004864 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004865 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4866 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4867 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004868 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004869 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004870}
4871
4872void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004873 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004874 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004875 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004876 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004877 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004878 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004879 HandleCodeCompleteResults(this, CodeCompleter,
4880 CodeCompletionContext::CCC_Other,
4881 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004882}
4883
4884void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004885 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004886 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004887 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004888 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004889 AddObjCStatementResults(Results, false);
4890 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004891 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004892 HandleCodeCompleteResults(this, CodeCompleter,
4893 CodeCompletionContext::CCC_Other,
4894 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004895}
4896
4897void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004898 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004899 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004900 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004901 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004902 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004903 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004904 HandleCodeCompleteResults(this, CodeCompleter,
4905 CodeCompletionContext::CCC_Other,
4906 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004907}
4908
Douglas Gregore6078da2009-11-19 00:14:45 +00004909/// \brief Determine whether the addition of the given flag to an Objective-C
4910/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004911static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004912 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004913 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004914 return true;
4915
Bill Wendling44426052012-12-20 19:22:21 +00004916 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004917
4918 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004919 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4920 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004921 return true;
4922
Jordan Rose53cb2f32012-08-20 20:01:13 +00004923 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004924 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004925 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004926 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004927 ObjCDeclSpec::DQ_PR_retain |
4928 ObjCDeclSpec::DQ_PR_strong |
4929 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004930 if (AssignCopyRetMask &&
4931 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004932 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004933 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004934 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004935 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4936 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004937 return true;
4938
4939 return false;
4940}
4941
Douglas Gregor36029f42009-11-18 23:08:07 +00004942void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004943 if (!CodeCompleter)
4944 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004945
Bill Wendling44426052012-12-20 19:22:21 +00004946 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004947
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004948 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004949 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004950 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004951 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004952 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004953 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004954 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004955 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004956 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004957 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4958 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004959 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004960 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004961 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004962 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004963 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004964 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004965 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004966 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004967 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004968 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004969 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004970 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004971
4972 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00004973 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004974 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004975 Results.AddResult(CodeCompletionResult("weak"));
4976
Bill Wendling44426052012-12-20 19:22:21 +00004977 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004978 CodeCompletionBuilder Setter(Results.getAllocator(),
4979 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004980 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004981 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004982 Setter.AddPlaceholderChunk("method");
4983 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004984 }
Bill Wendling44426052012-12-20 19:22:21 +00004985 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004986 CodeCompletionBuilder Getter(Results.getAllocator(),
4987 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004988 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004989 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004990 Getter.AddPlaceholderChunk("method");
4991 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004992 }
Douglas Gregor86b42682015-06-19 18:27:52 +00004993 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4994 Results.AddResult(CodeCompletionResult("nonnull"));
4995 Results.AddResult(CodeCompletionResult("nullable"));
4996 Results.AddResult(CodeCompletionResult("null_unspecified"));
4997 Results.AddResult(CodeCompletionResult("null_resettable"));
4998 }
Steve Naroff936354c2009-10-08 21:55:05 +00004999 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005000 HandleCodeCompleteResults(this, CodeCompleter,
5001 CodeCompletionContext::CCC_Other,
5002 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00005003}
Steve Naroffeae65032009-11-07 02:08:14 +00005004
James Dennettf1243872012-06-17 05:33:25 +00005005/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00005006/// via code completion.
5007enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00005008 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5009 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5010 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005011};
5012
Douglas Gregor67c692c2010-08-26 15:07:07 +00005013static bool isAcceptableObjCSelector(Selector Sel,
5014 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005015 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005016 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005017 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00005018 if (NumSelIdents > Sel.getNumArgs())
5019 return false;
5020
5021 switch (WantKind) {
5022 case MK_Any: break;
5023 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5024 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5025 }
5026
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005027 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5028 return false;
5029
Douglas Gregor67c692c2010-08-26 15:07:07 +00005030 for (unsigned I = 0; I != NumSelIdents; ++I)
5031 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5032 return false;
5033
5034 return true;
5035}
5036
Douglas Gregorc8537c52009-11-19 07:41:15 +00005037static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5038 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005039 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005040 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005041 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005042 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005043}
Douglas Gregor1154e272010-09-16 16:06:31 +00005044
5045namespace {
5046 /// \brief A set of selectors, which is used to avoid introducing multiple
5047 /// completions with the same selector into the result set.
5048 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5049}
5050
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005051/// \brief Add all of the Objective-C methods in the given Objective-C
5052/// container to the set of results.
5053///
5054/// The container will be a class, protocol, category, or implementation of
5055/// any of the above. This mether will recurse to include methods from
5056/// the superclasses of classes along with their categories, protocols, and
5057/// implementations.
5058///
5059/// \param Container the container in which we'll look to find methods.
5060///
James Dennett596e4752012-06-14 03:11:41 +00005061/// \param WantInstanceMethods Whether to add instance methods (only); if
5062/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005063///
5064/// \param CurContext the context in which we're performing the lookup that
5065/// finds methods.
5066///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005067/// \param AllowSameLength Whether we allow a method to be added to the list
5068/// when it has the same number of parameters as we have selector identifiers.
5069///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005070/// \param Results the structure into which we'll add results.
5071static void AddObjCMethods(ObjCContainerDecl *Container,
5072 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00005073 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005074 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005075 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00005076 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005077 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00005078 ResultBuilder &Results,
5079 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00005080 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005081 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005082 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5083 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005084 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005085 // The instance methods on the root class can be messaged via the
5086 // metaclass.
5087 if (M->isInstanceMethod() == WantInstanceMethods ||
5088 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005089 // Check whether the selector identifiers we've been given are a
5090 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005091 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005092 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005093
David Blaikie82e95a32014-11-19 07:49:47 +00005094 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005095 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005096
5097 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005098 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005099 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005100 if (!InOriginalClass)
5101 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005102 Results.MaybeAddResult(R, CurContext);
5103 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005104 }
5105
Douglas Gregorf37c9492010-09-16 15:34:59 +00005106 // Visit the protocols of protocols.
5107 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005108 if (Protocol->hasDefinition()) {
5109 const ObjCList<ObjCProtocolDecl> &Protocols
5110 = Protocol->getReferencedProtocols();
5111 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5112 E = Protocols.end();
5113 I != E; ++I)
5114 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005115 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005116 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005117 }
5118
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005119 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005120 return;
5121
5122 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005123 for (auto *I : IFace->protocols())
5124 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005125 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005126
5127 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005128 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005129 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005130 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005131 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005132
5133 // Add a categories protocol methods.
5134 const ObjCList<ObjCProtocolDecl> &Protocols
5135 = CatDecl->getReferencedProtocols();
5136 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5137 E = Protocols.end();
5138 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005139 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005140 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005141 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005142
5143 // Add methods in category implementations.
5144 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005145 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005146 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005147 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005148 }
5149
5150 // Add methods in superclass.
5151 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005152 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005153 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005154 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005155
5156 // Add methods in our implementation, if any.
5157 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005158 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005159 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005160 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005161}
5162
5163
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005164void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005165 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005166 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005167 if (!Class) {
5168 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005169 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005170 Class = Category->getClassInterface();
5171
5172 if (!Class)
5173 return;
5174 }
5175
5176 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005177 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005178 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005179 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005180 Results.EnterNewScope();
5181
Douglas Gregor1154e272010-09-16 16:06:31 +00005182 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005183 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005184 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005185 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005186 HandleCodeCompleteResults(this, CodeCompleter,
5187 CodeCompletionContext::CCC_Other,
5188 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005189}
5190
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005191void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005192 // Try to find the interface where setters might live.
5193 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005194 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005195 if (!Class) {
5196 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005197 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005198 Class = Category->getClassInterface();
5199
5200 if (!Class)
5201 return;
5202 }
5203
5204 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005205 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005206 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005207 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005208 Results.EnterNewScope();
5209
Douglas Gregor1154e272010-09-16 16:06:31 +00005210 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005211 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005212 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005213
5214 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005215 HandleCodeCompleteResults(this, CodeCompleter,
5216 CodeCompletionContext::CCC_Other,
5217 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005218}
5219
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005220void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5221 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005222 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005223 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005224 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005225 Results.EnterNewScope();
5226
5227 // Add context-sensitive, Objective-C parameter-passing keywords.
5228 bool AddedInOut = false;
5229 if ((DS.getObjCDeclQualifier() &
5230 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5231 Results.AddResult("in");
5232 Results.AddResult("inout");
5233 AddedInOut = true;
5234 }
5235 if ((DS.getObjCDeclQualifier() &
5236 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5237 Results.AddResult("out");
5238 if (!AddedInOut)
5239 Results.AddResult("inout");
5240 }
5241 if ((DS.getObjCDeclQualifier() &
5242 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5243 ObjCDeclSpec::DQ_Oneway)) == 0) {
5244 Results.AddResult("bycopy");
5245 Results.AddResult("byref");
5246 Results.AddResult("oneway");
5247 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005248 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5249 Results.AddResult("nonnull");
5250 Results.AddResult("nullable");
5251 Results.AddResult("null_unspecified");
5252 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005253
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005254 // If we're completing the return type of an Objective-C method and the
5255 // identifier IBAction refers to a macro, provide a completion item for
5256 // an action, e.g.,
5257 // IBAction)<#selector#>:(id)sender
5258 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005259 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005260 CodeCompletionBuilder Builder(Results.getAllocator(),
5261 Results.getCodeCompletionTUInfo(),
5262 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005263 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005264 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005265 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005266 Builder.AddChunk(CodeCompletionString::CK_Colon);
5267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005268 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005270 Builder.AddTextChunk("sender");
5271 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5272 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005273
5274 // If we're completing the return type, provide 'instancetype'.
5275 if (!IsParameter) {
5276 Results.AddResult(CodeCompletionResult("instancetype"));
5277 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005278
Douglas Gregor99fa2642010-08-24 01:06:58 +00005279 // Add various builtin type names and specifiers.
5280 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5281 Results.ExitScope();
5282
5283 // Add the various type names
5284 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5285 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5286 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5287 CodeCompleter->includeGlobals());
5288
5289 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005290 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005291
5292 HandleCodeCompleteResults(this, CodeCompleter,
5293 CodeCompletionContext::CCC_Type,
5294 Results.data(), Results.size());
5295}
5296
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005297/// \brief When we have an expression with type "id", we may assume
5298/// that it has some more-specific class type based on knowledge of
5299/// common uses of Objective-C. This routine returns that class type,
5300/// or NULL if no better result could be determined.
5301static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005302 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005303 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005304 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005305
5306 Selector Sel = Msg->getSelector();
5307 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005308 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005309
5310 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5311 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005312 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005313
5314 ObjCMethodDecl *Method = Msg->getMethodDecl();
5315 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005316 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005317
5318 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005319 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005320 switch (Msg->getReceiverKind()) {
5321 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005322 if (const ObjCObjectType *ObjType
5323 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5324 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005325 break;
5326
5327 case ObjCMessageExpr::Instance: {
5328 QualType T = Msg->getInstanceReceiver()->getType();
5329 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5330 IFace = Ptr->getInterfaceDecl();
5331 break;
5332 }
5333
5334 case ObjCMessageExpr::SuperInstance:
5335 case ObjCMessageExpr::SuperClass:
5336 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005337 }
5338
5339 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005340 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005341
5342 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5343 if (Method->isInstanceMethod())
5344 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5345 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005346 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005347 .Case("autorelease", IFace)
5348 .Case("copy", IFace)
5349 .Case("copyWithZone", IFace)
5350 .Case("mutableCopy", IFace)
5351 .Case("mutableCopyWithZone", IFace)
5352 .Case("awakeFromCoder", IFace)
5353 .Case("replacementObjectFromCoder", IFace)
5354 .Case("class", IFace)
5355 .Case("classForCoder", IFace)
5356 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005357 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005358
5359 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5360 .Case("new", IFace)
5361 .Case("alloc", IFace)
5362 .Case("allocWithZone", IFace)
5363 .Case("class", IFace)
5364 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005365 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005366}
5367
Douglas Gregor6fc04132010-08-27 15:10:57 +00005368// Add a special completion for a message send to "super", which fills in the
5369// most likely case of forwarding all of our arguments to the superclass
5370// function.
5371///
5372/// \param S The semantic analysis object.
5373///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005374/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005375/// the "super" keyword. Otherwise, we just need to provide the arguments.
5376///
5377/// \param SelIdents The identifiers in the selector that have already been
5378/// provided as arguments for a send to "super".
5379///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005380/// \param Results The set of results to augment.
5381///
5382/// \returns the Objective-C method declaration that would be invoked by
5383/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005384static ObjCMethodDecl *AddSuperSendCompletion(
5385 Sema &S, bool NeedSuperKeyword,
5386 ArrayRef<IdentifierInfo *> SelIdents,
5387 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005388 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5389 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005390 return nullptr;
5391
Douglas Gregor6fc04132010-08-27 15:10:57 +00005392 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5393 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005394 return nullptr;
5395
Douglas Gregor6fc04132010-08-27 15:10:57 +00005396 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005397 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005398 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5399 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005400 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5401 CurMethod->isInstanceMethod());
5402
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005403 // Check in categories or class extensions.
5404 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005405 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005406 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005407 CurMethod->isInstanceMethod())))
5408 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005409 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005410 }
5411 }
5412
Douglas Gregor6fc04132010-08-27 15:10:57 +00005413 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005414 return nullptr;
5415
Douglas Gregor6fc04132010-08-27 15:10:57 +00005416 // Check whether the superclass method has the same signature.
5417 if (CurMethod->param_size() != SuperMethod->param_size() ||
5418 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005419 return nullptr;
5420
Douglas Gregor6fc04132010-08-27 15:10:57 +00005421 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5422 CurPEnd = CurMethod->param_end(),
5423 SuperP = SuperMethod->param_begin();
5424 CurP != CurPEnd; ++CurP, ++SuperP) {
5425 // Make sure the parameter types are compatible.
5426 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5427 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005428 return nullptr;
5429
Douglas Gregor6fc04132010-08-27 15:10:57 +00005430 // Make sure we have a parameter name to forward!
5431 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005432 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005433 }
5434
5435 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005436 CodeCompletionBuilder Builder(Results.getAllocator(),
5437 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005438
5439 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005440 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5441 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005442 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005443
5444 // If we need the "super" keyword, add it (plus some spacing).
5445 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005446 Builder.AddTypedTextChunk("super");
5447 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005448 }
5449
5450 Selector Sel = CurMethod->getSelector();
5451 if (Sel.isUnarySelector()) {
5452 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005453 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005454 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005455 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005456 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005457 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005458 } else {
5459 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5460 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005461 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005462 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005463
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005464 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005465 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005466 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005467 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005468 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005469 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005470 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005471 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005472 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005473 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005474 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005475 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005476 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005477 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005478 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005479 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005480 }
5481 }
5482 }
5483
Douglas Gregor78254c82012-03-27 23:34:16 +00005484 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5485 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005486 return SuperMethod;
5487}
5488
Douglas Gregora817a192010-05-27 23:06:34 +00005489void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005490 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005491 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005492 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005493 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005494 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005495 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5496 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005497
Douglas Gregora817a192010-05-27 23:06:34 +00005498 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5499 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005500 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5501 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005502
5503 // If we are in an Objective-C method inside a class that has a superclass,
5504 // add "super" as an option.
5505 if (ObjCMethodDecl *Method = getCurMethodDecl())
5506 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005507 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005508 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005509
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005510 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005511 }
Douglas Gregora817a192010-05-27 23:06:34 +00005512
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005513 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005514 addThisCompletion(*this, Results);
5515
Douglas Gregora817a192010-05-27 23:06:34 +00005516 Results.ExitScope();
5517
5518 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005519 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005520 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005521 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005522
5523}
5524
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005525void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005526 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005527 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005528 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005529 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5530 // Figure out which interface we're in.
5531 CDecl = CurMethod->getClassInterface();
5532 if (!CDecl)
5533 return;
5534
5535 // Find the superclass of this class.
5536 CDecl = CDecl->getSuperClass();
5537 if (!CDecl)
5538 return;
5539
5540 if (CurMethod->isInstanceMethod()) {
5541 // We are inside an instance method, which means that the message
5542 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005543 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005544 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005545 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005546 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005547 }
5548
5549 // Fall through to send to the superclass in CDecl.
5550 } else {
5551 // "super" may be the name of a type or variable. Figure out which
5552 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005553 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005554 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5555 LookupOrdinaryName);
5556 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5557 // "super" names an interface. Use it.
5558 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005559 if (const ObjCObjectType *Iface
5560 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5561 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005562 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5563 // "super" names an unresolved type; we can't be more specific.
5564 } else {
5565 // Assume that "super" names some kind of value and parse that way.
5566 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005567 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005568 UnqualifiedId id;
5569 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005570 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5571 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005572 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005573 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005574 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005575 }
5576
5577 // Fall through
5578 }
5579
John McCallba7bf592010-08-24 05:47:05 +00005580 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005581 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005582 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005583 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005584 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005585 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005586}
5587
Douglas Gregor74661272010-09-21 00:03:25 +00005588/// \brief Given a set of code-completion results for the argument of a message
5589/// send, determine the preferred type (if any) for that argument expression.
5590static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5591 unsigned NumSelIdents) {
5592 typedef CodeCompletionResult Result;
5593 ASTContext &Context = Results.getSema().Context;
5594
5595 QualType PreferredType;
5596 unsigned BestPriority = CCP_Unlikely * 2;
5597 Result *ResultsData = Results.data();
5598 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5599 Result &R = ResultsData[I];
5600 if (R.Kind == Result::RK_Declaration &&
5601 isa<ObjCMethodDecl>(R.Declaration)) {
5602 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005603 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005604 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005605 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005606 ->getType();
5607 if (R.Priority < BestPriority || PreferredType.isNull()) {
5608 BestPriority = R.Priority;
5609 PreferredType = MyPreferredType;
5610 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5611 MyPreferredType)) {
5612 PreferredType = QualType();
5613 }
5614 }
5615 }
5616 }
5617 }
5618
5619 return PreferredType;
5620}
5621
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005622static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5623 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005624 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005625 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005626 bool IsSuper,
5627 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005628 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005629 ObjCInterfaceDecl *CDecl = nullptr;
5630
Douglas Gregor8ce33212009-11-17 17:59:40 +00005631 // If the given name refers to an interface type, retrieve the
5632 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005633 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005634 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005635 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005636 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5637 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005638 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005639
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005640 // Add all of the factory methods in this Objective-C class, its protocols,
5641 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005642 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005643
Douglas Gregor6fc04132010-08-27 15:10:57 +00005644 // If this is a send-to-super, try to add the special "super" send
5645 // completion.
5646 if (IsSuper) {
5647 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005648 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005649 Results.Ignore(SuperMethod);
5650 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005651
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005652 // If we're inside an Objective-C method definition, prefer its selector to
5653 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005654 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005655 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005656
Douglas Gregor1154e272010-09-16 16:06:31 +00005657 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005658 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005659 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005660 SemaRef.CurContext, Selectors, AtArgumentExpression,
5661 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005662 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005663 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005664
Douglas Gregord720daf2010-04-06 17:30:22 +00005665 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005666 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005667 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005668 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005669 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005670 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005671 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005672 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005673 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005674
5675 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005676 }
5677 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005678
5679 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5680 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005681 M != MEnd; ++M) {
5682 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005683 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005684 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005685 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005686 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005687
Nico Weber2e0c8f72014-12-27 03:58:08 +00005688 Result R(MethList->getMethod(),
5689 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005690 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005691 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005692 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005693 }
5694 }
5695 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005696
5697 Results.ExitScope();
5698}
Douglas Gregor6285f752010-04-06 16:40:00 +00005699
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005700void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005701 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005702 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005703 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005704
5705 QualType T = this->GetTypeFromParser(Receiver);
5706
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005707 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005708 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005709 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005710 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005711
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005712 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005713 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005714
5715 // If we're actually at the argument expression (rather than prior to the
5716 // selector), we're actually performing code completion for an expression.
5717 // Determine whether we have a single, best method. If so, we can
5718 // code-complete the expression using the corresponding parameter type as
5719 // our preferred type, improving completion results.
5720 if (AtArgumentExpression) {
5721 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005722 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005723 if (PreferredType.isNull())
5724 CodeCompleteOrdinaryName(S, PCC_Expression);
5725 else
5726 CodeCompleteExpression(S, PreferredType);
5727 return;
5728 }
5729
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005730 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005731 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005732 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005733}
5734
Richard Trieu2bd04012011-09-09 02:00:50 +00005735void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005736 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005737 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005738 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005739 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005740
5741 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005742
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005743 // If necessary, apply function/array conversion to the receiver.
5744 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005745 if (RecExpr) {
5746 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5747 if (Conv.isInvalid()) // conversion failed. bail.
5748 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005749 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005750 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005751 QualType ReceiverType = RecExpr? RecExpr->getType()
5752 : Super? Context.getObjCObjectPointerType(
5753 Context.getObjCInterfaceType(Super))
5754 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005755
Douglas Gregordc520b02010-11-08 21:12:30 +00005756 // If we're messaging an expression with type "id" or "Class", check
5757 // whether we know something special about the receiver that allows
5758 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005759 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005760 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5761 if (ReceiverType->isObjCClassType())
5762 return CodeCompleteObjCClassMessage(S,
5763 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005764 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005765 AtArgumentExpression, Super);
5766
5767 ReceiverType = Context.getObjCObjectPointerType(
5768 Context.getObjCInterfaceType(IFace));
5769 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005770 } else if (RecExpr && getLangOpts().CPlusPlus) {
5771 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5772 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005773 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005774 ReceiverType = RecExpr->getType();
5775 }
5776 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005777
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005778 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005779 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005780 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005781 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005782 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005783
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005784 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005785
Douglas Gregor6fc04132010-08-27 15:10:57 +00005786 // If this is a send-to-super, try to add the special "super" send
5787 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005788 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005789 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005790 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005791 Results.Ignore(SuperMethod);
5792 }
5793
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005794 // If we're inside an Objective-C method definition, prefer its selector to
5795 // others.
5796 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5797 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005798
Douglas Gregor1154e272010-09-16 16:06:31 +00005799 // Keep track of the selectors we've already added.
5800 VisitedSelectorSet Selectors;
5801
Douglas Gregora3329fa2009-11-18 00:06:18 +00005802 // Handle messages to Class. This really isn't a message to an instance
5803 // method, so we treat it the same way we would treat a message send to a
5804 // class method.
5805 if (ReceiverType->isObjCClassType() ||
5806 ReceiverType->isObjCQualifiedClassType()) {
5807 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5808 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005809 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005810 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005811 }
5812 }
5813 // Handle messages to a qualified ID ("id<foo>").
5814 else if (const ObjCObjectPointerType *QualID
5815 = ReceiverType->getAsObjCQualifiedIdType()) {
5816 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005817 for (auto *I : QualID->quals())
5818 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005819 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005820 }
5821 // Handle messages to a pointer to interface type.
5822 else if (const ObjCObjectPointerType *IFacePtr
5823 = ReceiverType->getAsObjCInterfacePointerType()) {
5824 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005825 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005826 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005827 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005828
5829 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005830 for (auto *I : IFacePtr->quals())
5831 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005832 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005833 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005834 // Handle messages to "id".
5835 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005836 // We're messaging "id", so provide all instance methods we know
5837 // about as code-completion results.
5838
5839 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005840 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005841 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005842 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5843 I != N; ++I) {
5844 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005845 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005846 continue;
5847
Sebastian Redl75d8a322010-08-02 23:18:59 +00005848 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005849 }
5850 }
5851
Sebastian Redl75d8a322010-08-02 23:18:59 +00005852 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5853 MEnd = MethodPool.end();
5854 M != MEnd; ++M) {
5855 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005856 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005857 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005858 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005859 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005860
Nico Weber2e0c8f72014-12-27 03:58:08 +00005861 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005862 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005863
Nico Weber2e0c8f72014-12-27 03:58:08 +00005864 Result R(MethList->getMethod(),
5865 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005866 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005867 R.AllParametersAreInformative = false;
5868 Results.MaybeAddResult(R, CurContext);
5869 }
5870 }
5871 }
Steve Naroffeae65032009-11-07 02:08:14 +00005872 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005873
5874
5875 // If we're actually at the argument expression (rather than prior to the
5876 // selector), we're actually performing code completion for an expression.
5877 // Determine whether we have a single, best method. If so, we can
5878 // code-complete the expression using the corresponding parameter type as
5879 // our preferred type, improving completion results.
5880 if (AtArgumentExpression) {
5881 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005882 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005883 if (PreferredType.isNull())
5884 CodeCompleteOrdinaryName(S, PCC_Expression);
5885 else
5886 CodeCompleteExpression(S, PreferredType);
5887 return;
5888 }
5889
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005890 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005891 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005892 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005893}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005894
Douglas Gregor68762e72010-08-23 21:17:50 +00005895void Sema::CodeCompleteObjCForCollection(Scope *S,
5896 DeclGroupPtrTy IterationVar) {
5897 CodeCompleteExpressionData Data;
5898 Data.ObjCCollection = true;
5899
5900 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005901 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005902 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5903 if (*I)
5904 Data.IgnoreDecls.push_back(*I);
5905 }
5906 }
5907
5908 CodeCompleteExpression(S, Data);
5909}
5910
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005911void Sema::CodeCompleteObjCSelector(Scope *S,
5912 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005913 // If we have an external source, load the entire class method
5914 // pool from the AST file.
5915 if (ExternalSource) {
5916 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5917 I != N; ++I) {
5918 Selector Sel = ExternalSource->GetExternalSelector(I);
5919 if (Sel.isNull() || MethodPool.count(Sel))
5920 continue;
5921
5922 ReadMethodPool(Sel);
5923 }
5924 }
5925
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005926 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005927 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005928 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005929 Results.EnterNewScope();
5930 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5931 MEnd = MethodPool.end();
5932 M != MEnd; ++M) {
5933
5934 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005935 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005936 continue;
5937
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005938 CodeCompletionBuilder Builder(Results.getAllocator(),
5939 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005940 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005941 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005942 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005943 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005944 continue;
5945 }
5946
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005947 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005948 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005949 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005950 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005951 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005952 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005953 Accumulator.clear();
5954 }
5955 }
5956
Benjamin Kramer632500c2011-07-26 16:59:25 +00005957 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005958 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005959 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005960 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005961 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005962 }
5963 Results.ExitScope();
5964
5965 HandleCodeCompleteResults(this, CodeCompleter,
5966 CodeCompletionContext::CCC_SelectorName,
5967 Results.data(), Results.size());
5968}
5969
Douglas Gregorbaf69612009-11-18 04:19:12 +00005970/// \brief Add all of the protocol declarations that we find in the given
5971/// (translation unit) context.
5972static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005973 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005974 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005975 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005976
Aaron Ballman629afae2014-03-07 19:56:05 +00005977 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005978 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005979 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005980 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005981 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5982 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005983 }
5984}
5985
Craig Topper883dd332015-12-24 23:58:11 +00005986void Sema::CodeCompleteObjCProtocolReferences(
5987 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005988 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005989 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005990 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005991
Douglas Gregora3b23b02010-12-09 21:44:02 +00005992 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5993 Results.EnterNewScope();
5994
5995 // Tell the result set to ignore all of the protocols we have
5996 // already seen.
5997 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00005998 for (const IdentifierLocPair &Pair : Protocols)
5999 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6000 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00006001 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006002
Douglas Gregora3b23b02010-12-09 21:44:02 +00006003 // Add all protocols.
6004 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6005 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006006
Douglas Gregora3b23b02010-12-09 21:44:02 +00006007 Results.ExitScope();
6008 }
6009
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006010 HandleCodeCompleteResults(this, CodeCompleter,
6011 CodeCompletionContext::CCC_ObjCProtocolName,
6012 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006013}
6014
6015void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006016 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006017 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006018 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006019
Douglas Gregora3b23b02010-12-09 21:44:02 +00006020 if (CodeCompleter && CodeCompleter->includeGlobals()) {
6021 Results.EnterNewScope();
6022
6023 // Add all protocols.
6024 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6025 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006026
Douglas Gregora3b23b02010-12-09 21:44:02 +00006027 Results.ExitScope();
6028 }
6029
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006030 HandleCodeCompleteResults(this, CodeCompleter,
6031 CodeCompletionContext::CCC_ObjCProtocolName,
6032 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00006033}
Douglas Gregor49c22a72009-11-18 16:26:39 +00006034
6035/// \brief Add all of the Objective-C interface declarations that we find in
6036/// the given (translation unit) context.
6037static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6038 bool OnlyForwardDeclarations,
6039 bool OnlyUnimplemented,
6040 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006041 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00006042
Aaron Ballman629afae2014-03-07 19:56:05 +00006043 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00006044 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006045 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00006046 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00006047 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00006048 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6049 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006050 }
6051}
6052
6053void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006054 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006055 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006056 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006057 Results.EnterNewScope();
6058
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006059 if (CodeCompleter->includeGlobals()) {
6060 // Add all classes.
6061 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6062 false, Results);
6063 }
6064
Douglas Gregor49c22a72009-11-18 16:26:39 +00006065 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006066
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006067 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006068 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006069 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006070}
6071
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006072void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6073 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006074 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006075 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006076 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006077 Results.EnterNewScope();
6078
6079 // Make sure that we ignore the class we're currently defining.
6080 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006081 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006082 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006083 Results.Ignore(CurClass);
6084
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006085 if (CodeCompleter->includeGlobals()) {
6086 // Add all classes.
6087 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6088 false, Results);
6089 }
6090
Douglas Gregor49c22a72009-11-18 16:26:39 +00006091 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006092
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006093 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006094 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006095 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006096}
6097
6098void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006099 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006100 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006101 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006102 Results.EnterNewScope();
6103
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006104 if (CodeCompleter->includeGlobals()) {
6105 // Add all unimplemented classes.
6106 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6107 true, Results);
6108 }
6109
Douglas Gregor49c22a72009-11-18 16:26:39 +00006110 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006111
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006112 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006113 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006114 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006115}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006116
6117void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006118 IdentifierInfo *ClassName,
6119 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006120 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006121
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006122 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006123 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006124 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006125
6126 // Ignore any categories we find that have already been implemented by this
6127 // interface.
6128 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6129 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006130 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006131 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006132 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006133 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006134 }
6135
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006136 // Add all of the categories we know about.
6137 Results.EnterNewScope();
6138 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006139 for (const auto *D : TU->decls())
6140 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006141 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006142 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6143 nullptr),
6144 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006145 Results.ExitScope();
6146
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006147 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006148 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006149 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006150}
6151
6152void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006153 IdentifierInfo *ClassName,
6154 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006155 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006156
6157 // Find the corresponding interface. If we couldn't find the interface, the
6158 // program itself is ill-formed. However, we'll try to be helpful still by
6159 // providing the list of all of the categories we know about.
6160 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006161 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006162 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6163 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006164 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006165
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006167 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006168 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006169
6170 // Add all of the categories that have have corresponding interface
6171 // declarations in this class and any of its superclasses, except for
6172 // already-implemented categories in the class itself.
6173 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6174 Results.EnterNewScope();
6175 bool IgnoreImplemented = true;
6176 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006177 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006178 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006179 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006180 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6181 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006182 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006183
6184 Class = Class->getSuperClass();
6185 IgnoreImplemented = false;
6186 }
6187 Results.ExitScope();
6188
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006189 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006190 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006191 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006192}
Douglas Gregor5d649882009-11-18 22:32:06 +00006193
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006194void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006195 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006196 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006197 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006198 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006199
6200 // Figure out where this @synthesize lives.
6201 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006202 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006203 if (!Container ||
6204 (!isa<ObjCImplementationDecl>(Container) &&
6205 !isa<ObjCCategoryImplDecl>(Container)))
6206 return;
6207
6208 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006209 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006210 for (const auto *D : Container->decls())
6211 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006212 Results.Ignore(PropertyImpl->getPropertyDecl());
6213
6214 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006215 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006216 Results.EnterNewScope();
6217 if (ObjCImplementationDecl *ClassImpl
6218 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006219 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006220 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006221 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006222 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006223 AddObjCProperties(CCContext,
6224 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006225 false, /*AllowNullaryMethods=*/false, CurContext,
6226 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006227 Results.ExitScope();
6228
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006229 HandleCodeCompleteResults(this, CodeCompleter,
6230 CodeCompletionContext::CCC_Other,
6231 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006232}
6233
6234void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006235 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006236 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006237 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006238 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006239 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006240
6241 // Figure out where this @synthesize lives.
6242 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006243 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006244 if (!Container ||
6245 (!isa<ObjCImplementationDecl>(Container) &&
6246 !isa<ObjCCategoryImplDecl>(Container)))
6247 return;
6248
6249 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006250 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006251 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006252 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006253 Class = ClassImpl->getClassInterface();
6254 else
6255 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6256 ->getClassInterface();
6257
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006258 // Determine the type of the property we're synthesizing.
6259 QualType PropertyType = Context.getObjCIdType();
6260 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006261 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6262 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006263 PropertyType
6264 = Property->getType().getNonReferenceType().getUnqualifiedType();
6265
6266 // Give preference to ivars
6267 Results.setPreferredType(PropertyType);
6268 }
6269 }
6270
Douglas Gregor5d649882009-11-18 22:32:06 +00006271 // Add all of the instance variables in this class and its superclasses.
6272 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006273 bool SawSimilarlyNamedIvar = false;
6274 std::string NameWithPrefix;
6275 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006276 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006277 std::string NameWithSuffix = PropertyName->getName().str();
6278 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006279 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006280 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6281 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006282 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6283 CurContext, nullptr, false);
6284
Douglas Gregor331faa02011-04-18 14:13:53 +00006285 // Determine whether we've seen an ivar with a name similar to the
6286 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006287 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006288 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006289 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006290 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006291
6292 // Reduce the priority of this result by one, to give it a slight
6293 // advantage over other results whose names don't match so closely.
6294 if (Results.size() &&
6295 Results.data()[Results.size() - 1].Kind
6296 == CodeCompletionResult::RK_Declaration &&
6297 Results.data()[Results.size() - 1].Declaration == Ivar)
6298 Results.data()[Results.size() - 1].Priority--;
6299 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006300 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006301 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006302
6303 if (!SawSimilarlyNamedIvar) {
6304 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006305 // an ivar of the appropriate type.
6306 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006307 typedef CodeCompletionResult Result;
6308 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006309 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6310 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006311
Douglas Gregor75acd922011-09-27 23:30:47 +00006312 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006313 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006314 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006315 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6316 Results.AddResult(Result(Builder.TakeString(), Priority,
6317 CXCursor_ObjCIvarDecl));
6318 }
6319
Douglas Gregor5d649882009-11-18 22:32:06 +00006320 Results.ExitScope();
6321
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006322 HandleCodeCompleteResults(this, CodeCompleter,
6323 CodeCompletionContext::CCC_Other,
6324 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006325}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006326
Douglas Gregor416b5752010-08-25 01:08:01 +00006327// Mapping from selectors to the methods that implement that selector, along
6328// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006329typedef llvm::DenseMap<
6330 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006331
6332/// \brief Find all of the methods that reside in the given container
6333/// (and its superclasses, protocols, etc.) that meet the given
6334/// criteria. Insert those methods into the map of known methods,
6335/// indexed by selector so they can be easily found.
6336static void FindImplementableMethods(ASTContext &Context,
6337 ObjCContainerDecl *Container,
6338 bool WantInstanceMethods,
6339 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006340 KnownMethodsMap &KnownMethods,
6341 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006342 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006343 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006344 if (!IFace->hasDefinition())
6345 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006346
6347 IFace = IFace->getDefinition();
6348 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006349
Douglas Gregor636a61e2010-04-07 00:21:17 +00006350 const ObjCList<ObjCProtocolDecl> &Protocols
6351 = IFace->getReferencedProtocols();
6352 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006353 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006354 I != E; ++I)
6355 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006356 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006357
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006358 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006359 for (auto *Cat : IFace->visible_categories()) {
6360 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006361 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006362 }
6363
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006364 // Visit the superclass.
6365 if (IFace->getSuperClass())
6366 FindImplementableMethods(Context, IFace->getSuperClass(),
6367 WantInstanceMethods, ReturnType,
6368 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006369 }
6370
6371 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6372 // Recurse into protocols.
6373 const ObjCList<ObjCProtocolDecl> &Protocols
6374 = Category->getReferencedProtocols();
6375 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006376 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006377 I != E; ++I)
6378 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006379 KnownMethods, InOriginalClass);
6380
6381 // If this category is the original class, jump to the interface.
6382 if (InOriginalClass && Category->getClassInterface())
6383 FindImplementableMethods(Context, Category->getClassInterface(),
6384 WantInstanceMethods, ReturnType, KnownMethods,
6385 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006386 }
6387
6388 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006389 // Make sure we have a definition; that's what we'll walk.
6390 if (!Protocol->hasDefinition())
6391 return;
6392 Protocol = Protocol->getDefinition();
6393 Container = Protocol;
6394
6395 // Recurse into protocols.
6396 const ObjCList<ObjCProtocolDecl> &Protocols
6397 = Protocol->getReferencedProtocols();
6398 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6399 E = Protocols.end();
6400 I != E; ++I)
6401 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6402 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006403 }
6404
6405 // Add methods in this container. This operation occurs last because
6406 // we want the methods from this container to override any methods
6407 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006408 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006409 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006410 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006411 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006412 continue;
6413
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006414 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006415 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006416 }
6417 }
6418}
6419
Douglas Gregor669a25a2011-02-17 00:22:45 +00006420/// \brief Add the parenthesized return or parameter type chunk to a code
6421/// completion string.
6422static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006423 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006424 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006425 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006426 CodeCompletionBuilder &Builder) {
6427 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006428 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006429 if (!Quals.empty())
6430 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006431 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006432 Builder.getAllocator()));
6433 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6434}
6435
6436/// \brief Determine whether the given class is or inherits from a class by
6437/// the given name.
6438static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006439 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006440 if (!Class)
6441 return false;
6442
6443 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6444 return true;
6445
6446 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6447}
6448
6449/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6450/// Key-Value Observing (KVO).
6451static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6452 bool IsInstanceMethod,
6453 QualType ReturnType,
6454 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006455 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006456 ResultBuilder &Results) {
6457 IdentifierInfo *PropName = Property->getIdentifier();
6458 if (!PropName || PropName->getLength() == 0)
6459 return;
6460
Douglas Gregor75acd922011-09-27 23:30:47 +00006461 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6462
Douglas Gregor669a25a2011-02-17 00:22:45 +00006463 // Builder that will create each code completion.
6464 typedef CodeCompletionResult Result;
6465 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006466 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006467
6468 // The selector table.
6469 SelectorTable &Selectors = Context.Selectors;
6470
6471 // The property name, copied into the code completion allocation region
6472 // on demand.
6473 struct KeyHolder {
6474 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006475 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006476 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006477
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006478 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006479 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6480
Douglas Gregor669a25a2011-02-17 00:22:45 +00006481 operator const char *() {
6482 if (CopiedKey)
6483 return CopiedKey;
6484
6485 return CopiedKey = Allocator.CopyString(Key);
6486 }
6487 } Key(Allocator, PropName->getName());
6488
6489 // The uppercased name of the property name.
6490 std::string UpperKey = PropName->getName();
6491 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006492 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006493
6494 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6495 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6496 Property->getType());
6497 bool ReturnTypeMatchesVoid
6498 = ReturnType.isNull() || ReturnType->isVoidType();
6499
6500 // Add the normal accessor -(type)key.
6501 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006502 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006503 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6504 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006505 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6506 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006507
6508 Builder.AddTypedTextChunk(Key);
6509 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6510 CXCursor_ObjCInstanceMethodDecl));
6511 }
6512
6513 // If we have an integral or boolean property (or the user has provided
6514 // an integral or boolean return type), add the accessor -(type)isKey.
6515 if (IsInstanceMethod &&
6516 ((!ReturnType.isNull() &&
6517 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6518 (ReturnType.isNull() &&
6519 (Property->getType()->isIntegerType() ||
6520 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006521 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006522 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006523 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6524 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006525 if (ReturnType.isNull()) {
6526 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6527 Builder.AddTextChunk("BOOL");
6528 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6529 }
6530
6531 Builder.AddTypedTextChunk(
6532 Allocator.CopyString(SelectorId->getName()));
6533 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6534 CXCursor_ObjCInstanceMethodDecl));
6535 }
6536 }
6537
6538 // Add the normal mutator.
6539 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6540 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006541 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006542 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006543 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006544 if (ReturnType.isNull()) {
6545 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6546 Builder.AddTextChunk("void");
6547 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6548 }
6549
6550 Builder.AddTypedTextChunk(
6551 Allocator.CopyString(SelectorId->getName()));
6552 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006553 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6554 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006555 Builder.AddTextChunk(Key);
6556 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6557 CXCursor_ObjCInstanceMethodDecl));
6558 }
6559 }
6560
6561 // Indexed and unordered accessors
6562 unsigned IndexedGetterPriority = CCP_CodePattern;
6563 unsigned IndexedSetterPriority = CCP_CodePattern;
6564 unsigned UnorderedGetterPriority = CCP_CodePattern;
6565 unsigned UnorderedSetterPriority = CCP_CodePattern;
6566 if (const ObjCObjectPointerType *ObjCPointer
6567 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6568 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6569 // If this interface type is not provably derived from a known
6570 // collection, penalize the corresponding completions.
6571 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6572 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6573 if (!InheritsFromClassNamed(IFace, "NSArray"))
6574 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6575 }
6576
6577 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6578 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6579 if (!InheritsFromClassNamed(IFace, "NSSet"))
6580 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6581 }
6582 }
6583 } else {
6584 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6585 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6586 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6587 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6588 }
6589
6590 // Add -(NSUInteger)countOf<key>
6591 if (IsInstanceMethod &&
6592 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006593 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006594 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006595 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6596 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006597 if (ReturnType.isNull()) {
6598 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6599 Builder.AddTextChunk("NSUInteger");
6600 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6601 }
6602
6603 Builder.AddTypedTextChunk(
6604 Allocator.CopyString(SelectorId->getName()));
6605 Results.AddResult(Result(Builder.TakeString(),
6606 std::min(IndexedGetterPriority,
6607 UnorderedGetterPriority),
6608 CXCursor_ObjCInstanceMethodDecl));
6609 }
6610 }
6611
6612 // Indexed getters
6613 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6614 if (IsInstanceMethod &&
6615 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006616 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006617 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006618 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006619 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006620 if (ReturnType.isNull()) {
6621 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6622 Builder.AddTextChunk("id");
6623 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6624 }
6625
6626 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6628 Builder.AddTextChunk("NSUInteger");
6629 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6630 Builder.AddTextChunk("index");
6631 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6632 CXCursor_ObjCInstanceMethodDecl));
6633 }
6634 }
6635
6636 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6637 if (IsInstanceMethod &&
6638 (ReturnType.isNull() ||
6639 (ReturnType->isObjCObjectPointerType() &&
6640 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6641 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6642 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006643 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006644 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006645 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006646 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006647 if (ReturnType.isNull()) {
6648 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6649 Builder.AddTextChunk("NSArray *");
6650 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6651 }
6652
6653 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6654 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6655 Builder.AddTextChunk("NSIndexSet *");
6656 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6657 Builder.AddTextChunk("indexes");
6658 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6659 CXCursor_ObjCInstanceMethodDecl));
6660 }
6661 }
6662
6663 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6664 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006665 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006666 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006667 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006668 &Context.Idents.get("range")
6669 };
6670
David Blaikie82e95a32014-11-19 07:49:47 +00006671 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006672 if (ReturnType.isNull()) {
6673 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6674 Builder.AddTextChunk("void");
6675 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6676 }
6677
6678 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6679 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6680 Builder.AddPlaceholderChunk("object-type");
6681 Builder.AddTextChunk(" **");
6682 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6683 Builder.AddTextChunk("buffer");
6684 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6685 Builder.AddTypedTextChunk("range:");
6686 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6687 Builder.AddTextChunk("NSRange");
6688 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6689 Builder.AddTextChunk("inRange");
6690 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6691 CXCursor_ObjCInstanceMethodDecl));
6692 }
6693 }
6694
6695 // Mutable indexed accessors
6696
6697 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6698 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006699 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006700 IdentifierInfo *SelectorIds[2] = {
6701 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006702 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006703 };
6704
David Blaikie82e95a32014-11-19 07:49:47 +00006705 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).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("insertObject:");
6713 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6714 Builder.AddPlaceholderChunk("object-type");
6715 Builder.AddTextChunk(" *");
6716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6717 Builder.AddTextChunk("object");
6718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6719 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6720 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6721 Builder.AddPlaceholderChunk("NSUInteger");
6722 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6723 Builder.AddTextChunk("index");
6724 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6725 CXCursor_ObjCInstanceMethodDecl));
6726 }
6727 }
6728
6729 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6730 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006731 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006732 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006733 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006734 &Context.Idents.get("atIndexes")
6735 };
6736
David Blaikie82e95a32014-11-19 07:49:47 +00006737 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006738 if (ReturnType.isNull()) {
6739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6740 Builder.AddTextChunk("void");
6741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6742 }
6743
6744 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6746 Builder.AddTextChunk("NSArray *");
6747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6748 Builder.AddTextChunk("array");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddTypedTextChunk("atIndexes:");
6751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6752 Builder.AddPlaceholderChunk("NSIndexSet *");
6753 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6754 Builder.AddTextChunk("indexes");
6755 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6756 CXCursor_ObjCInstanceMethodDecl));
6757 }
6758 }
6759
6760 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6761 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006762 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006763 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006764 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006765 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006766 if (ReturnType.isNull()) {
6767 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6768 Builder.AddTextChunk("void");
6769 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6770 }
6771
6772 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6774 Builder.AddTextChunk("NSUInteger");
6775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6776 Builder.AddTextChunk("index");
6777 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6778 CXCursor_ObjCInstanceMethodDecl));
6779 }
6780 }
6781
6782 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6783 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006784 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006785 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006786 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006787 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006788 if (ReturnType.isNull()) {
6789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6790 Builder.AddTextChunk("void");
6791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6792 }
6793
6794 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6796 Builder.AddTextChunk("NSIndexSet *");
6797 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6798 Builder.AddTextChunk("indexes");
6799 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6800 CXCursor_ObjCInstanceMethodDecl));
6801 }
6802 }
6803
6804 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6805 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006806 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006807 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006808 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006809 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006810 &Context.Idents.get("withObject")
6811 };
6812
David Blaikie82e95a32014-11-19 07:49:47 +00006813 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006814 if (ReturnType.isNull()) {
6815 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6816 Builder.AddTextChunk("void");
6817 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6818 }
6819
6820 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6821 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6822 Builder.AddPlaceholderChunk("NSUInteger");
6823 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6824 Builder.AddTextChunk("index");
6825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6826 Builder.AddTypedTextChunk("withObject:");
6827 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6828 Builder.AddTextChunk("id");
6829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6830 Builder.AddTextChunk("object");
6831 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6832 CXCursor_ObjCInstanceMethodDecl));
6833 }
6834 }
6835
6836 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6837 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006838 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006839 = (Twine("replace") + UpperKey + "AtIndexes").str();
6840 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006841 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006842 &Context.Idents.get(SelectorName1),
6843 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006844 };
6845
David Blaikie82e95a32014-11-19 07:49:47 +00006846 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006847 if (ReturnType.isNull()) {
6848 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6849 Builder.AddTextChunk("void");
6850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6851 }
6852
6853 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6855 Builder.AddPlaceholderChunk("NSIndexSet *");
6856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6857 Builder.AddTextChunk("indexes");
6858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6859 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6860 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6861 Builder.AddTextChunk("NSArray *");
6862 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6863 Builder.AddTextChunk("array");
6864 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6865 CXCursor_ObjCInstanceMethodDecl));
6866 }
6867 }
6868
6869 // Unordered getters
6870 // - (NSEnumerator *)enumeratorOfKey
6871 if (IsInstanceMethod &&
6872 (ReturnType.isNull() ||
6873 (ReturnType->isObjCObjectPointerType() &&
6874 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6875 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6876 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006877 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006878 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006879 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6880 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006881 if (ReturnType.isNull()) {
6882 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6883 Builder.AddTextChunk("NSEnumerator *");
6884 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6885 }
6886
6887 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6888 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6889 CXCursor_ObjCInstanceMethodDecl));
6890 }
6891 }
6892
6893 // - (type *)memberOfKey:(type *)object
6894 if (IsInstanceMethod &&
6895 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006896 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006897 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006898 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006899 if (ReturnType.isNull()) {
6900 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6901 Builder.AddPlaceholderChunk("object-type");
6902 Builder.AddTextChunk(" *");
6903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6904 }
6905
6906 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6907 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6908 if (ReturnType.isNull()) {
6909 Builder.AddPlaceholderChunk("object-type");
6910 Builder.AddTextChunk(" *");
6911 } else {
6912 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006913 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006914 Builder.getAllocator()));
6915 }
6916 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6917 Builder.AddTextChunk("object");
6918 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6919 CXCursor_ObjCInstanceMethodDecl));
6920 }
6921 }
6922
6923 // Mutable unordered accessors
6924 // - (void)addKeyObject:(type *)object
6925 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006926 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006927 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006928 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006929 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006930 if (ReturnType.isNull()) {
6931 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6932 Builder.AddTextChunk("void");
6933 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6934 }
6935
6936 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6937 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6938 Builder.AddPlaceholderChunk("object-type");
6939 Builder.AddTextChunk(" *");
6940 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6941 Builder.AddTextChunk("object");
6942 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6943 CXCursor_ObjCInstanceMethodDecl));
6944 }
6945 }
6946
6947 // - (void)addKey:(NSSet *)objects
6948 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006949 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006950 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006951 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006952 if (ReturnType.isNull()) {
6953 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6954 Builder.AddTextChunk("void");
6955 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6956 }
6957
6958 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6959 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6960 Builder.AddTextChunk("NSSet *");
6961 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6962 Builder.AddTextChunk("objects");
6963 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6964 CXCursor_ObjCInstanceMethodDecl));
6965 }
6966 }
6967
6968 // - (void)removeKeyObject:(type *)object
6969 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006970 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006971 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006972 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006973 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006974 if (ReturnType.isNull()) {
6975 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6976 Builder.AddTextChunk("void");
6977 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6978 }
6979
6980 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6981 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6982 Builder.AddPlaceholderChunk("object-type");
6983 Builder.AddTextChunk(" *");
6984 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6985 Builder.AddTextChunk("object");
6986 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6987 CXCursor_ObjCInstanceMethodDecl));
6988 }
6989 }
6990
6991 // - (void)removeKey:(NSSet *)objects
6992 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006993 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006994 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006995 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006996 if (ReturnType.isNull()) {
6997 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6998 Builder.AddTextChunk("void");
6999 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7000 }
7001
7002 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7003 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7004 Builder.AddTextChunk("NSSet *");
7005 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7006 Builder.AddTextChunk("objects");
7007 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7008 CXCursor_ObjCInstanceMethodDecl));
7009 }
7010 }
7011
7012 // - (void)intersectKey:(NSSet *)objects
7013 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007014 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007015 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007016 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007017 if (ReturnType.isNull()) {
7018 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7019 Builder.AddTextChunk("void");
7020 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7021 }
7022
7023 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7025 Builder.AddTextChunk("NSSet *");
7026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7027 Builder.AddTextChunk("objects");
7028 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7029 CXCursor_ObjCInstanceMethodDecl));
7030 }
7031 }
7032
7033 // Key-Value Observing
7034 // + (NSSet *)keyPathsForValuesAffectingKey
7035 if (!IsInstanceMethod &&
7036 (ReturnType.isNull() ||
7037 (ReturnType->isObjCObjectPointerType() &&
7038 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7039 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7040 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007041 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007042 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007043 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007044 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7045 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007046 if (ReturnType.isNull()) {
7047 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7048 Builder.AddTextChunk("NSSet *");
7049 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7050 }
7051
7052 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7053 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007054 CXCursor_ObjCClassMethodDecl));
7055 }
7056 }
7057
7058 // + (BOOL)automaticallyNotifiesObserversForKey
7059 if (!IsInstanceMethod &&
7060 (ReturnType.isNull() ||
7061 ReturnType->isIntegerType() ||
7062 ReturnType->isBooleanType())) {
7063 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007064 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007065 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007066 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7067 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007068 if (ReturnType.isNull()) {
7069 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7070 Builder.AddTextChunk("BOOL");
7071 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7072 }
7073
7074 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7075 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7076 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007077 }
7078 }
7079}
7080
Douglas Gregor636a61e2010-04-07 00:21:17 +00007081void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7082 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007083 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007084 // Determine the return type of the method we're declaring, if
7085 // provided.
7086 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007087 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007088 if (CurContext->isObjCContainer()) {
7089 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7090 IDecl = cast<Decl>(OCD);
7091 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007092 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007093 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007094 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007095 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007096 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7097 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007098 IsInImplementation = true;
7099 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007100 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007101 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007102 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007103 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007104 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007105 }
7106
7107 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007108 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007109 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007110 }
7111
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007112 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007113 HandleCodeCompleteResults(this, CodeCompleter,
7114 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007115 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007116 return;
7117 }
7118
7119 // Find all of the methods that we could declare/implement here.
7120 KnownMethodsMap KnownMethods;
7121 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007122 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007123
Douglas Gregor636a61e2010-04-07 00:21:17 +00007124 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007125 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007126 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007127 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007128 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007129 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007130 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007131 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7132 MEnd = KnownMethods.end();
7133 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007134 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007135 CodeCompletionBuilder Builder(Results.getAllocator(),
7136 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007137
7138 // If the result type was not already provided, add it to the
7139 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007140 if (ReturnType.isNull()) {
7141 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7142 AttributedType::stripOuterNullability(ResTy);
7143 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007144 Method->getObjCDeclQualifier(), Context, Policy,
7145 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007146 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007147
7148 Selector Sel = Method->getSelector();
7149
7150 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007151 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007152 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007153
7154 // Add parameters to the pattern.
7155 unsigned I = 0;
7156 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7157 PEnd = Method->param_end();
7158 P != PEnd; (void)++P, ++I) {
7159 // Add the part of the selector name.
7160 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007161 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007162 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007163 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7164 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007165 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007166 } else
7167 break;
7168
7169 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007170 QualType ParamType;
7171 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7172 ParamType = (*P)->getType();
7173 else
7174 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007175 ParamType = ParamType.substObjCTypeArgs(Context, {},
7176 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007177 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007178 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007179 (*P)->getObjCDeclQualifier(),
7180 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007181 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007182
7183 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007184 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007185 }
7186
7187 if (Method->isVariadic()) {
7188 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007189 Builder.AddChunk(CodeCompletionString::CK_Comma);
7190 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007191 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007192
Douglas Gregord37c59d2010-05-28 00:57:46 +00007193 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007194 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007195 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7196 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7197 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007198 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007199 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007200 Builder.AddTextChunk("return");
7201 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7202 Builder.AddPlaceholderChunk("expression");
7203 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007204 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007205 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007206
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007207 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7208 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007209 }
7210
Douglas Gregor416b5752010-08-25 01:08:01 +00007211 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007212 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007213 Priority += CCD_InBaseClass;
7214
Douglas Gregor78254c82012-03-27 23:34:16 +00007215 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007216 }
7217
Douglas Gregor669a25a2011-02-17 00:22:45 +00007218 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7219 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007220 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007221 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007222 Containers.push_back(SearchDecl);
7223
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007224 VisitedSelectorSet KnownSelectors;
7225 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7226 MEnd = KnownMethods.end();
7227 M != MEnd; ++M)
7228 KnownSelectors.insert(M->first);
7229
7230
Douglas Gregor669a25a2011-02-17 00:22:45 +00007231 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7232 if (!IFace)
7233 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7234 IFace = Category->getClassInterface();
7235
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007236 if (IFace)
7237 for (auto *Cat : IFace->visible_categories())
7238 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007239
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007240 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007241 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007242 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007243 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007244 }
7245
Douglas Gregor636a61e2010-04-07 00:21:17 +00007246 Results.ExitScope();
7247
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007248 HandleCodeCompleteResults(this, CodeCompleter,
7249 CodeCompletionContext::CCC_Other,
7250 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007251}
Douglas Gregor95887f92010-07-08 23:20:03 +00007252
7253void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7254 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007255 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007256 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007257 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007258 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007259 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007260 if (ExternalSource) {
7261 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7262 I != N; ++I) {
7263 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007264 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007265 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007266
7267 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007268 }
7269 }
7270
7271 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007272 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007273 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007274 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007275 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007276
7277 if (ReturnTy)
7278 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007279
Douglas Gregor95887f92010-07-08 23:20:03 +00007280 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007281 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7282 MEnd = MethodPool.end();
7283 M != MEnd; ++M) {
7284 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7285 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007286 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007287 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007288 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007289 continue;
7290
Douglas Gregor45879692010-07-08 23:37:41 +00007291 if (AtParameterName) {
7292 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007293 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007294 if (NumSelIdents &&
7295 NumSelIdents <= MethList->getMethod()->param_size()) {
7296 ParmVarDecl *Param =
7297 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007298 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007299 CodeCompletionBuilder Builder(Results.getAllocator(),
7300 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007301 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007302 Param->getIdentifier()->getName()));
7303 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007304 }
7305 }
7306
7307 continue;
7308 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007309
Nico Weber2e0c8f72014-12-27 03:58:08 +00007310 Result R(MethList->getMethod(),
7311 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007312 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007313 R.AllParametersAreInformative = false;
7314 R.DeclaringEntity = true;
7315 Results.MaybeAddResult(R, CurContext);
7316 }
7317 }
7318
7319 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007320 HandleCodeCompleteResults(this, CodeCompleter,
7321 CodeCompletionContext::CCC_Other,
7322 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007323}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007324
Douglas Gregorec00a262010-08-24 22:20:20 +00007325void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007326 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007327 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007328 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007329 Results.EnterNewScope();
7330
7331 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007332 CodeCompletionBuilder Builder(Results.getAllocator(),
7333 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007334 Builder.AddTypedTextChunk("if");
7335 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7336 Builder.AddPlaceholderChunk("condition");
7337 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007338
7339 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007340 Builder.AddTypedTextChunk("ifdef");
7341 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7342 Builder.AddPlaceholderChunk("macro");
7343 Results.AddResult(Builder.TakeString());
7344
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007345 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007346 Builder.AddTypedTextChunk("ifndef");
7347 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7348 Builder.AddPlaceholderChunk("macro");
7349 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007350
7351 if (InConditional) {
7352 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007353 Builder.AddTypedTextChunk("elif");
7354 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7355 Builder.AddPlaceholderChunk("condition");
7356 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007357
7358 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007359 Builder.AddTypedTextChunk("else");
7360 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007361
7362 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007363 Builder.AddTypedTextChunk("endif");
7364 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007365 }
7366
7367 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007368 Builder.AddTypedTextChunk("include");
7369 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7370 Builder.AddTextChunk("\"");
7371 Builder.AddPlaceholderChunk("header");
7372 Builder.AddTextChunk("\"");
7373 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007374
7375 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007376 Builder.AddTypedTextChunk("include");
7377 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7378 Builder.AddTextChunk("<");
7379 Builder.AddPlaceholderChunk("header");
7380 Builder.AddTextChunk(">");
7381 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007382
7383 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007384 Builder.AddTypedTextChunk("define");
7385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7386 Builder.AddPlaceholderChunk("macro");
7387 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007388
7389 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007390 Builder.AddTypedTextChunk("define");
7391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7392 Builder.AddPlaceholderChunk("macro");
7393 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7394 Builder.AddPlaceholderChunk("args");
7395 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7396 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007397
7398 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007399 Builder.AddTypedTextChunk("undef");
7400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7401 Builder.AddPlaceholderChunk("macro");
7402 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007403
7404 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007405 Builder.AddTypedTextChunk("line");
7406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7407 Builder.AddPlaceholderChunk("number");
7408 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007409
7410 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007411 Builder.AddTypedTextChunk("line");
7412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7413 Builder.AddPlaceholderChunk("number");
7414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7415 Builder.AddTextChunk("\"");
7416 Builder.AddPlaceholderChunk("filename");
7417 Builder.AddTextChunk("\"");
7418 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007419
7420 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007421 Builder.AddTypedTextChunk("error");
7422 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7423 Builder.AddPlaceholderChunk("message");
7424 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007425
7426 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007427 Builder.AddTypedTextChunk("pragma");
7428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7429 Builder.AddPlaceholderChunk("arguments");
7430 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007431
David Blaikiebbafb8a2012-03-11 07:00:24 +00007432 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007433 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007434 Builder.AddTypedTextChunk("import");
7435 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7436 Builder.AddTextChunk("\"");
7437 Builder.AddPlaceholderChunk("header");
7438 Builder.AddTextChunk("\"");
7439 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007440
7441 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007442 Builder.AddTypedTextChunk("import");
7443 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7444 Builder.AddTextChunk("<");
7445 Builder.AddPlaceholderChunk("header");
7446 Builder.AddTextChunk(">");
7447 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007448 }
7449
7450 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007451 Builder.AddTypedTextChunk("include_next");
7452 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7453 Builder.AddTextChunk("\"");
7454 Builder.AddPlaceholderChunk("header");
7455 Builder.AddTextChunk("\"");
7456 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007457
7458 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007459 Builder.AddTypedTextChunk("include_next");
7460 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7461 Builder.AddTextChunk("<");
7462 Builder.AddPlaceholderChunk("header");
7463 Builder.AddTextChunk(">");
7464 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007465
7466 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007467 Builder.AddTypedTextChunk("warning");
7468 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7469 Builder.AddPlaceholderChunk("message");
7470 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007471
7472 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7473 // completions for them. And __include_macros is a Clang-internal extension
7474 // that we don't want to encourage anyone to use.
7475
7476 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7477 Results.ExitScope();
7478
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007479 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007480 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007481 Results.data(), Results.size());
7482}
7483
7484void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007485 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007486 S->getFnParent()? Sema::PCC_RecoveryInFunction
7487 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007488}
7489
Douglas Gregorec00a262010-08-24 22:20:20 +00007490void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007491 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007492 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007493 IsDefinition? CodeCompletionContext::CCC_MacroName
7494 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007495 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7496 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007497 CodeCompletionBuilder Builder(Results.getAllocator(),
7498 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007499 Results.EnterNewScope();
7500 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7501 MEnd = PP.macro_end();
7502 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007503 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007504 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007505 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7506 CCP_CodePattern,
7507 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007508 }
7509 Results.ExitScope();
7510 } else if (IsDefinition) {
7511 // FIXME: Can we detect when the user just wrote an include guard above?
7512 }
7513
Douglas Gregor0ac41382010-09-23 23:01:17 +00007514 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007515 Results.data(), Results.size());
7516}
7517
Douglas Gregorec00a262010-08-24 22:20:20 +00007518void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007519 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007520 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007521 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007522
7523 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007524 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007525
7526 // defined (<macro>)
7527 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007528 CodeCompletionBuilder Builder(Results.getAllocator(),
7529 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007530 Builder.AddTypedTextChunk("defined");
7531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7532 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7533 Builder.AddPlaceholderChunk("macro");
7534 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7535 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007536 Results.ExitScope();
7537
7538 HandleCodeCompleteResults(this, CodeCompleter,
7539 CodeCompletionContext::CCC_PreprocessorExpression,
7540 Results.data(), Results.size());
7541}
7542
7543void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7544 IdentifierInfo *Macro,
7545 MacroInfo *MacroInfo,
7546 unsigned Argument) {
7547 // FIXME: In the future, we could provide "overload" results, much like we
7548 // do for function calls.
7549
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007550 // Now just ignore this. There will be another code-completion callback
7551 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007552}
7553
Douglas Gregor11583702010-08-25 17:04:25 +00007554void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007555 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007556 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007557 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007558}
7559
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007560void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007561 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007562 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007563 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7564 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007565 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7566 CodeCompletionDeclConsumer Consumer(Builder,
7567 Context.getTranslationUnitDecl());
7568 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7569 Consumer);
7570 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007571
7572 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007573 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007574
7575 Results.clear();
7576 Results.insert(Results.end(),
7577 Builder.data(), Builder.data() + Builder.size());
7578}