blob: 72ab65fc58ce0a27a3ee7a7feecc74e1a4a75b23 [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//===----------------------------------------------------------------------===//
Ilya Biryukov4e7a6fe2017-09-22 19:07:37 +000013#include "clang/AST/DeclCXX.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"
Ilya Biryukov4e7a6fe2017-09-22 19:07:37 +000026#include "clang/Sema/SemaInternal.h"
Douglas Gregor1154e272010-09-16 16:06:31 +000027#include "llvm/ADT/DenseSet.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000028#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000029#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000030#include "llvm/ADT/SmallString.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000032#include "llvm/ADT/StringSwitch.h"
Douglas Gregor67c692c2010-08-26 15:07:07 +000033#include "llvm/ADT/Twine.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000034#include <list>
35#include <map>
36#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000037
38using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000039using namespace sema;
Douglas Gregor2436e712009-09-17 21:32:03 +000040
Douglas Gregor3545ff42009-09-21 16:56:56 +000041namespace {
42 /// \brief A container of code-completion results.
43 class ResultBuilder {
44 public:
45 /// \brief The type of a name-lookup filter, which can be provided to the
46 /// name-lookup routines to specify which declarations should be included in
47 /// the result set (when it returns true) and which declarations should be
48 /// filtered out (returns false).
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000049 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
Ivan Donchevskii13d90542017-10-27 11:05:40 +000050
John McCall276321a2010-08-25 06:19:51 +000051 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +000052
53 private:
54 /// \brief The actual results we have found.
55 std::vector<Result> Results;
56
57 /// \brief A record of all of the declarations we have found and placed
58 /// into the result set, used to ensure that no declaration ever gets into
59 /// the result set twice.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000060 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
Douglas Gregor3545ff42009-09-21 16:56:56 +000061
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000062 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000063
64 /// \brief An entry in the shadow map, which is optimized to store
65 /// a single (declaration, index) mapping (the common case) but
66 /// can also store a list of (declaration, index) mappings.
67 class ShadowMapEntry {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000069
70 /// \brief Contains either the solitary NamedDecl * or a vector
71 /// of (declaration, index) pairs.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000072 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000073
74 /// \brief When the entry contains a single declaration, this is
75 /// the index associated with that entry.
76 unsigned SingleDeclIndex;
77
78 public:
79 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000081 void Add(const NamedDecl *ND, unsigned Index) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000082 if (DeclOrVector.isNull()) {
83 // 0 - > 1 elements: just set the single element information.
84 DeclOrVector = ND;
85 SingleDeclIndex = Index;
86 return;
87 }
88
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000089 if (const NamedDecl *PrevND =
90 DeclOrVector.dyn_cast<const NamedDecl *>()) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000091 // 1 -> 2 elements: create the vector of results and push in the
92 // existing declaration.
93 DeclIndexPairVector *Vec = new DeclIndexPairVector;
94 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
95 DeclOrVector = Vec;
96 }
97
98 // Add the new element to the end of the vector.
99 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
100 DeclIndexPair(ND, Index));
101 }
102
103 void Destroy() {
104 if (DeclIndexPairVector *Vec
105 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
106 delete Vec;
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 DeclOrVector = ((NamedDecl *)nullptr);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000108 }
109 }
110
111 // Iteration.
112 class iterator;
113 iterator begin() const;
114 iterator end() const;
115 };
116
Douglas Gregor3545ff42009-09-21 16:56:56 +0000117 /// \brief A mapping from declaration names to the declarations that have
118 /// this name within a particular scope and their index within the list of
119 /// results.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000120 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000121
122 /// \brief The semantic analysis object for which results are being
123 /// produced.
124 Sema &SemaRef;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000125
126 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000127 CodeCompletionAllocator &Allocator;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000128
129 CodeCompletionTUInfo &CCTUInfo;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000130
131 /// \brief If non-NULL, a filter function used to remove any code-completion
132 /// results that are not desirable.
133 LookupFilter Filter;
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000134
135 /// \brief Whether we should allow declarations as
136 /// nested-name-specifiers that would otherwise be filtered out.
137 bool AllowNestedNameSpecifiers;
138
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000139 /// \brief If set, the type that we would prefer our resulting value
140 /// declarations to have.
141 ///
142 /// Closely matching the preferred type gives a boost to a result's
143 /// priority.
144 CanQualType PreferredType;
145
Douglas Gregor3545ff42009-09-21 16:56:56 +0000146 /// \brief A list of shadow maps, which is used to model name hiding at
147 /// different levels of, e.g., the inheritance hierarchy.
148 std::list<ShadowMap> ShadowMaps;
149
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000150 /// \brief If we're potentially referring to a C++ member function, the set
151 /// of qualifiers applied to the object type.
152 Qualifiers ObjectTypeQualifiers;
153
154 /// \brief Whether the \p ObjectTypeQualifiers field is active.
155 bool HasObjectTypeQualifiers;
156
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000157 /// \brief The selector that we prefer.
158 Selector PreferredSelector;
159
Douglas Gregor05fcf842010-11-02 20:36:02 +0000160 /// \brief The completion context in which we are gathering results.
Douglas Gregor50832e02010-09-20 22:39:41 +0000161 CodeCompletionContext CompletionContext;
162
James Dennett596e4752012-06-14 03:11:41 +0000163 /// \brief If we are in an instance method definition, the \@implementation
Douglas Gregor05fcf842010-11-02 20:36:02 +0000164 /// object.
165 ObjCImplementationDecl *ObjCImplementation;
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000166
Douglas Gregor50832e02010-09-20 22:39:41 +0000167 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor95887f92010-07-08 23:20:03 +0000168
Douglas Gregor0212fd72010-09-21 16:06:22 +0000169 void MaybeAddConstructorResults(Result R);
170
Douglas Gregor3545ff42009-09-21 16:56:56 +0000171 public:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000172 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000173 CodeCompletionTUInfo &CCTUInfo,
Douglas Gregor0ac41382010-09-23 23:01:17 +0000174 const CodeCompletionContext &CompletionContext,
Craig Topperc3ec1492014-05-26 06:22:03 +0000175 LookupFilter Filter = nullptr)
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000176 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
177 Filter(Filter),
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000178 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregor05fcf842010-11-02 20:36:02 +0000179 CompletionContext(CompletionContext),
Craig Topperc3ec1492014-05-26 06:22:03 +0000180 ObjCImplementation(nullptr)
Douglas Gregor05fcf842010-11-02 20:36:02 +0000181 {
182 // If this is an Objective-C instance method definition, dig out the
183 // corresponding implementation.
184 switch (CompletionContext.getKind()) {
185 case CodeCompletionContext::CCC_Expression:
186 case CodeCompletionContext::CCC_ObjCMessageReceiver:
187 case CodeCompletionContext::CCC_ParenthesizedExpression:
188 case CodeCompletionContext::CCC_Statement:
189 case CodeCompletionContext::CCC_Recovery:
190 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
191 if (Method->isInstanceMethod())
192 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
193 ObjCImplementation = Interface->getImplementation();
194 break;
195
196 default:
197 break;
198 }
199 }
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000200
201 /// \brief Determine the priority for a reference to the given declaration.
202 unsigned getBasePriority(const NamedDecl *D);
203
Douglas Gregorf64acca2010-05-25 21:41:55 +0000204 /// \brief Whether we should include code patterns in the completion
205 /// results.
206 bool includeCodePatterns() const {
207 return SemaRef.CodeCompleter &&
Douglas Gregorac322ec2010-08-27 21:18:54 +0000208 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregorf64acca2010-05-25 21:41:55 +0000209 }
210
Douglas Gregor3545ff42009-09-21 16:56:56 +0000211 /// \brief Set the filter used for code-completion results.
212 void setFilter(LookupFilter Filter) {
213 this->Filter = Filter;
214 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000215
216 Result *data() { return Results.empty()? nullptr : &Results.front(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000217 unsigned size() const { return Results.size(); }
218 bool empty() const { return Results.empty(); }
219
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000220 /// \brief Specify the preferred type.
221 void setPreferredType(QualType T) {
222 PreferredType = SemaRef.Context.getCanonicalType(T);
223 }
224
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000225 /// \brief Set the cv-qualifiers on the object type, for us in filtering
226 /// calls to member functions.
227 ///
228 /// When there are qualifiers in this set, they will be used to filter
229 /// out member functions that aren't available (because there will be a
230 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231 /// match.
232 void setObjectTypeQualifiers(Qualifiers Quals) {
233 ObjectTypeQualifiers = Quals;
234 HasObjectTypeQualifiers = true;
235 }
236
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000237 /// \brief Set the preferred selector.
238 ///
239 /// When an Objective-C method declaration result is added, and that
240 /// method's selector matches this preferred selector, we give that method
241 /// a slight priority boost.
242 void setPreferredSelector(Selector Sel) {
243 PreferredSelector = Sel;
244 }
Douglas Gregor05fcf842010-11-02 20:36:02 +0000245
Douglas Gregor50832e02010-09-20 22:39:41 +0000246 /// \brief Retrieve the code-completion context for which results are
247 /// being collected.
248 const CodeCompletionContext &getCompletionContext() const {
249 return CompletionContext;
250 }
251
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000252 /// \brief Specify whether nested-name-specifiers are allowed.
253 void allowNestedNameSpecifiers(bool Allow = true) {
254 AllowNestedNameSpecifiers = Allow;
255 }
256
Douglas Gregor74661272010-09-21 00:03:25 +0000257 /// \brief Return the semantic analysis object for which we are collecting
258 /// code completion results.
259 Sema &getSema() const { return SemaRef; }
260
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000261 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000262 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000263
264 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000265
Douglas Gregor7c208612010-01-14 00:20:49 +0000266 /// \brief Determine whether the given declaration is at all interesting
267 /// as a code-completion result.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000268 ///
269 /// \param ND the declaration that we are inspecting.
270 ///
271 /// \param AsNestedNameSpecifier will be set true if this declaration is
272 /// only interesting when it is a nested-name-specifier.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000273 bool isInterestingDecl(const NamedDecl *ND,
274 bool &AsNestedNameSpecifier) const;
Douglas Gregore0717ab2010-01-14 00:41:07 +0000275
276 /// \brief Check whether the result is hidden by the Hiding declaration.
277 ///
278 /// \returns true if the result is hidden and cannot be found, false if
279 /// the hidden result could still be found. When false, \p R may be
280 /// modified to describe how the result can be found (e.g., via extra
281 /// qualification).
282 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000283 const NamedDecl *Hiding);
Douglas Gregore0717ab2010-01-14 00:41:07 +0000284
Douglas Gregor3545ff42009-09-21 16:56:56 +0000285 /// \brief Add a new result to this result set (if it isn't already in one
286 /// of the shadow maps), or replace an existing result (for, e.g., a
287 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000288 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000289 /// \param R the result to add (if it is unique).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000290 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000291 /// \param CurContext the context in which this result will be named.
Craig Topperc3ec1492014-05-26 06:22:03 +0000292 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
293
Douglas Gregorc580c522010-01-14 01:09:38 +0000294 /// \brief Add a new result to this result set, where we already know
Yaron Keren8fbe43982014-11-14 18:33:42 +0000295 /// the hiding declaration (if any).
Douglas Gregorc580c522010-01-14 01:09:38 +0000296 ///
297 /// \param R the result to add (if it is unique).
298 ///
299 /// \param CurContext the context in which this result will be named.
300 ///
301 /// \param Hiding the declaration that hides the result.
Douglas Gregor09bbc652010-01-14 15:47:35 +0000302 ///
303 /// \param InBaseClass whether the result was found in a base
304 /// class of the searched context.
305 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
306 bool InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +0000307
Douglas Gregor78a21012010-01-14 16:01:26 +0000308 /// \brief Add a new non-declaration result to this result set.
309 void AddResult(Result R);
310
Douglas Gregor3545ff42009-09-21 16:56:56 +0000311 /// \brief Enter into a new scope.
312 void EnterNewScope();
313
314 /// \brief Exit from the current scope.
315 void ExitScope();
316
Douglas Gregorbaf69612009-11-18 04:19:12 +0000317 /// \brief Ignore this declaration, if it is seen again.
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +0000318 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
Douglas Gregorbaf69612009-11-18 04:19:12 +0000319
Douglas Gregor3545ff42009-09-21 16:56:56 +0000320 /// \name Name lookup predicates
321 ///
322 /// These predicates can be passed to the name lookup functions to filter the
323 /// results of name lookup. All of the predicates have the same type, so that
324 ///
325 //@{
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000326 bool IsOrdinaryName(const NamedDecl *ND) const;
327 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
328 bool IsIntegralConstantValue(const NamedDecl *ND) const;
329 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
330 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
331 bool IsEnum(const NamedDecl *ND) const;
332 bool IsClassOrStruct(const NamedDecl *ND) const;
333 bool IsUnion(const NamedDecl *ND) const;
334 bool IsNamespace(const NamedDecl *ND) const;
335 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
336 bool IsType(const NamedDecl *ND) const;
337 bool IsMember(const NamedDecl *ND) const;
338 bool IsObjCIvar(const NamedDecl *ND) const;
339 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
340 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
341 bool IsObjCCollection(const NamedDecl *ND) const;
342 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000343 //@}
344 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000345}
Douglas Gregor3545ff42009-09-21 16:56:56 +0000346
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000347class ResultBuilder::ShadowMapEntry::iterator {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000348 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000349 unsigned SingleDeclIndex;
350
351public:
352 typedef DeclIndexPair value_type;
353 typedef value_type reference;
354 typedef std::ptrdiff_t difference_type;
355 typedef std::input_iterator_tag iterator_category;
356
357 class pointer {
358 DeclIndexPair Value;
359
360 public:
361 pointer(const DeclIndexPair &Value) : Value(Value) { }
362
363 const DeclIndexPair *operator->() const {
364 return &Value;
365 }
366 };
Craig Topperc3ec1492014-05-26 06:22:03 +0000367
368 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000369
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000370 iterator(const NamedDecl *SingleDecl, unsigned Index)
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000371 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
372
373 iterator(const DeclIndexPair *Iterator)
374 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
375
376 iterator &operator++() {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000377 if (DeclOrIterator.is<const NamedDecl *>()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000378 DeclOrIterator = (NamedDecl *)nullptr;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000379 SingleDeclIndex = 0;
380 return *this;
381 }
382
383 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
384 ++I;
385 DeclOrIterator = I;
386 return *this;
387 }
388
Chris Lattner9795b392010-09-04 18:12:20 +0000389 /*iterator operator++(int) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000390 iterator tmp(*this);
391 ++(*this);
392 return tmp;
Chris Lattner9795b392010-09-04 18:12:20 +0000393 }*/
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000394
395 reference operator*() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000396 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000397 return reference(ND, SingleDeclIndex);
398
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000399 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000400 }
401
402 pointer operator->() const {
403 return pointer(**this);
404 }
405
406 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000407 return X.DeclOrIterator.getOpaqueValue()
408 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000409 X.SingleDeclIndex == Y.SingleDeclIndex;
410 }
411
412 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000413 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000414 }
415};
416
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000417ResultBuilder::ShadowMapEntry::iterator
418ResultBuilder::ShadowMapEntry::begin() const {
419 if (DeclOrVector.isNull())
420 return iterator();
421
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000422 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000423 return iterator(ND, SingleDeclIndex);
424
425 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
426}
427
428ResultBuilder::ShadowMapEntry::iterator
429ResultBuilder::ShadowMapEntry::end() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000430 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000431 return iterator();
432
433 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
434}
435
Douglas Gregor2af2f672009-09-21 20:12:40 +0000436/// \brief Compute the qualification required to get from the current context
437/// (\p CurContext) to the target context (\p TargetContext).
438///
439/// \param Context the AST context in which the qualification will be used.
440///
441/// \param CurContext the context where an entity is being named, which is
442/// typically based on the current scope.
443///
444/// \param TargetContext the context in which the named entity actually
445/// resides.
446///
447/// \returns a nested name specifier that refers into the target context, or
448/// NULL if no qualification is needed.
449static NestedNameSpecifier *
450getRequiredQualification(ASTContext &Context,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000451 const DeclContext *CurContext,
452 const DeclContext *TargetContext) {
453 SmallVector<const DeclContext *, 4> TargetParents;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000454
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000455 for (const DeclContext *CommonAncestor = TargetContext;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000456 CommonAncestor && !CommonAncestor->Encloses(CurContext);
457 CommonAncestor = CommonAncestor->getLookupParent()) {
458 if (CommonAncestor->isTransparentContext() ||
459 CommonAncestor->isFunctionOrMethod())
460 continue;
461
462 TargetParents.push_back(CommonAncestor);
463 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000464
465 NestedNameSpecifier *Result = nullptr;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000466 while (!TargetParents.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000467 const DeclContext *Parent = TargetParents.pop_back_val();
468
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000469 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
Douglas Gregor68762e72010-08-23 21:17:50 +0000470 if (!Namespace->getIdentifier())
471 continue;
472
Douglas Gregor2af2f672009-09-21 20:12:40 +0000473 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregor68762e72010-08-23 21:17:50 +0000474 }
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000475 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000476 Result = NestedNameSpecifier::Create(Context, Result,
477 false,
478 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000479 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000480 return Result;
481}
482
Alp Toker034bbd52014-06-30 01:33:53 +0000483/// Determine whether \p Id is a name reserved for the implementation (C99
484/// 7.1.3, C++ [lib.global.names]).
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000485static bool isReservedName(const IdentifierInfo *Id,
486 bool doubleUnderscoreOnly = false) {
Alp Toker034bbd52014-06-30 01:33:53 +0000487 if (Id->getLength() < 2)
488 return false;
489 const char *Name = Id->getNameStart();
490 return Name[0] == '_' &&
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000491 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
492 !doubleUnderscoreOnly));
493}
494
495// Some declarations have reserved names that we don't want to ever show.
496// Filter out names reserved for the implementation if they come from a
497// system header.
498static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
499 const IdentifierInfo *Id = ND->getIdentifier();
500 if (!Id)
501 return false;
502
503 // Ignore reserved names for compiler provided decls.
504 if (isReservedName(Id) && ND->getLocation().isInvalid())
505 return true;
506
507 // For system headers ignore only double-underscore names.
508 // This allows for system headers providing private symbols with a single
509 // underscore.
510 if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
511 SemaRef.SourceMgr.isInSystemHeader(
512 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
513 return true;
514
515 return false;
Alp Toker034bbd52014-06-30 01:33:53 +0000516}
517
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000518bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000519 bool &AsNestedNameSpecifier) const {
520 AsNestedNameSpecifier = false;
521
Richard Smithf2005d32015-12-29 23:34:32 +0000522 auto *Named = ND;
Douglas Gregor7c208612010-01-14 00:20:49 +0000523 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000524
525 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000526 if (!ND->getDeclName())
527 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000528
529 // Friend declarations and declarations introduced due to friends are never
530 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000531 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000532 return false;
533
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000534 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000535 if (isa<ClassTemplateSpecializationDecl>(ND) ||
536 isa<ClassTemplatePartialSpecializationDecl>(ND))
537 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000538
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000539 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000540 if (isa<UsingDecl>(ND))
541 return false;
Argyrios Kyrtzidis5d8006d2016-07-01 01:17:02 +0000542
543 if (shouldIgnoreDueToReservedName(ND, SemaRef))
544 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000545
Douglas Gregor59cab552010-08-16 23:05:20 +0000546 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
Richard Smithf2005d32015-12-29 23:34:32 +0000547 (isa<NamespaceDecl>(ND) &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000548 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000549 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000551 AsNestedNameSpecifier = true;
552
Douglas Gregor3545ff42009-09-21 16:56:56 +0000553 // Filter out any unwanted results.
Richard Smithf2005d32015-12-29 23:34:32 +0000554 if (Filter && !(this->*Filter)(Named)) {
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000555 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000557 IsNestedNameSpecifier(ND) &&
558 (Filter != &ResultBuilder::IsMember ||
559 (isa<CXXRecordDecl>(ND) &&
560 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
561 AsNestedNameSpecifier = true;
562 return true;
563 }
564
Douglas Gregor7c208612010-01-14 00:20:49 +0000565 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000566 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000567 // ... then it must be interesting!
568 return true;
569}
570
Douglas Gregore0717ab2010-01-14 00:41:07 +0000571bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000572 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000573 // In C, there is no way to refer to a hidden name.
574 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
575 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000576 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000577 return true;
578
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000579 const DeclContext *HiddenCtx =
580 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000581
582 // There is no way to qualify a name declared in a function or method.
583 if (HiddenCtx->isFunctionOrMethod())
584 return true;
585
Sebastian Redl50c68252010-08-31 00:36:30 +0000586 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000587 return true;
588
589 // We can refer to the result with the appropriate qualification. Do it.
590 R.Hidden = true;
591 R.QualifierIsInformative = false;
592
593 if (!R.Qualifier)
594 R.Qualifier = getRequiredQualification(SemaRef.Context,
595 CurContext,
596 R.Declaration->getDeclContext());
597 return false;
598}
599
Douglas Gregor95887f92010-07-08 23:20:03 +0000600/// \brief A simplified classification of types used to determine whether two
601/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000602SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000603 switch (T->getTypeClass()) {
604 case Type::Builtin:
605 switch (cast<BuiltinType>(T)->getKind()) {
606 case BuiltinType::Void:
607 return STC_Void;
608
609 case BuiltinType::NullPtr:
610 return STC_Pointer;
611
612 case BuiltinType::Overload:
613 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000614 return STC_Other;
615
616 case BuiltinType::ObjCId:
617 case BuiltinType::ObjCClass:
618 case BuiltinType::ObjCSel:
619 return STC_ObjectiveC;
620
621 default:
622 return STC_Arithmetic;
623 }
David Blaikie8a40f702012-01-17 06:56:22 +0000624
Douglas Gregor95887f92010-07-08 23:20:03 +0000625 case Type::Complex:
626 return STC_Arithmetic;
627
628 case Type::Pointer:
629 return STC_Pointer;
630
631 case Type::BlockPointer:
632 return STC_Block;
633
634 case Type::LValueReference:
635 case Type::RValueReference:
636 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
637
638 case Type::ConstantArray:
639 case Type::IncompleteArray:
640 case Type::VariableArray:
641 case Type::DependentSizedArray:
642 return STC_Array;
643
644 case Type::DependentSizedExtVector:
645 case Type::Vector:
646 case Type::ExtVector:
647 return STC_Arithmetic;
648
649 case Type::FunctionProto:
650 case Type::FunctionNoProto:
651 return STC_Function;
652
653 case Type::Record:
654 return STC_Record;
655
656 case Type::Enum:
657 return STC_Arithmetic;
658
659 case Type::ObjCObject:
660 case Type::ObjCInterface:
661 case Type::ObjCObjectPointer:
662 return STC_ObjectiveC;
663
664 default:
665 return STC_Other;
666 }
667}
668
669/// \brief Get the type that a given expression will have if this declaration
670/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000671QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000672 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
673
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000674 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000675 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000676 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000677 return C.getObjCInterfaceType(Iface);
678
679 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000680 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000681 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000682 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000683 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000684 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000685 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000686 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000687 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000688 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000689 T = Value->getType();
690 else
691 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000692
693 // Dig through references, function pointers, and block pointers to
694 // get down to the likely type of an expression when the entity is
695 // used.
696 do {
697 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
698 T = Ref->getPointeeType();
699 continue;
700 }
701
702 if (const PointerType *Pointer = T->getAs<PointerType>()) {
703 if (Pointer->getPointeeType()->isFunctionType()) {
704 T = Pointer->getPointeeType();
705 continue;
706 }
707
708 break;
709 }
710
711 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
712 T = Block->getPointeeType();
713 continue;
714 }
715
716 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000717 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000718 continue;
719 }
720
721 break;
722 } while (true);
723
724 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000725}
726
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000727unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
728 if (!ND)
729 return CCP_Unlikely;
730
731 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000732 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
733 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000734 // _cmd is relatively rare
735 if (const ImplicitParamDecl *ImplicitParam =
736 dyn_cast<ImplicitParamDecl>(ND))
737 if (ImplicitParam->getIdentifier() &&
738 ImplicitParam->getIdentifier()->isStr("_cmd"))
739 return CCP_ObjC_cmd;
740
741 return CCP_LocalDeclaration;
742 }
Richard Smith541b38b2013-09-20 01:15:31 +0000743
744 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Ilya Biryukov4e7a6fe2017-09-22 19:07:37 +0000745 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
746 // Explicit destructor calls are very rare.
747 if (isa<CXXDestructorDecl>(ND))
748 return CCP_Unlikely;
749 // Explicit operator and conversion function calls are also very rare.
750 auto DeclNameKind = ND->getDeclName().getNameKind();
751 if (DeclNameKind == DeclarationName::CXXOperatorName ||
752 DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
753 DeclNameKind == DeclarationName::CXXConversionFunctionName)
754 return CCP_Unlikely;
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000755 return CCP_MemberDeclaration;
Ilya Biryukov4e7a6fe2017-09-22 19:07:37 +0000756 }
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000757
758 // Content-based decisions.
759 if (isa<EnumConstantDecl>(ND))
760 return CCP_Constant;
761
Douglas Gregor52e0de42013-01-31 05:03:46 +0000762 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
763 // message receiver, or parenthesized expression context. There, it's as
764 // likely that the user will want to write a type as other declarations.
765 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
766 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
767 CompletionContext.getKind()
768 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
769 CompletionContext.getKind()
770 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000771 return CCP_Type;
772
773 return CCP_Declaration;
774}
775
Douglas Gregor50832e02010-09-20 22:39:41 +0000776void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
777 // If this is an Objective-C method declaration whose selector matches our
778 // preferred selector, give it a priority boost.
779 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000780 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000781 if (PreferredSelector == Method->getSelector())
782 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000783
Douglas Gregor50832e02010-09-20 22:39:41 +0000784 // If we have a preferred type, adjust the priority for results with exactly-
785 // matching or nearly-matching types.
786 if (!PreferredType.isNull()) {
787 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
788 if (!T.isNull()) {
789 CanQualType TC = SemaRef.Context.getCanonicalType(T);
790 // Check for exactly-matching types (modulo qualifiers).
791 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
792 R.Priority /= CCF_ExactTypeMatch;
793 // Check for nearly-matching types, based on classification of each.
794 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000795 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000796 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
797 R.Priority /= CCF_SimilarTypeMatch;
798 }
799 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000800}
801
Douglas Gregor0212fd72010-09-21 16:06:22 +0000802void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000803 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000804 !CompletionContext.wantConstructorResults())
805 return;
806
807 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000808 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000809 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000810 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000811 Record = ClassTemplate->getTemplatedDecl();
812 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
813 // Skip specializations and partial specializations.
814 if (isa<ClassTemplateSpecializationDecl>(Record))
815 return;
816 } else {
817 // There are no constructors here.
818 return;
819 }
820
821 Record = Record->getDefinition();
822 if (!Record)
823 return;
824
825
826 QualType RecordTy = Context.getTypeDeclType(Record);
827 DeclarationName ConstructorName
828 = Context.DeclarationNames.getCXXConstructorName(
829 Context.getCanonicalType(RecordTy));
Richard Smithcf4bdde2015-02-21 02:45:19 +0000830 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
831 for (DeclContext::lookup_iterator I = Ctors.begin(),
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000832 E = Ctors.end();
833 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000834 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000835 R.CursorKind = getCursorKindForDecl(R.Declaration);
836 Results.push_back(R);
837 }
838}
839
Douglas Gregor7c208612010-01-14 00:20:49 +0000840void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
841 assert(!ShadowMaps.empty() && "Must enter into a results scope");
842
843 if (R.Kind != Result::RK_Declaration) {
844 // For non-declaration results, just add the result.
845 Results.push_back(R);
846 return;
847 }
848
849 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000850 if (const UsingShadowDecl *Using =
851 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000852 MaybeAddResult(Result(Using->getTargetDecl(),
853 getBasePriority(Using->getTargetDecl()),
854 R.Qualifier),
855 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000856 return;
857 }
858
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000859 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000860 unsigned IDNS = CanonDecl->getIdentifierNamespace();
861
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000862 bool AsNestedNameSpecifier = false;
863 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000864 return;
865
Douglas Gregor0212fd72010-09-21 16:06:22 +0000866 // C++ constructors are never found by name lookup.
867 if (isa<CXXConstructorDecl>(R.Declaration))
868 return;
869
Douglas Gregor3545ff42009-09-21 16:56:56 +0000870 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000871 ShadowMapEntry::iterator I, IEnd;
872 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
873 if (NamePos != SMap.end()) {
874 I = NamePos->second.begin();
875 IEnd = NamePos->second.end();
876 }
877
878 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000879 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000880 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000881 if (ND->getCanonicalDecl() == CanonDecl) {
882 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000883 Results[Index].Declaration = R.Declaration;
884
Douglas Gregor3545ff42009-09-21 16:56:56 +0000885 // We're done.
886 return;
887 }
888 }
889
890 // This is a new declaration in this scope. However, check whether this
891 // declaration name is hidden by a similarly-named declaration in an outer
892 // scope.
893 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
894 --SMEnd;
895 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000896 ShadowMapEntry::iterator I, IEnd;
897 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
898 if (NamePos != SM->end()) {
899 I = NamePos->second.begin();
900 IEnd = NamePos->second.end();
901 }
902 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000903 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000904 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000905 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
906 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000907 continue;
908
909 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000910 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000911 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000912 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000913 continue;
914
915 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000916 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000917 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000918
919 break;
920 }
921 }
922
923 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000924 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000925 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000926
Douglas Gregore412a5a2009-09-23 22:26:46 +0000927 // If the filter is for nested-name-specifiers, then this result starts a
928 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000929 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000930 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000931 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000932 } else
933 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000934
Douglas Gregor5bf52692009-09-22 23:15:58 +0000935 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000936 if (R.QualifierIsInformative && !R.Qualifier &&
937 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000938 const DeclContext *Ctx = R.Declaration->getDeclContext();
939 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000940 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
941 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000942 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000943 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
944 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000945 else
946 R.QualifierIsInformative = false;
947 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000948
Douglas Gregor3545ff42009-09-21 16:56:56 +0000949 // Insert this result into the set of results and into the current shadow
950 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000951 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000952 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000953
954 if (!AsNestedNameSpecifier)
955 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000956}
957
Douglas Gregorc580c522010-01-14 01:09:38 +0000958void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000959 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000960 if (R.Kind != Result::RK_Declaration) {
961 // For non-declaration results, just add the result.
962 Results.push_back(R);
963 return;
964 }
965
Douglas Gregorc580c522010-01-14 01:09:38 +0000966 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000967 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000968 AddResult(Result(Using->getTargetDecl(),
969 getBasePriority(Using->getTargetDecl()),
970 R.Qualifier),
971 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000972 return;
973 }
974
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000975 bool AsNestedNameSpecifier = false;
976 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000977 return;
978
Douglas Gregor0212fd72010-09-21 16:06:22 +0000979 // C++ constructors are never found by name lookup.
980 if (isa<CXXConstructorDecl>(R.Declaration))
981 return;
982
Douglas Gregorc580c522010-01-14 01:09:38 +0000983 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
984 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000985
Douglas Gregorc580c522010-01-14 01:09:38 +0000986 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000987 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000988 return;
989
990 // If the filter is for nested-name-specifiers, then this result starts a
991 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000992 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000993 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000994 R.Priority = CCP_NestedNameSpecifier;
995 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000996 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
997 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000998 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000999 R.QualifierIsInformative = true;
1000
Douglas Gregorc580c522010-01-14 01:09:38 +00001001 // If this result is supposed to have an informative qualifier, add one.
1002 if (R.QualifierIsInformative && !R.Qualifier &&
1003 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001004 const DeclContext *Ctx = R.Declaration->getDeclContext();
1005 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +00001006 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
1007 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001008 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +00001009 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +00001010 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +00001011 else
1012 R.QualifierIsInformative = false;
1013 }
1014
Douglas Gregora2db7932010-05-26 22:00:08 +00001015 // Adjust the priority if this result comes from a base class.
1016 if (InBaseClass)
1017 R.Priority += CCD_InBaseClass;
1018
Douglas Gregor50832e02010-09-20 22:39:41 +00001019 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001020
Douglas Gregor9be0ed42010-08-26 16:36:48 +00001021 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001022 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +00001023 if (Method->isInstance()) {
1024 Qualifiers MethodQuals
1025 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1026 if (ObjectTypeQualifiers == MethodQuals)
1027 R.Priority += CCD_ObjectQualifierMatch;
1028 else if (ObjectTypeQualifiers - MethodQuals) {
1029 // The method cannot be invoked, because doing so would drop
1030 // qualifiers.
1031 return;
1032 }
1033 }
1034
Douglas Gregorc580c522010-01-14 01:09:38 +00001035 // Insert this result into the set of results.
1036 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001037
1038 if (!AsNestedNameSpecifier)
1039 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001040}
1041
Douglas Gregor78a21012010-01-14 16:01:26 +00001042void ResultBuilder::AddResult(Result R) {
1043 assert(R.Kind != Result::RK_Declaration &&
1044 "Declaration results need more context");
1045 Results.push_back(R);
1046}
1047
Douglas Gregor3545ff42009-09-21 16:56:56 +00001048/// \brief Enter into a new scope.
Benjamin Kramer3204b152015-05-29 19:42:19 +00001049void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001050
1051/// \brief Exit from the current scope.
1052void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001053 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1054 EEnd = ShadowMaps.back().end();
1055 E != EEnd;
1056 ++E)
1057 E->second.Destroy();
1058
Douglas Gregor3545ff42009-09-21 16:56:56 +00001059 ShadowMaps.pop_back();
1060}
1061
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001062/// \brief Determines whether this given declaration will be found by
1063/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001064bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001065 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1066
Richard Smith541b38b2013-09-20 01:15:31 +00001067 // If name lookup finds a local extern declaration, then we are in a
1068 // context where it behaves like an ordinary name.
1069 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001070 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001071 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001073 if (isa<ObjCIvarDecl>(ND))
1074 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001075 }
1076
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001077 return ND->getIdentifierNamespace() & IDNS;
1078}
1079
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001080/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001081/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001082bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001083 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1084 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1085 return false;
1086
Richard Smith541b38b2013-09-20 01:15:31 +00001087 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001088 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001089 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001090 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001091 if (isa<ObjCIvarDecl>(ND))
1092 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001093 }
1094
Douglas Gregor70febae2010-05-28 00:49:12 +00001095 return ND->getIdentifierNamespace() & IDNS;
1096}
1097
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001098bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001099 if (!IsOrdinaryNonTypeName(ND))
1100 return 0;
1101
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001102 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001103 if (VD->getType()->isIntegralOrEnumerationType())
1104 return true;
1105
1106 return false;
1107}
1108
Douglas Gregor70febae2010-05-28 00:49:12 +00001109/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001110/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001111bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001112 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1113
Richard Smith541b38b2013-09-20 01:15:31 +00001114 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001115 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001116 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001117
1118 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001119 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1120 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001121}
1122
Douglas Gregor3545ff42009-09-21 16:56:56 +00001123/// \brief Determines whether the given declaration is suitable as the
1124/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001125bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001126 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001127 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001128 ND = ClassTemplate->getTemplatedDecl();
1129
1130 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1131}
1132
1133/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001134bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001135 return isa<EnumDecl>(ND);
1136}
1137
1138/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001139bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001140 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001141 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001142 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001143
1144 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001145 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001146 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001147 RD->getTagKind() == TTK_Struct ||
1148 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001149
1150 return false;
1151}
1152
1153/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001154bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001155 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001156 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001157 ND = ClassTemplate->getTemplatedDecl();
1158
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001159 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001160 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001161
1162 return false;
1163}
1164
1165/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001166bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001167 return isa<NamespaceDecl>(ND);
1168}
1169
1170/// \brief Determines whether the given declaration is a namespace or
1171/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001172bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001173 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001174}
1175
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001176/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001177bool ResultBuilder::IsType(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001178 ND = ND->getUnderlyingDecl();
Douglas Gregor99fa2642010-08-24 01:06:58 +00001179 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001180}
1181
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001182/// \brief Determines which members of a class should be visible via
1183/// "." or "->". Only value declarations, nested name specifiers, and
1184/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001185bool ResultBuilder::IsMember(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001186 ND = ND->getUnderlyingDecl();
Douglas Gregor70788392009-12-11 18:14:22 +00001187 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
Richard Smithf2005d32015-12-29 23:34:32 +00001188 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001189}
1190
Douglas Gregora817a192010-05-27 23:06:34 +00001191static bool isObjCReceiverType(ASTContext &C, QualType T) {
1192 T = C.getCanonicalType(T);
1193 switch (T->getTypeClass()) {
1194 case Type::ObjCObject:
1195 case Type::ObjCInterface:
1196 case Type::ObjCObjectPointer:
1197 return true;
1198
1199 case Type::Builtin:
1200 switch (cast<BuiltinType>(T)->getKind()) {
1201 case BuiltinType::ObjCId:
1202 case BuiltinType::ObjCClass:
1203 case BuiltinType::ObjCSel:
1204 return true;
1205
1206 default:
1207 break;
1208 }
1209 return false;
1210
1211 default:
1212 break;
1213 }
1214
David Blaikiebbafb8a2012-03-11 07:00:24 +00001215 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001216 return false;
1217
1218 // FIXME: We could perform more analysis here to determine whether a
1219 // particular class type has any conversions to Objective-C types. For now,
1220 // just accept all class types.
1221 return T->isDependentType() || T->isRecordType();
1222}
1223
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001224bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001225 QualType T = getDeclUsageType(SemaRef.Context, ND);
1226 if (T.isNull())
1227 return false;
1228
1229 T = SemaRef.Context.getBaseElementType(T);
1230 return isObjCReceiverType(SemaRef.Context, T);
1231}
1232
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001233bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001234 if (IsObjCMessageReceiver(ND))
1235 return true;
1236
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001237 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001238 if (!Var)
1239 return false;
1240
1241 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1242}
1243
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001244bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001245 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1246 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001247 return false;
1248
1249 QualType T = getDeclUsageType(SemaRef.Context, ND);
1250 if (T.isNull())
1251 return false;
1252
1253 T = SemaRef.Context.getBaseElementType(T);
1254 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1255 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001256 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001257}
Douglas Gregora817a192010-05-27 23:06:34 +00001258
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001259bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001260 return false;
1261}
1262
James Dennettf1243872012-06-17 05:33:25 +00001263/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001264/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001265bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001266 return isa<ObjCIvarDecl>(ND);
1267}
1268
Douglas Gregorc580c522010-01-14 01:09:38 +00001269namespace {
1270 /// \brief Visible declaration consumer that adds a code-completion result
1271 /// for each visible declaration.
1272 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1273 ResultBuilder &Results;
1274 DeclContext *CurContext;
1275
1276 public:
1277 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1278 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001279
1280 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1281 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001282 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001283 if (Ctx)
1284 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001285
1286 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1287 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001288 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001289 }
1290 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001291}
Douglas Gregorc580c522010-01-14 01:09:38 +00001292
Douglas Gregor3545ff42009-09-21 16:56:56 +00001293/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001294static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001295 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001296 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001297 Results.AddResult(Result("short", CCP_Type));
1298 Results.AddResult(Result("long", CCP_Type));
1299 Results.AddResult(Result("signed", CCP_Type));
1300 Results.AddResult(Result("unsigned", CCP_Type));
1301 Results.AddResult(Result("void", CCP_Type));
1302 Results.AddResult(Result("char", CCP_Type));
1303 Results.AddResult(Result("int", CCP_Type));
1304 Results.AddResult(Result("float", CCP_Type));
1305 Results.AddResult(Result("double", CCP_Type));
1306 Results.AddResult(Result("enum", CCP_Type));
1307 Results.AddResult(Result("struct", CCP_Type));
1308 Results.AddResult(Result("union", CCP_Type));
1309 Results.AddResult(Result("const", CCP_Type));
1310 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001311
Douglas Gregor3545ff42009-09-21 16:56:56 +00001312 if (LangOpts.C99) {
1313 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001314 Results.AddResult(Result("_Complex", CCP_Type));
1315 Results.AddResult(Result("_Imaginary", CCP_Type));
1316 Results.AddResult(Result("_Bool", CCP_Type));
1317 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001318 }
1319
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001320 CodeCompletionBuilder Builder(Results.getAllocator(),
1321 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001322 if (LangOpts.CPlusPlus) {
1323 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001324 Results.AddResult(Result("bool", CCP_Type +
1325 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001326 Results.AddResult(Result("class", CCP_Type));
1327 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001328
Douglas Gregorf4c33342010-05-28 00:22:41 +00001329 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001330 Builder.AddTypedTextChunk("typename");
1331 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1332 Builder.AddPlaceholderChunk("qualifier");
1333 Builder.AddTextChunk("::");
1334 Builder.AddPlaceholderChunk("name");
1335 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001336
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001338 Results.AddResult(Result("auto", CCP_Type));
1339 Results.AddResult(Result("char16_t", CCP_Type));
1340 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001341
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001342 Builder.AddTypedTextChunk("decltype");
1343 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1344 Builder.AddPlaceholderChunk("expression");
1345 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1346 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001347 }
Alex Lorenz46eed9d2017-02-13 23:35:59 +00001348 } else
1349 Results.AddResult(Result("__auto_type", CCP_Type));
1350
Douglas Gregor3545ff42009-09-21 16:56:56 +00001351 // GNU extensions
1352 if (LangOpts.GNUMode) {
1353 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001354 // Results.AddResult(Result("_Decimal32"));
1355 // Results.AddResult(Result("_Decimal64"));
1356 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001357
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001358 Builder.AddTypedTextChunk("typeof");
1359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1360 Builder.AddPlaceholderChunk("expression");
1361 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001362
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001363 Builder.AddTypedTextChunk("typeof");
1364 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1365 Builder.AddPlaceholderChunk("type");
1366 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1367 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001368 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001369
1370 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001371 Results.AddResult(Result("_Nonnull", CCP_Type));
1372 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1373 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001374}
1375
John McCallfaf5fb42010-08-26 23:41:50 +00001376static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001377 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001378 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001379 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001380 // Note: we don't suggest either "auto" or "register", because both
1381 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1382 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001383 Results.AddResult(Result("extern"));
1384 Results.AddResult(Result("static"));
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001385
1386 if (LangOpts.CPlusPlus11) {
1387 CodeCompletionAllocator &Allocator = Results.getAllocator();
1388 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1389
1390 // alignas
1391 Builder.AddTypedTextChunk("alignas");
1392 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1393 Builder.AddPlaceholderChunk("expression");
1394 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1395 Results.AddResult(Result(Builder.TakeString()));
1396
1397 Results.AddResult(Result("constexpr"));
1398 Results.AddResult(Result("thread_local"));
1399 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001400}
1401
John McCallfaf5fb42010-08-26 23:41:50 +00001402static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001403 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001404 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001405 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001406 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001407 case Sema::PCC_Class:
1408 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001409 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001410 Results.AddResult(Result("explicit"));
1411 Results.AddResult(Result("friend"));
1412 Results.AddResult(Result("mutable"));
1413 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001414 }
1415 // Fall through
1416
John McCallfaf5fb42010-08-26 23:41:50 +00001417 case Sema::PCC_ObjCInterface:
1418 case Sema::PCC_ObjCImplementation:
1419 case Sema::PCC_Namespace:
1420 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001421 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001422 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001423 break;
1424
John McCallfaf5fb42010-08-26 23:41:50 +00001425 case Sema::PCC_ObjCInstanceVariableList:
1426 case Sema::PCC_Expression:
1427 case Sema::PCC_Statement:
1428 case Sema::PCC_ForInit:
1429 case Sema::PCC_Condition:
1430 case Sema::PCC_RecoveryInFunction:
1431 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001432 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001433 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001434 break;
1435 }
1436}
1437
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001438static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1439static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1440static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001441 ResultBuilder &Results,
1442 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001443static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001444 ResultBuilder &Results,
1445 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001446static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001447 ResultBuilder &Results,
1448 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001449static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001450
Douglas Gregorf4c33342010-05-28 00:22:41 +00001451static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001452 CodeCompletionBuilder Builder(Results.getAllocator(),
1453 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001454 Builder.AddTypedTextChunk("typedef");
1455 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1456 Builder.AddPlaceholderChunk("type");
1457 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1458 Builder.AddPlaceholderChunk("name");
1459 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001460}
1461
John McCallfaf5fb42010-08-26 23:41:50 +00001462static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001463 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001464 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001465 case Sema::PCC_Namespace:
1466 case Sema::PCC_Class:
1467 case Sema::PCC_ObjCInstanceVariableList:
1468 case Sema::PCC_Template:
1469 case Sema::PCC_MemberTemplate:
1470 case Sema::PCC_Statement:
1471 case Sema::PCC_RecoveryInFunction:
1472 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001473 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001474 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001475 return true;
1476
John McCallfaf5fb42010-08-26 23:41:50 +00001477 case Sema::PCC_Expression:
1478 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001479 return LangOpts.CPlusPlus;
1480
1481 case Sema::PCC_ObjCInterface:
1482 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001483 return false;
1484
John McCallfaf5fb42010-08-26 23:41:50 +00001485 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001486 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001487 }
David Blaikie8a40f702012-01-17 06:56:22 +00001488
1489 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001490}
1491
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001492static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1493 const Preprocessor &PP) {
1494 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001495 Policy.AnonymousTagLocations = false;
1496 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001497 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001498 return Policy;
1499}
1500
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001501/// \brief Retrieve a printing policy suitable for code completion.
1502static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1503 return getCompletionPrintingPolicy(S.Context, S.PP);
1504}
1505
Douglas Gregore5c79d52011-10-18 21:20:17 +00001506/// \brief Retrieve the string representation of the given type as a string
1507/// that has the appropriate lifetime for code completion.
1508///
1509/// This routine provides a fast path where we provide constant strings for
1510/// common type names.
1511static const char *GetCompletionTypeString(QualType T,
1512 ASTContext &Context,
1513 const PrintingPolicy &Policy,
1514 CodeCompletionAllocator &Allocator) {
1515 if (!T.getLocalQualifiers()) {
1516 // Built-in type names are constant strings.
1517 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001518 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001519
1520 // Anonymous tag types are constant strings.
1521 if (const TagType *TagT = dyn_cast<TagType>(T))
1522 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001523 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001524 switch (Tag->getTagKind()) {
1525 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001526 case TTK_Interface: return "__interface <anonymous>";
1527 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001528 case TTK_Union: return "union <anonymous>";
1529 case TTK_Enum: return "enum <anonymous>";
1530 }
1531 }
1532 }
1533
1534 // Slow path: format the type as a string.
1535 std::string Result;
1536 T.getAsStringInternal(Result, Policy);
1537 return Allocator.CopyString(Result);
1538}
1539
Douglas Gregord8c61782012-02-15 15:34:24 +00001540/// \brief Add a completion for "this", if we're in a member function.
1541static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1542 QualType ThisTy = S.getCurrentThisType();
1543 if (ThisTy.isNull())
1544 return;
1545
1546 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001547 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001548 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1549 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1550 S.Context,
1551 Policy,
1552 Allocator));
1553 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001554 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001555}
1556
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001557static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1558 ResultBuilder &Results,
1559 const LangOptions &LangOpts) {
1560 if (!LangOpts.CPlusPlus11)
1561 return;
1562
1563 Builder.AddTypedTextChunk("static_assert");
1564 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1565 Builder.AddPlaceholderChunk("expression");
1566 Builder.AddChunk(CodeCompletionString::CK_Comma);
1567 Builder.AddPlaceholderChunk("message");
1568 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1569 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1570}
1571
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001572/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001573static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001574 Scope *S,
1575 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001576 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001577 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001578 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001579
John McCall276321a2010-08-25 06:19:51 +00001580 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001581 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001582 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001583 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001584 if (Results.includeCodePatterns()) {
1585 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001586 Builder.AddTypedTextChunk("namespace");
1587 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1588 Builder.AddPlaceholderChunk("identifier");
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("declarations");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001594 }
1595
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001596 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001597 Builder.AddTypedTextChunk("namespace");
1598 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1599 Builder.AddPlaceholderChunk("name");
1600 Builder.AddChunk(CodeCompletionString::CK_Equal);
1601 Builder.AddPlaceholderChunk("namespace");
1602 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001603
1604 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001605 Builder.AddTypedTextChunk("using");
1606 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1607 Builder.AddTextChunk("namespace");
1608 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1609 Builder.AddPlaceholderChunk("identifier");
1610 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001611
1612 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001613 Builder.AddTypedTextChunk("asm");
1614 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1615 Builder.AddPlaceholderChunk("string-literal");
1616 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1617 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001618
Douglas Gregorf4c33342010-05-28 00:22:41 +00001619 if (Results.includeCodePatterns()) {
1620 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001621 Builder.AddTypedTextChunk("template");
1622 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1623 Builder.AddPlaceholderChunk("declaration");
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001625 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001627
David Blaikiebbafb8a2012-03-11 07:00:24 +00001628 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001629 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001630
Douglas Gregorf4c33342010-05-28 00:22:41 +00001631 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632 // Fall through
1633
John McCallfaf5fb42010-08-26 23:41:50 +00001634 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001635 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001636 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001637 Builder.AddTypedTextChunk("using");
1638 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1639 Builder.AddPlaceholderChunk("qualifier");
1640 Builder.AddTextChunk("::");
1641 Builder.AddPlaceholderChunk("name");
1642 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001643
Douglas Gregorf4c33342010-05-28 00:22:41 +00001644 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001645 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001646 Builder.AddTypedTextChunk("using");
1647 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1648 Builder.AddTextChunk("typename");
1649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1650 Builder.AddPlaceholderChunk("qualifier");
1651 Builder.AddTextChunk("::");
1652 Builder.AddPlaceholderChunk("name");
1653 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001654 }
1655
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001656 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1657
John McCallfaf5fb42010-08-26 23:41:50 +00001658 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001659 AddTypedefResult(Results);
1660
Erik Verbruggen6524c052017-10-24 13:46:58 +00001661 bool IsNotInheritanceScope =
1662 !(S->getFlags() & Scope::ClassInheritanceScope);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001663 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001664 Builder.AddTypedTextChunk("public");
Erik Verbruggen6524c052017-10-24 13:46:58 +00001665 if (IsNotInheritanceScope && Results.includeCodePatterns())
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001666 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001667 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001668
1669 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001670 Builder.AddTypedTextChunk("protected");
Erik Verbruggen6524c052017-10-24 13:46:58 +00001671 if (IsNotInheritanceScope && Results.includeCodePatterns())
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001672 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674
1675 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001676 Builder.AddTypedTextChunk("private");
Erik Verbruggen6524c052017-10-24 13:46:58 +00001677 if (IsNotInheritanceScope && Results.includeCodePatterns())
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001678 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001679 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001680 }
1681 }
1682 // Fall through
1683
John McCallfaf5fb42010-08-26 23:41:50 +00001684 case Sema::PCC_Template:
1685 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001686 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001687 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001688 Builder.AddTypedTextChunk("template");
1689 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1690 Builder.AddPlaceholderChunk("parameters");
1691 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1692 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001693 }
1694
David Blaikiebbafb8a2012-03-11 07:00:24 +00001695 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1696 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001697 break;
1698
John McCallfaf5fb42010-08-26 23:41:50 +00001699 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1701 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1702 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001703 break;
1704
John McCallfaf5fb42010-08-26 23:41:50 +00001705 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1707 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1708 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001709 break;
1710
John McCallfaf5fb42010-08-26 23:41:50 +00001711 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001712 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001713 break;
1714
John McCallfaf5fb42010-08-26 23:41:50 +00001715 case Sema::PCC_RecoveryInFunction:
1716 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001717 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001718
David Blaikiebbafb8a2012-03-11 07:00:24 +00001719 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1720 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001721 Builder.AddTypedTextChunk("try");
1722 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1723 Builder.AddPlaceholderChunk("statements");
1724 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1725 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1726 Builder.AddTextChunk("catch");
1727 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1728 Builder.AddPlaceholderChunk("declaration");
1729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1730 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1731 Builder.AddPlaceholderChunk("statements");
1732 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1733 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1734 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001735 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001736 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001737 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001738
Douglas Gregorf64acca2010-05-25 21:41:55 +00001739 if (Results.includeCodePatterns()) {
1740 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("if");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001744 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001745 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001746 Builder.AddPlaceholderChunk("expression");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1749 Builder.AddPlaceholderChunk("statements");
1750 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1751 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1752 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001753
Douglas Gregorf64acca2010-05-25 21:41:55 +00001754 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001755 Builder.AddTypedTextChunk("switch");
1756 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001757 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001758 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001759 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001760 Builder.AddPlaceholderChunk("expression");
1761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1762 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1763 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1764 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1765 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001766 }
1767
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001769 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001770 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001771 Builder.AddTypedTextChunk("case");
1772 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1773 Builder.AddPlaceholderChunk("expression");
1774 Builder.AddChunk(CodeCompletionString::CK_Colon);
1775 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001776
1777 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001778 Builder.AddTypedTextChunk("default");
1779 Builder.AddChunk(CodeCompletionString::CK_Colon);
1780 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001781 }
1782
Douglas Gregorf64acca2010-05-25 21:41:55 +00001783 if (Results.includeCodePatterns()) {
1784 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001785 Builder.AddTypedTextChunk("while");
1786 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001787 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001788 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001789 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001790 Builder.AddPlaceholderChunk("expression");
1791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1792 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1793 Builder.AddPlaceholderChunk("statements");
1794 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1795 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1796 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001797
1798 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001799 Builder.AddTypedTextChunk("do");
1800 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1801 Builder.AddPlaceholderChunk("statements");
1802 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1803 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1804 Builder.AddTextChunk("while");
1805 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1806 Builder.AddPlaceholderChunk("expression");
1807 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1808 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001809
Douglas Gregorf64acca2010-05-25 21:41:55 +00001810 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001811 Builder.AddTypedTextChunk("for");
1812 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001813 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001814 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001815 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001816 Builder.AddPlaceholderChunk("init-expression");
1817 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1818 Builder.AddPlaceholderChunk("condition");
1819 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1820 Builder.AddPlaceholderChunk("inc-expression");
1821 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1822 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1823 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1824 Builder.AddPlaceholderChunk("statements");
1825 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1826 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1827 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001828 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001829
1830 if (S->getContinueParent()) {
1831 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001832 Builder.AddTypedTextChunk("continue");
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001834 }
1835
1836 if (S->getBreakParent()) {
1837 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001838 Builder.AddTypedTextChunk("break");
1839 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001840 }
1841
1842 // "return expression ;" or "return ;", depending on whether we
1843 // know the function is void or not.
1844 bool isVoid = false;
1845 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001846 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001847 else if (ObjCMethodDecl *Method
1848 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001849 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001850 else if (SemaRef.getCurBlock() &&
1851 !SemaRef.getCurBlock()->ReturnType.isNull())
1852 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001853 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001854 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001855 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1856 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001857 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001858 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001859
Douglas Gregorf4c33342010-05-28 00:22:41 +00001860 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001861 Builder.AddTypedTextChunk("goto");
1862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1863 Builder.AddPlaceholderChunk("label");
1864 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001865
Douglas Gregorf4c33342010-05-28 00:22:41 +00001866 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001867 Builder.AddTypedTextChunk("using");
1868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1869 Builder.AddTextChunk("namespace");
1870 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1871 Builder.AddPlaceholderChunk("identifier");
1872 Results.AddResult(Result(Builder.TakeString()));
Alex Lorenz8f4d3992017-02-13 23:19:40 +00001873
1874 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001875 }
Galina Kistanovabe3ba9da2017-06-07 06:31:55 +00001876 LLVM_FALLTHROUGH;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001877
1878 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001879 case Sema::PCC_ForInit:
1880 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001881 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001882 // Fall through: conditions and statements can have expressions.
Galina Kistanova33399112017-06-03 06:35:06 +00001883 LLVM_FALLTHROUGH;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001884
Douglas Gregor5e35d592010-09-14 23:59:36 +00001885 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001886 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001887 CCC == Sema::PCC_ParenthesizedExpression) {
1888 // (__bridge <type>)<expression>
1889 Builder.AddTypedTextChunk("__bridge");
1890 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1891 Builder.AddPlaceholderChunk("type");
1892 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1893 Builder.AddPlaceholderChunk("expression");
1894 Results.AddResult(Result(Builder.TakeString()));
1895
1896 // (__bridge_transfer <Objective-C type>)<expression>
1897 Builder.AddTypedTextChunk("__bridge_transfer");
1898 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1899 Builder.AddPlaceholderChunk("Objective-C type");
1900 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1901 Builder.AddPlaceholderChunk("expression");
1902 Results.AddResult(Result(Builder.TakeString()));
1903
1904 // (__bridge_retained <CF type>)<expression>
1905 Builder.AddTypedTextChunk("__bridge_retained");
1906 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1907 Builder.AddPlaceholderChunk("CF type");
1908 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1909 Builder.AddPlaceholderChunk("expression");
1910 Results.AddResult(Result(Builder.TakeString()));
1911 }
1912 // Fall through
Galina Kistanova33399112017-06-03 06:35:06 +00001913 LLVM_FALLTHROUGH;
John McCall31168b02011-06-15 23:02:42 +00001914
John McCallfaf5fb42010-08-26 23:41:50 +00001915 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001916 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001917 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001918 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001919
Douglas Gregore5c79d52011-10-18 21:20:17 +00001920 // true
1921 Builder.AddResultTypeChunk("bool");
1922 Builder.AddTypedTextChunk("true");
1923 Results.AddResult(Result(Builder.TakeString()));
1924
1925 // false
1926 Builder.AddResultTypeChunk("bool");
1927 Builder.AddTypedTextChunk("false");
1928 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001929
David Blaikiebbafb8a2012-03-11 07:00:24 +00001930 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001931 // dynamic_cast < type-id > ( expression )
1932 Builder.AddTypedTextChunk("dynamic_cast");
1933 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1934 Builder.AddPlaceholderChunk("type");
1935 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1936 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1937 Builder.AddPlaceholderChunk("expression");
1938 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1939 Results.AddResult(Result(Builder.TakeString()));
1940 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001941
1942 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001943 Builder.AddTypedTextChunk("static_cast");
1944 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1945 Builder.AddPlaceholderChunk("type");
1946 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1948 Builder.AddPlaceholderChunk("expression");
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 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001953 Builder.AddTypedTextChunk("reinterpret_cast");
1954 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1955 Builder.AddPlaceholderChunk("type");
1956 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1958 Builder.AddPlaceholderChunk("expression");
1959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1960 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001961
Douglas Gregorf4c33342010-05-28 00:22:41 +00001962 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001963 Builder.AddTypedTextChunk("const_cast");
1964 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1965 Builder.AddPlaceholderChunk("type");
1966 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1967 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1968 Builder.AddPlaceholderChunk("expression");
1969 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1970 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001971
David Blaikiebbafb8a2012-03-11 07:00:24 +00001972 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001973 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001974 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001975 Builder.AddTypedTextChunk("typeid");
1976 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1977 Builder.AddPlaceholderChunk("expression-or-type");
1978 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1979 Results.AddResult(Result(Builder.TakeString()));
1980 }
1981
Douglas Gregorf4c33342010-05-28 00:22:41 +00001982 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001983 Builder.AddTypedTextChunk("new");
1984 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1985 Builder.AddPlaceholderChunk("type");
1986 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1987 Builder.AddPlaceholderChunk("expressions");
1988 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1989 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001990
Douglas Gregorf4c33342010-05-28 00:22:41 +00001991 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001992 Builder.AddTypedTextChunk("new");
1993 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994 Builder.AddPlaceholderChunk("type");
1995 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1996 Builder.AddPlaceholderChunk("size");
1997 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1998 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1999 Builder.AddPlaceholderChunk("expressions");
2000 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2001 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002002
Douglas Gregorf4c33342010-05-28 00:22:41 +00002003 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002004 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002005 Builder.AddTypedTextChunk("delete");
2006 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2007 Builder.AddPlaceholderChunk("expression");
2008 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002009
Douglas Gregorf4c33342010-05-28 00:22:41 +00002010 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002011 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002012 Builder.AddTypedTextChunk("delete");
2013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2014 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2015 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2016 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2017 Builder.AddPlaceholderChunk("expression");
2018 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002019
David Blaikiebbafb8a2012-03-11 07:00:24 +00002020 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00002021 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002022 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00002023 Builder.AddTypedTextChunk("throw");
2024 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2025 Builder.AddPlaceholderChunk("expression");
2026 Results.AddResult(Result(Builder.TakeString()));
2027 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00002028
Douglas Gregora2db7932010-05-26 22:00:08 +00002029 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00002030
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002031 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00002032 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00002033 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002034 Builder.AddTypedTextChunk("nullptr");
2035 Results.AddResult(Result(Builder.TakeString()));
2036
2037 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00002038 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002039 Builder.AddTypedTextChunk("alignof");
2040 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2041 Builder.AddPlaceholderChunk("type");
2042 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2043 Results.AddResult(Result(Builder.TakeString()));
2044
2045 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00002046 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002047 Builder.AddTypedTextChunk("noexcept");
2048 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2049 Builder.AddPlaceholderChunk("expression");
2050 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2051 Results.AddResult(Result(Builder.TakeString()));
2052
2053 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002054 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00002055 Builder.AddTypedTextChunk("sizeof...");
2056 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2057 Builder.AddPlaceholderChunk("parameter-pack");
2058 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2059 Results.AddResult(Result(Builder.TakeString()));
2060 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002061 }
2062
David Blaikiebbafb8a2012-03-11 07:00:24 +00002063 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002064 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00002065 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2066 // The interface can be NULL.
2067 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002068 if (ID->getSuperClass()) {
2069 std::string SuperType;
2070 SuperType = ID->getSuperClass()->getNameAsString();
2071 if (Method->isInstanceMethod())
2072 SuperType += " *";
2073
2074 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2075 Builder.AddTypedTextChunk("super");
2076 Results.AddResult(Result(Builder.TakeString()));
2077 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002078 }
2079
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002080 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002081 }
2082
Jordan Rose58d54722012-06-30 21:33:57 +00002083 if (SemaRef.getLangOpts().C11) {
2084 // _Alignof
2085 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002086 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002087 Builder.AddTypedTextChunk("alignof");
2088 else
2089 Builder.AddTypedTextChunk("_Alignof");
2090 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2091 Builder.AddPlaceholderChunk("type");
2092 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2093 Results.AddResult(Result(Builder.TakeString()));
2094 }
2095
Douglas Gregorf4c33342010-05-28 00:22:41 +00002096 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002097 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002098 Builder.AddTypedTextChunk("sizeof");
2099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2100 Builder.AddPlaceholderChunk("expression-or-type");
2101 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2102 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002103 break;
2104 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002105
John McCallfaf5fb42010-08-26 23:41:50 +00002106 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002107 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002108 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002109 }
2110
David Blaikiebbafb8a2012-03-11 07:00:24 +00002111 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2112 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002113
David Blaikiebbafb8a2012-03-11 07:00:24 +00002114 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002115 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002116}
2117
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002118/// \brief If the given declaration has an associated type, add it as a result
2119/// type chunk.
2120static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002121 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002122 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002123 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002124 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002125 if (!ND)
2126 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002127
2128 // Skip constructors and conversion functions, which have their return types
2129 // built into their names.
2130 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2131 return;
2132
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002133 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002134 QualType T;
2135 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002136 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002137 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2138 if (!BaseType.isNull())
2139 T = Method->getSendResultType(BaseType);
2140 else
2141 T = Method->getReturnType();
2142 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002143 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2144 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2145 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002146 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2147 if (!BaseType.isNull())
2148 T = Ivar->getUsageType(BaseType);
2149 else
2150 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002151 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002152 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002153 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2154 if (!BaseType.isNull())
2155 T = Property->getUsageType(BaseType);
2156 else
2157 T = Property->getType();
2158 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002159
2160 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2161 return;
2162
Douglas Gregor75acd922011-09-27 23:30:47 +00002163 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002164 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002165}
2166
Richard Smith20e883e2015-04-29 23:20:19 +00002167static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002168 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002169 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002170 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2171 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002172 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002173 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002174 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002175 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002176 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002177 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002178 }
2179}
2180
Douglas Gregor86b42682015-06-19 18:27:52 +00002181static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2182 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002183 std::string Result;
2184 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002185 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002186 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002187 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002188 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002189 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002190 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002191 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002192 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002193 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002194 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002195 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002196 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2197 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2198 switch (*nullability) {
2199 case NullabilityKind::NonNull:
2200 Result += "nonnull ";
2201 break;
2202
2203 case NullabilityKind::Nullable:
2204 Result += "nullable ";
2205 break;
2206
2207 case NullabilityKind::Unspecified:
2208 Result += "null_unspecified ";
2209 break;
2210 }
2211 }
2212 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002213 return Result;
2214}
2215
Alex Lorenza1951202016-10-18 10:35:27 +00002216/// \brief Tries to find the most appropriate type location for an Objective-C
2217/// block placeholder.
2218///
2219/// This function ignores things like typedefs and qualifiers in order to
2220/// present the most relevant and accurate block placeholders in code completion
2221/// results.
2222static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2223 FunctionTypeLoc &Block,
2224 FunctionProtoTypeLoc &BlockProto,
2225 bool SuppressBlock = false) {
2226 if (!TSInfo)
2227 return;
2228 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2229 while (true) {
2230 // Look through typedefs.
2231 if (!SuppressBlock) {
2232 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2233 if (TypeSourceInfo *InnerTSInfo =
2234 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2235 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2236 continue;
2237 }
2238 }
2239
2240 // Look through qualified types
2241 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2242 TL = QualifiedTL.getUnqualifiedLoc();
2243 continue;
2244 }
2245
2246 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2247 TL = AttrTL.getModifiedLoc();
2248 continue;
2249 }
2250 }
2251
2252 // Try to get the function prototype behind the block pointer type,
2253 // then we're done.
2254 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2255 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2256 Block = TL.getAs<FunctionTypeLoc>();
2257 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2258 }
2259 break;
2260 }
2261}
2262
Alex Lorenz920ae142016-10-18 10:38:58 +00002263static std::string
2264formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2265 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002266 bool SuppressBlockName = false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002267 bool SuppressBlock = false,
2268 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2269
Richard Smith20e883e2015-04-29 23:20:19 +00002270static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002271 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002272 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002273 bool SuppressBlock = false,
2274 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002275 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2276 if (Param->getType()->isDependentType() ||
2277 !Param->getType()->isBlockPointerType()) {
2278 // The argument for a dependent or non-block parameter is a placeholder
2279 // containing that parameter's type.
2280 std::string Result;
2281
Douglas Gregor981a0c42010-08-29 19:47:46 +00002282 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002283 Result = Param->getIdentifier()->getName();
2284
Douglas Gregor86b42682015-06-19 18:27:52 +00002285 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002286 if (ObjCSubsts)
2287 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2288 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002289 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002290 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2291 Type);
2292 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002293 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002294 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002295 } else {
2296 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002297 }
2298 return Result;
2299 }
Alex Lorenza1951202016-10-18 10:35:27 +00002300
Douglas Gregore90dd002010-08-24 16:15:59 +00002301 // The argument for a block pointer parameter is a block literal with
2302 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002303 FunctionTypeLoc Block;
2304 FunctionProtoTypeLoc BlockProto;
Alex Lorenza1951202016-10-18 10:35:27 +00002305 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2306 SuppressBlock);
Alex Lorenz6bf4a582017-03-13 15:43:42 +00002307 // Try to retrieve the block type information from the property if this is a
2308 // parameter in a setter.
2309 if (!Block && ObjCMethodParam &&
2310 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2311 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2312 ->findPropertyDecl(/*CheckOverrides=*/false))
2313 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2314 SuppressBlock);
2315 }
Douglas Gregore90dd002010-08-24 16:15:59 +00002316
2317 if (!Block) {
2318 // We were unable to find a FunctionProtoTypeLoc with parameter names
2319 // for the block; just use the parameter type as a placeholder.
2320 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002321 if (!ObjCMethodParam && Param->getIdentifier())
2322 Result = Param->getIdentifier()->getName();
2323
Douglas Gregor86b42682015-06-19 18:27:52 +00002324 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002325
2326 if (ObjCMethodParam) {
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002327 Result = Type.getAsString(Policy);
2328 std::string Quals =
2329 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2330 if (!Quals.empty())
2331 Result = "(" + Quals + " " + Result + ")";
2332 if (Result.back() != ')')
2333 Result += " ";
Douglas Gregore90dd002010-08-24 16:15:59 +00002334 if (Param->getIdentifier())
2335 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002336 } else {
2337 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002338 }
2339
2340 return Result;
2341 }
Alex Lorenz01bcfc12016-11-23 16:28:34 +00002342
Douglas Gregore90dd002010-08-24 16:15:59 +00002343 // We have the function prototype behind the block pointer type, as it was
2344 // written in the source.
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002345 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2346 /*SuppressBlockName=*/false, SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002347 ObjCSubsts);
2348}
2349
2350/// \brief Returns a placeholder string that corresponds to an Objective-C block
2351/// declaration.
2352///
2353/// \param BlockDecl A declaration with an Objective-C block type.
2354///
2355/// \param Block The most relevant type location for that block type.
2356///
2357/// \param SuppressBlockName Determines wether or not the name of the block
2358/// declaration is included in the resulting string.
2359static std::string
2360formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2361 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002362 bool SuppressBlockName, bool SuppressBlock,
Alex Lorenz920ae142016-10-18 10:38:58 +00002363 Optional<ArrayRef<QualType>> ObjCSubsts) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002364 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002365 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002366 if (ObjCSubsts)
Alex Lorenz920ae142016-10-18 10:38:58 +00002367 ResultType =
2368 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2369 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002370 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002371 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002372
2373 // Format the parameter list.
2374 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002375 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002376 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002377 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002378 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002379 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002380 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002381 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002382 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002383 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002384 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002385 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002386 /*SuppressName=*/false,
Alex Lorenz920ae142016-10-18 10:38:58 +00002387 /*SuppressBlock=*/true, ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002388
David Blaikie6adc78e2013-02-18 22:06:02 +00002389 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002390 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002391 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002392 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002393 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002394
Douglas Gregord793e7c2011-10-18 04:23:19 +00002395 if (SuppressBlock) {
2396 // Format as a parameter.
2397 Result = Result + " (^";
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002398 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002399 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002400 Result += ")";
2401 Result += Params;
2402 } else {
2403 // Format as a block literal argument.
2404 Result = '^' + Result;
2405 Result += Params;
Alex Lorenz920ae142016-10-18 10:38:58 +00002406
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00002407 if (!SuppressBlockName && BlockDecl->getIdentifier())
Alex Lorenz920ae142016-10-18 10:38:58 +00002408 Result += BlockDecl->getIdentifier()->getName();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002409 }
Alex Lorenz920ae142016-10-18 10:38:58 +00002410
Douglas Gregore90dd002010-08-24 16:15:59 +00002411 return Result;
2412}
2413
Erik Verbruggen11338c52017-07-19 10:45:40 +00002414static std::string GetDefaultValueString(const ParmVarDecl *Param,
2415 const SourceManager &SM,
2416 const LangOptions &LangOpts) {
Ilya Biryukovb6d1ec82017-07-21 09:24:00 +00002417 const SourceRange SrcRange = Param->getDefaultArgRange();
Erik Verbruggen11338c52017-07-19 10:45:40 +00002418 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2419 bool Invalid = CharSrcRange.isInvalid();
2420 if (Invalid)
2421 return "";
2422 StringRef srcText = Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2423 if (Invalid)
2424 return "";
2425
2426 if (srcText.empty() || srcText == "=") {
2427 // Lexer can't determine the value.
2428 // This happens if the code is incorrect (for example class is forward declared).
2429 return "";
2430 }
Erik Verbruggen797980e2017-07-19 11:15:36 +00002431 std::string DefValue(srcText.str());
Erik Verbruggen11338c52017-07-19 10:45:40 +00002432 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2433 // this value always has (or always does not have) '=' in front of it
2434 if (DefValue.at(0) != '=') {
2435 // If we don't have '=' in front of value.
2436 // Lexer returns built-in types values without '=' and user-defined types values with it.
2437 return " = " + DefValue;
2438 }
2439 return " " + DefValue;
2440}
2441
Douglas Gregor3545ff42009-09-21 16:56:56 +00002442/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002443static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002444 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002445 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002446 CodeCompletionBuilder &Result,
2447 unsigned Start = 0,
2448 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002449 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002450
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002451 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002452 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002453
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002454 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002455 // When we see an optional default argument, put that argument and
2456 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002457 CodeCompletionBuilder Opt(Result.getAllocator(),
2458 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002459 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002460 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002461 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002462 Result.AddOptionalChunk(Opt.TakeString());
2463 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002464 }
2465
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002466 if (FirstParameter)
2467 FirstParameter = false;
2468 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002469 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002470
2471 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002472
2473 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002474 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
Erik Verbruggen11338c52017-07-19 10:45:40 +00002475 if (Param->hasDefaultArg())
2476 PlaceholderStr += GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
Richard Smith20e883e2015-04-29 23:20:19 +00002477
Douglas Gregor400f5972010-08-31 05:13:43 +00002478 if (Function->isVariadic() && P == N - 1)
2479 PlaceholderStr += ", ...";
2480
Douglas Gregor3545ff42009-09-21 16:56:56 +00002481 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002482 Result.AddPlaceholderChunk(
2483 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002484 }
Douglas Gregorba449032009-09-22 21:42:17 +00002485
2486 if (const FunctionProtoType *Proto
2487 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002488 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002489 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002490 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002491
Richard Smith20e883e2015-04-29 23:20:19 +00002492 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002493 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002494}
2495
2496/// \brief Add template parameter chunks to the given code completion string.
2497static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002498 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002499 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002500 CodeCompletionBuilder &Result,
2501 unsigned MaxParameters = 0,
2502 unsigned Start = 0,
2503 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002504 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002505
2506 // Prefer to take the template parameter names from the first declaration of
2507 // the template.
2508 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2509
Douglas Gregor3545ff42009-09-21 16:56:56 +00002510 TemplateParameterList *Params = Template->getTemplateParameters();
2511 TemplateParameterList::iterator PEnd = Params->end();
2512 if (MaxParameters)
2513 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002514 for (TemplateParameterList::iterator P = Params->begin() + Start;
2515 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002516 bool HasDefaultArg = false;
2517 std::string PlaceholderStr;
2518 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2519 if (TTP->wasDeclaredWithTypename())
2520 PlaceholderStr = "typename";
2521 else
2522 PlaceholderStr = "class";
2523
2524 if (TTP->getIdentifier()) {
2525 PlaceholderStr += ' ';
2526 PlaceholderStr += TTP->getIdentifier()->getName();
2527 }
2528
2529 HasDefaultArg = TTP->hasDefaultArgument();
2530 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002531 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002532 if (NTTP->getIdentifier())
2533 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002534 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002535 HasDefaultArg = NTTP->hasDefaultArgument();
2536 } else {
2537 assert(isa<TemplateTemplateParmDecl>(*P));
2538 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2539
2540 // Since putting the template argument list into the placeholder would
2541 // be very, very long, we just use an abbreviation.
2542 PlaceholderStr = "template<...> class";
2543 if (TTP->getIdentifier()) {
2544 PlaceholderStr += ' ';
2545 PlaceholderStr += TTP->getIdentifier()->getName();
2546 }
2547
2548 HasDefaultArg = TTP->hasDefaultArgument();
2549 }
2550
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002551 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002552 // When we see an optional default argument, put that argument and
2553 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002554 CodeCompletionBuilder Opt(Result.getAllocator(),
2555 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002556 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002557 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002558 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002559 P - Params->begin(), true);
2560 Result.AddOptionalChunk(Opt.TakeString());
2561 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002562 }
2563
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002564 InDefaultArg = false;
2565
Douglas Gregor3545ff42009-09-21 16:56:56 +00002566 if (FirstParameter)
2567 FirstParameter = false;
2568 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002569 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002570
2571 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002572 Result.AddPlaceholderChunk(
2573 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002574 }
2575}
2576
Douglas Gregorf2510672009-09-21 19:57:38 +00002577/// \brief Add a qualifier to the given code-completion string, if the
2578/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002579static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002580AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002581 NestedNameSpecifier *Qualifier,
2582 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002583 ASTContext &Context,
2584 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002585 if (!Qualifier)
2586 return;
2587
2588 std::string PrintedNNS;
2589 {
2590 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002591 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002592 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002593 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002594 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002595 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002596 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002597}
2598
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002599static void
2600AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002601 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002602 const FunctionProtoType *Proto
2603 = Function->getType()->getAs<FunctionProtoType>();
2604 if (!Proto || !Proto->getTypeQuals())
2605 return;
2606
Douglas Gregor304f9b02011-02-01 21:15:40 +00002607 // FIXME: Add ref-qualifier!
2608
2609 // Handle single qualifiers without copying
2610 if (Proto->getTypeQuals() == Qualifiers::Const) {
2611 Result.AddInformativeChunk(" const");
2612 return;
2613 }
2614
2615 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2616 Result.AddInformativeChunk(" volatile");
2617 return;
2618 }
2619
2620 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2621 Result.AddInformativeChunk(" restrict");
2622 return;
2623 }
2624
2625 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002626 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002627 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002628 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002629 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002630 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002631 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002632 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002633 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002634}
2635
Douglas Gregor0212fd72010-09-21 16:06:22 +00002636/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002637static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002638 const NamedDecl *ND,
2639 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002640 DeclarationName Name = ND->getDeclName();
2641 if (!Name)
2642 return;
2643
2644 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002645 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002646 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002647 switch (Name.getCXXOverloadedOperator()) {
2648 case OO_None:
2649 case OO_Conditional:
2650 case NUM_OVERLOADED_OPERATORS:
2651 OperatorName = "operator";
2652 break;
2653
2654#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2655 case OO_##Name: OperatorName = "operator" Spelling; break;
2656#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2657#include "clang/Basic/OperatorKinds.def"
2658
2659 case OO_New: OperatorName = "operator new"; break;
2660 case OO_Delete: OperatorName = "operator delete"; break;
2661 case OO_Array_New: OperatorName = "operator new[]"; break;
2662 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2663 case OO_Call: OperatorName = "operator()"; break;
2664 case OO_Subscript: OperatorName = "operator[]"; break;
2665 }
2666 Result.AddTypedTextChunk(OperatorName);
2667 break;
2668 }
2669
Douglas Gregor0212fd72010-09-21 16:06:22 +00002670 case DeclarationName::Identifier:
2671 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002672 case DeclarationName::CXXDestructorName:
2673 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002674 Result.AddTypedTextChunk(
2675 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002676 break;
2677
Richard Smith35845152017-02-07 01:37:30 +00002678 case DeclarationName::CXXDeductionGuideName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002679 case DeclarationName::CXXUsingDirective:
2680 case DeclarationName::ObjCZeroArgSelector:
2681 case DeclarationName::ObjCOneArgSelector:
2682 case DeclarationName::ObjCMultiArgSelector:
2683 break;
2684
2685 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002686 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002687 QualType Ty = Name.getCXXNameType();
2688 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2689 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2690 else if (const InjectedClassNameType *InjectedTy
2691 = Ty->getAs<InjectedClassNameType>())
2692 Record = InjectedTy->getDecl();
2693 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002694 Result.AddTypedTextChunk(
2695 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002696 break;
2697 }
2698
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002699 Result.AddTypedTextChunk(
2700 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002701 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002702 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002703 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002704 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002705 }
2706 break;
2707 }
2708 }
2709}
2710
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002711CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002712 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002713 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002714 CodeCompletionTUInfo &CCTUInfo,
2715 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002716 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2717 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002718}
2719
Douglas Gregor3545ff42009-09-21 16:56:56 +00002720/// \brief If possible, create a new code completion string for the given
2721/// result.
2722///
2723/// \returns Either a new, heap-allocated code completion string describing
2724/// how to use this result, or NULL to indicate that the string or name of the
2725/// result is all that is needed.
2726CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002727CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2728 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002729 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002730 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002731 CodeCompletionTUInfo &CCTUInfo,
2732 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002733 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002734
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002735 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002736 if (Kind == RK_Pattern) {
2737 Pattern->Priority = Priority;
2738 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002739
2740 if (Declaration) {
2741 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002742 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002743 // Provide code completion comment for self.GetterName where
2744 // GetterName is the getter method for a property with name
2745 // different from the property name (declared via a property
2746 // getter attribute.
2747 const NamedDecl *ND = Declaration;
2748 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2749 if (M->isPropertyAccessor())
2750 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2751 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002752 PDecl->getIdentifier() != M->getIdentifier()) {
2753 if (const RawComment *RC =
2754 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002755 Result.addBriefComment(RC->getBriefText(Ctx));
2756 Pattern->BriefComment = Result.getBriefComment();
2757 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002758 else if (const RawComment *RC =
2759 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2760 Result.addBriefComment(RC->getBriefText(Ctx));
2761 Pattern->BriefComment = Result.getBriefComment();
2762 }
2763 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002764 }
2765
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002766 return Pattern;
2767 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002768
Douglas Gregorf09935f2009-12-01 05:55:20 +00002769 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002770 Result.AddTypedTextChunk(Keyword);
2771 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002772 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002773
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002774 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002775 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002776 Result.AddTypedTextChunk(
2777 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002778
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002779 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002780 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002781
2782 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002783 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Faisal Valiac506d72017-07-17 17:18:43 +00002784 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002785
2786 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2787 if (MI->isC99Varargs()) {
2788 --AEnd;
2789
2790 if (A == AEnd) {
2791 Result.AddPlaceholderChunk("...");
2792 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002793 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002794
Faisal Valiac506d72017-07-17 17:18:43 +00002795 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
2796 if (A != MI->param_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002797 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002798
2799 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002800 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002801 if (MI->isC99Varargs())
2802 Arg += ", ...";
2803 else
2804 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002805 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002806 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002807 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002808
2809 // Non-variadic macros are simple.
2810 Result.AddPlaceholderChunk(
2811 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002812 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002813 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002814 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002815 }
2816
Douglas Gregorf64acca2010-05-25 21:41:55 +00002817 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002818 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002819 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002820
2821 if (IncludeBriefComments) {
2822 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002823 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002824 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002825 }
2826 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2827 if (OMD->isPropertyAccessor())
2828 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2829 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2830 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002831 }
2832
Douglas Gregor9eb77012009-11-07 00:00:49 +00002833 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002834 Result.AddTypedTextChunk(
2835 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002836 Result.AddTextChunk("::");
2837 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002838 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002839
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002840 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2841 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002842
Douglas Gregorc3425b12015-07-07 06:20:19 +00002843 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002844
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002845 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002846 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002847 Ctx, Policy);
2848 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002849 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002850 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002851 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002852 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002853 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002854 }
2855
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002856 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002857 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002858 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002859 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002860 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002861
Douglas Gregor3545ff42009-09-21 16:56:56 +00002862 // Figure out which template parameters are deduced (or have default
2863 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002864 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002865 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002866 unsigned LastDeducibleArgument;
2867 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2868 --LastDeducibleArgument) {
2869 if (!Deduced[LastDeducibleArgument - 1]) {
2870 // C++0x: Figure out if the template argument has a default. If so,
2871 // the user doesn't need to type this argument.
2872 // FIXME: We need to abstract template parameters better!
2873 bool HasDefaultArg = false;
2874 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002875 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002876 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2877 HasDefaultArg = TTP->hasDefaultArgument();
2878 else if (NonTypeTemplateParmDecl *NTTP
2879 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2880 HasDefaultArg = NTTP->hasDefaultArgument();
2881 else {
2882 assert(isa<TemplateTemplateParmDecl>(Param));
2883 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002884 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002885 }
2886
2887 if (!HasDefaultArg)
2888 break;
2889 }
2890 }
2891
2892 if (LastDeducibleArgument) {
2893 // Some of the function template arguments cannot be deduced from a
2894 // function call, so we introduce an explicit template argument list
2895 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002896 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002897 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002898 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002899 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002900 }
2901
2902 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002903 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002904 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002905 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002906 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002907 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002908 }
2909
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002910 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002911 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002912 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002913 Result.AddTypedTextChunk(
2914 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002915 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002916 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002917 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002918 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002919 }
2920
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002921 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002922 Selector Sel = Method->getSelector();
2923 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002924 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002925 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002926 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002927 }
2928
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002929 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002930 SelName += ':';
2931 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002932 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002933 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002934 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002935
2936 // If there is only one parameter, and we're past it, add an empty
2937 // typed-text chunk since there is nothing to type.
2938 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002939 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002940 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002941 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002942 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2943 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002944 P != PEnd; (void)++P, ++Idx) {
2945 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002946 std::string Keyword;
2947 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002948 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002949 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002950 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002951 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002952 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002953 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002954 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002955 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002956 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002957
2958 // If we're before the starting parameter, skip the placeholder.
2959 if (Idx < StartParameter)
2960 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002961
2962 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002963 QualType ParamType = (*P)->getType();
2964 Optional<ArrayRef<QualType>> ObjCSubsts;
2965 if (!CCContext.getBaseType().isNull())
2966 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2967
2968 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2969 Arg = FormatFunctionParameter(Policy, *P, true,
2970 /*SuppressBlock=*/false,
2971 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002972 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002973 if (ObjCSubsts)
2974 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2975 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002976 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002977 ParamType);
2978 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002979 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002980 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002981 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002982 }
2983
Douglas Gregor400f5972010-08-31 05:13:43 +00002984 if (Method->isVariadic() && (P + 1) == PEnd)
2985 Arg += ", ...";
2986
Douglas Gregor95887f92010-07-08 23:20:03 +00002987 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002988 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002989 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002990 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002991 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002992 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002993 }
2994
Douglas Gregor04c5f972009-12-23 00:21:46 +00002995 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002996 if (Method->param_size() == 0) {
2997 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002998 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002999 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003000 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00003001 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003002 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00003003 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00003004
Richard Smith20e883e2015-04-29 23:20:19 +00003005 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00003006 }
3007
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003008 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00003009 }
3010
Douglas Gregorf09935f2009-12-01 05:55:20 +00003011 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00003012 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00003013 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00003014
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003015 Result.AddTypedTextChunk(
3016 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003017 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003018}
3019
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003020/// \brief Add function overload parameter chunks to the given code completion
3021/// string.
3022static void AddOverloadParameterChunks(ASTContext &Context,
3023 const PrintingPolicy &Policy,
3024 const FunctionDecl *Function,
3025 const FunctionProtoType *Prototype,
3026 CodeCompletionBuilder &Result,
3027 unsigned CurrentArg,
3028 unsigned Start = 0,
3029 bool InOptional = false) {
3030 bool FirstParameter = true;
3031 unsigned NumParams = Function ? Function->getNumParams()
3032 : Prototype->getNumParams();
3033
3034 for (unsigned P = Start; P != NumParams; ++P) {
3035 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3036 // When we see an optional default argument, put that argument and
3037 // the remaining default arguments into a new, optional string.
3038 CodeCompletionBuilder Opt(Result.getAllocator(),
3039 Result.getCodeCompletionTUInfo());
3040 if (!FirstParameter)
3041 Opt.AddChunk(CodeCompletionString::CK_Comma);
3042 // Optional sections are nested.
3043 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3044 CurrentArg, P, /*InOptional=*/true);
3045 Result.AddOptionalChunk(Opt.TakeString());
3046 return;
3047 }
3048
3049 if (FirstParameter)
3050 FirstParameter = false;
3051 else
3052 Result.AddChunk(CodeCompletionString::CK_Comma);
3053
3054 InOptional = false;
3055
3056 // Format the placeholder string.
3057 std::string Placeholder;
Erik Verbruggen11338c52017-07-19 10:45:40 +00003058 if (Function) {
3059 const ParmVarDecl *Param = Function->getParamDecl(P);
3060 Placeholder = FormatFunctionParameter(Policy, Param);
3061 if (Param->hasDefaultArg())
3062 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
3063 } else {
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003064 Placeholder = Prototype->getParamType(P).getAsString(Policy);
Erik Verbruggen11338c52017-07-19 10:45:40 +00003065 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003066
3067 if (P == CurrentArg)
3068 Result.AddCurrentParameterChunk(
3069 Result.getAllocator().CopyString(Placeholder));
3070 else
3071 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3072 }
3073
3074 if (Prototype && Prototype->isVariadic()) {
3075 CodeCompletionBuilder Opt(Result.getAllocator(),
3076 Result.getCodeCompletionTUInfo());
3077 if (!FirstParameter)
3078 Opt.AddChunk(CodeCompletionString::CK_Comma);
3079
3080 if (CurrentArg < NumParams)
3081 Opt.AddPlaceholderChunk("...");
3082 else
3083 Opt.AddCurrentParameterChunk("...");
3084
3085 Result.AddOptionalChunk(Opt.TakeString());
3086 }
3087}
3088
Douglas Gregorf0f51982009-09-23 00:34:09 +00003089CodeCompletionString *
3090CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003091 unsigned CurrentArg, Sema &S,
3092 CodeCompletionAllocator &Allocator,
3093 CodeCompletionTUInfo &CCTUInfo,
3094 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00003095 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00003096
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003097 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003098 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00003099 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003100 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00003101 = dyn_cast<FunctionProtoType>(getFunctionType());
3102 if (!FDecl && !Proto) {
3103 // Function without a prototype. Just give the return type and a
3104 // highlighted ellipsis.
3105 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003106 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3107 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003108 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3109 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3110 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003111 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003112 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003113
3114 if (FDecl) {
3115 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3116 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3117 FDecl->getParamDecl(CurrentArg)))
3118 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00003119 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003120 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003121 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3122 } else {
3123 Result.AddResultTypeChunk(
3124 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00003125 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003126 }
Alp Toker314cc812014-01-25 16:55:45 +00003127
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003128 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003129 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3130 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00003131 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003132
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003133 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00003134}
3135
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003136unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003137 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00003138 bool PreferredTypeIsPointer) {
3139 unsigned Priority = CCP_Macro;
3140
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003141 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3142 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3143 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00003144 Priority = CCP_Constant;
3145 if (PreferredTypeIsPointer)
3146 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00003147 }
3148 // Treat "YES", "NO", "true", and "false" as constants.
3149 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3150 MacroName.equals("true") || MacroName.equals("false"))
3151 Priority = CCP_Constant;
3152 // Treat "bool" as a type.
3153 else if (MacroName.equals("bool"))
3154 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3155
Douglas Gregor6e240332010-08-16 16:18:59 +00003156
3157 return Priority;
3158}
3159
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003160CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003161 if (!D)
3162 return CXCursor_UnexposedDecl;
3163
3164 switch (D->getKind()) {
3165 case Decl::Enum: return CXCursor_EnumDecl;
3166 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3167 case Decl::Field: return CXCursor_FieldDecl;
3168 case Decl::Function:
3169 return CXCursor_FunctionDecl;
3170 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3171 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003172 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003173
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003174 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003175 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3176 case Decl::ObjCMethod:
3177 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3178 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3179 case Decl::CXXMethod: return CXCursor_CXXMethod;
3180 case Decl::CXXConstructor: return CXCursor_Constructor;
3181 case Decl::CXXDestructor: return CXCursor_Destructor;
3182 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3183 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003184 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003185 case Decl::ParmVar: return CXCursor_ParmDecl;
3186 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003187 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003188 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003189 case Decl::Var: return CXCursor_VarDecl;
3190 case Decl::Namespace: return CXCursor_Namespace;
3191 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3192 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3193 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3194 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3195 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3196 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003197 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003198 case Decl::ClassTemplatePartialSpecialization:
3199 return CXCursor_ClassTemplatePartialSpecialization;
3200 case Decl::UsingDirective: return CXCursor_UsingDirective;
Olivier Goffart81978012016-06-09 16:15:55 +00003201 case Decl::StaticAssert: return CXCursor_StaticAssert;
Olivier Goffartd211c642016-11-04 06:29:27 +00003202 case Decl::Friend: return CXCursor_FriendDecl;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003203 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003204
3205 case Decl::Using:
3206 case Decl::UnresolvedUsingValue:
3207 case Decl::UnresolvedUsingTypename:
3208 return CXCursor_UsingDeclaration;
3209
Douglas Gregor4cd65962011-06-03 23:08:58 +00003210 case Decl::ObjCPropertyImpl:
3211 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3212 case ObjCPropertyImplDecl::Dynamic:
3213 return CXCursor_ObjCDynamicDecl;
3214
3215 case ObjCPropertyImplDecl::Synthesize:
3216 return CXCursor_ObjCSynthesizeDecl;
3217 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003218
3219 case Decl::Import:
3220 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003221
3222 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3223
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003224 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003225 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003226 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003227 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003228 case TTK_Struct: return CXCursor_StructDecl;
3229 case TTK_Class: return CXCursor_ClassDecl;
3230 case TTK_Union: return CXCursor_UnionDecl;
3231 case TTK_Enum: return CXCursor_EnumDecl;
3232 }
3233 }
3234 }
3235
3236 return CXCursor_UnexposedDecl;
3237}
3238
Douglas Gregor55b037b2010-07-08 20:55:51 +00003239static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003240 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003241 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003242 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003243
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003244 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003245
Douglas Gregor9eb77012009-11-07 00:00:49 +00003246 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3247 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003248 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003249 auto MD = PP.getMacroDefinition(M->first);
3250 if (IncludeUndefined || MD) {
3251 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003252 if (MI->isUsedForHeaderGuard())
3253 continue;
3254
Douglas Gregor8cb17462012-10-09 16:01:50 +00003255 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003256 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003257 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003258 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003259 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003260 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003261
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003262 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003263
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003264}
3265
Douglas Gregorce0e8562010-08-23 21:54:33 +00003266static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3267 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003268 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003269
3270 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003271
Douglas Gregorce0e8562010-08-23 21:54:33 +00003272 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3273 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003274 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003275 Results.AddResult(Result("__func__", CCP_Constant));
3276 Results.ExitScope();
3277}
3278
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003279static void HandleCodeCompleteResults(Sema *S,
3280 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003281 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003282 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003283 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003284 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003285 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003286}
3287
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003288static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3289 Sema::ParserCompletionContext PCC) {
3290 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003291 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003292 return CodeCompletionContext::CCC_TopLevel;
3293
John McCallfaf5fb42010-08-26 23:41:50 +00003294 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003295 return CodeCompletionContext::CCC_ClassStructUnion;
3296
John McCallfaf5fb42010-08-26 23:41:50 +00003297 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003298 return CodeCompletionContext::CCC_ObjCInterface;
3299
John McCallfaf5fb42010-08-26 23:41:50 +00003300 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003301 return CodeCompletionContext::CCC_ObjCImplementation;
3302
John McCallfaf5fb42010-08-26 23:41:50 +00003303 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003304 return CodeCompletionContext::CCC_ObjCIvarList;
3305
John McCallfaf5fb42010-08-26 23:41:50 +00003306 case Sema::PCC_Template:
3307 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003308 if (S.CurContext->isFileContext())
3309 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003310 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003311 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003312 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003313
John McCallfaf5fb42010-08-26 23:41:50 +00003314 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003315 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003316
John McCallfaf5fb42010-08-26 23:41:50 +00003317 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003318 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3319 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003320 return CodeCompletionContext::CCC_ParenthesizedExpression;
3321 else
3322 return CodeCompletionContext::CCC_Expression;
3323
3324 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003325 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003326 return CodeCompletionContext::CCC_Expression;
3327
John McCallfaf5fb42010-08-26 23:41:50 +00003328 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003329 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003330
John McCallfaf5fb42010-08-26 23:41:50 +00003331 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003332 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003333
3334 case Sema::PCC_ParenthesizedExpression:
3335 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003336
3337 case Sema::PCC_LocalDeclarationSpecifiers:
3338 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003339 }
David Blaikie8a40f702012-01-17 06:56:22 +00003340
3341 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003342}
3343
Douglas Gregorac322ec2010-08-27 21:18:54 +00003344/// \brief If we're in a C++ virtual member function, add completion results
3345/// that invoke the functions we override, since it's common to invoke the
3346/// overridden function as well as adding new functionality.
3347///
3348/// \param S The semantic analysis object for which we are generating results.
3349///
3350/// \param InContext This context in which the nested-name-specifier preceding
3351/// the code-completion point
3352static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3353 ResultBuilder &Results) {
3354 // Look through blocks.
3355 DeclContext *CurContext = S.CurContext;
3356 while (isa<BlockDecl>(CurContext))
3357 CurContext = CurContext->getParent();
3358
3359
3360 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3361 if (!Method || !Method->isVirtual())
3362 return;
3363
3364 // We need to have names for all of the parameters, if we're going to
3365 // generate a forwarding call.
David Majnemer59f77922016-06-24 04:05:48 +00003366 for (auto P : Method->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003367 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003368 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003369
Douglas Gregor75acd922011-09-27 23:30:47 +00003370 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003371 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3372 MEnd = Method->end_overridden_methods();
3373 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003374 CodeCompletionBuilder Builder(Results.getAllocator(),
3375 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003376 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003377 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3378 continue;
3379
3380 // If we need a nested-name-specifier, add one now.
3381 if (!InContext) {
3382 NestedNameSpecifier *NNS
3383 = getRequiredQualification(S.Context, CurContext,
3384 Overridden->getDeclContext());
3385 if (NNS) {
3386 std::string Str;
3387 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003388 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003389 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003390 }
3391 } else if (!InContext->Equals(Overridden->getDeclContext()))
3392 continue;
3393
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003394 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003395 Overridden->getNameAsString()));
3396 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003397 bool FirstParam = true;
David Majnemer59f77922016-06-24 04:05:48 +00003398 for (auto P : Method->parameters()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003399 if (FirstParam)
3400 FirstParam = false;
3401 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003402 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003403
Aaron Ballman43b68be2014-03-07 17:50:17 +00003404 Builder.AddPlaceholderChunk(
3405 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003406 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3408 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003409 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003410 CXCursor_CXXMethod,
3411 CXAvailability_Available,
3412 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003413 Results.Ignore(Overridden);
3414 }
3415}
3416
Douglas Gregor07f43572012-01-29 18:15:03 +00003417void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3418 ModuleIdPath Path) {
3419 typedef CodeCompletionResult Result;
3420 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003421 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003422 CodeCompletionContext::CCC_Other);
3423 Results.EnterNewScope();
3424
3425 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003426 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003427 typedef CodeCompletionResult Result;
3428 if (Path.empty()) {
3429 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003430 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003431 PP.getHeaderSearchInfo().collectAllModules(Modules);
3432 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3433 Builder.AddTypedTextChunk(
3434 Builder.getAllocator().CopyString(Modules[I]->Name));
3435 Results.AddResult(Result(Builder.TakeString(),
3436 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003437 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003438 Modules[I]->isAvailable()
3439 ? CXAvailability_Available
3440 : CXAvailability_NotAvailable));
3441 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003442 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003443 // Load the named module.
3444 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3445 Module::AllVisible,
3446 /*IsInclusionDirective=*/false);
3447 // Enumerate submodules.
3448 if (Mod) {
3449 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3450 SubEnd = Mod->submodule_end();
3451 Sub != SubEnd; ++Sub) {
3452
3453 Builder.AddTypedTextChunk(
3454 Builder.getAllocator().CopyString((*Sub)->Name));
3455 Results.AddResult(Result(Builder.TakeString(),
3456 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003457 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003458 (*Sub)->isAvailable()
3459 ? CXAvailability_Available
3460 : CXAvailability_NotAvailable));
3461 }
3462 }
3463 }
3464 Results.ExitScope();
3465 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3466 Results.data(),Results.size());
3467}
3468
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003469void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003470 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003471 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003472 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003473 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003474 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003475
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003476 // Determine how to filter results, e.g., so that the names of
3477 // values (functions, enumerators, function templates, etc.) are
3478 // only allowed where we can have an expression.
3479 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003480 case PCC_Namespace:
3481 case PCC_Class:
3482 case PCC_ObjCInterface:
3483 case PCC_ObjCImplementation:
3484 case PCC_ObjCInstanceVariableList:
3485 case PCC_Template:
3486 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003487 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003488 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003489 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3490 break;
3491
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003492 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003493 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003494 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003495 case PCC_ForInit:
3496 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003497 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003498 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3499 else
3500 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003501
David Blaikiebbafb8a2012-03-11 07:00:24 +00003502 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003503 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003504 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003505
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003506 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003507 // Unfiltered
3508 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003509 }
3510
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003511 // If we are in a C++ non-static member function, check the qualifiers on
3512 // the member function to filter/prioritize the results list.
3513 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3514 if (CurMethod->isInstance())
3515 Results.setObjectTypeQualifiers(
3516 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3517
Douglas Gregorc580c522010-01-14 01:09:38 +00003518 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003519 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3520 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003521
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003522 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003523 Results.ExitScope();
3524
Douglas Gregorce0e8562010-08-23 21:54:33 +00003525 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003526 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003527 case PCC_Expression:
3528 case PCC_Statement:
3529 case PCC_RecoveryInFunction:
3530 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003531 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003532 break;
3533
3534 case PCC_Namespace:
3535 case PCC_Class:
3536 case PCC_ObjCInterface:
3537 case PCC_ObjCImplementation:
3538 case PCC_ObjCInstanceVariableList:
3539 case PCC_Template:
3540 case PCC_MemberTemplate:
3541 case PCC_ForInit:
3542 case PCC_Condition:
3543 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003544 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003545 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003546 }
3547
Douglas Gregor9eb77012009-11-07 00:00:49 +00003548 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003549 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003550
Douglas Gregor50832e02010-09-20 22:39:41 +00003551 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003552 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003553}
3554
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003555static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3556 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003557 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003558 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003559 bool IsSuper,
3560 ResultBuilder &Results);
3561
3562void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3563 bool AllowNonIdentifiers,
3564 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003565 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003566 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003567 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003568 AllowNestedNameSpecifiers
3569 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3570 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003571 Results.EnterNewScope();
3572
3573 // Type qualifiers can come after names.
3574 Results.AddResult(Result("const"));
3575 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003577 Results.AddResult(Result("restrict"));
3578
David Blaikiebbafb8a2012-03-11 07:00:24 +00003579 if (getLangOpts().CPlusPlus) {
Alex Lorenz8f4d3992017-02-13 23:19:40 +00003580 if (getLangOpts().CPlusPlus11 &&
3581 (DS.getTypeSpecType() == DeclSpec::TST_class ||
3582 DS.getTypeSpecType() == DeclSpec::TST_struct))
3583 Results.AddResult("final");
3584
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003585 if (AllowNonIdentifiers) {
3586 Results.AddResult(Result("operator"));
3587 }
3588
3589 // Add nested-name-specifiers.
3590 if (AllowNestedNameSpecifiers) {
3591 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003592 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003593 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3594 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3595 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003596 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003597 }
3598 }
3599 Results.ExitScope();
3600
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003601 // If we're in a context where we might have an expression (rather than a
3602 // declaration), and what we've seen so far is an Objective-C type that could
3603 // be a receiver of a class message, this may be a class message send with
3604 // the initial opening bracket '[' missing. Add appropriate completions.
3605 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003606 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003607 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003608 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3609 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003610 !DS.isTypeAltiVecVector() &&
3611 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003612 (S->getFlags() & Scope::DeclScope) != 0 &&
3613 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3614 Scope::FunctionPrototypeScope |
3615 Scope::AtCatchScope)) == 0) {
3616 ParsedType T = DS.getRepAsType();
3617 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003618 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003619 }
3620
Douglas Gregor56ccce02010-08-24 04:59:56 +00003621 // Note that we intentionally suppress macro results here, since we do not
3622 // encourage using macros to produce the names of entities.
3623
Douglas Gregor0ac41382010-09-23 23:01:17 +00003624 HandleCodeCompleteResults(this, CodeCompleter,
3625 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003626 Results.data(), Results.size());
3627}
3628
Douglas Gregor68762e72010-08-23 21:17:50 +00003629struct Sema::CodeCompleteExpressionData {
3630 CodeCompleteExpressionData(QualType PreferredType = QualType())
3631 : PreferredType(PreferredType), IntegralConstantExpression(false),
3632 ObjCCollection(false) { }
3633
3634 QualType PreferredType;
3635 bool IntegralConstantExpression;
3636 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003637 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003638};
3639
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003640/// \brief Perform code-completion in an expression context when we know what
3641/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003642void Sema::CodeCompleteExpression(Scope *S,
3643 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003644 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003645 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003646 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003647 if (Data.ObjCCollection)
3648 Results.setFilter(&ResultBuilder::IsObjCCollection);
3649 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003650 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003651 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003652 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3653 else
3654 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003655
3656 if (!Data.PreferredType.isNull())
3657 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3658
3659 // Ignore any declarations that we were told that we don't care about.
3660 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3661 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003662
3663 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003664 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3665 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003666
3667 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003668 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003669 Results.ExitScope();
3670
Douglas Gregor55b037b2010-07-08 20:55:51 +00003671 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003672 if (!Data.PreferredType.isNull())
3673 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3674 || Data.PreferredType->isMemberPointerType()
3675 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003676
Douglas Gregorce0e8562010-08-23 21:54:33 +00003677 if (S->getFnParent() &&
3678 !Data.ObjCCollection &&
3679 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003680 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003681
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003682 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003683 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003684 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003685 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3686 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003687 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003688}
3689
Douglas Gregoreda7e542010-09-18 01:28:11 +00003690void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3691 if (E.isInvalid())
3692 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003693 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003694 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003695}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003696
Douglas Gregorb888acf2010-12-09 23:01:55 +00003697/// \brief The set of properties that have already been added, referenced by
3698/// property name.
3699typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3700
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003701/// \brief Retrieve the container definition, if any?
3702static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3703 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3704 if (Interface->hasDefinition())
3705 return Interface->getDefinition();
3706
3707 return Interface;
3708 }
3709
3710 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3711 if (Protocol->hasDefinition())
3712 return Protocol->getDefinition();
3713
3714 return Protocol;
3715 }
3716 return Container;
3717}
3718
Alex Lorenzbaef8022016-11-09 13:43:18 +00003719/// \brief Adds a block invocation code completion result for the given block
3720/// declaration \p BD.
3721static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3722 CodeCompletionBuilder &Builder,
3723 const NamedDecl *BD,
3724 const FunctionTypeLoc &BlockLoc,
3725 const FunctionProtoTypeLoc &BlockProtoLoc) {
3726 Builder.AddResultTypeChunk(
3727 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3728 Policy, Builder.getAllocator()));
3729
3730 AddTypedNameChunk(Context, Policy, BD, Builder);
3731 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3732
3733 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3734 Builder.AddPlaceholderChunk("...");
3735 } else {
3736 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3737 if (I)
3738 Builder.AddChunk(CodeCompletionString::CK_Comma);
3739
3740 // Format the placeholder string.
3741 std::string PlaceholderStr =
3742 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3743
3744 if (I == N - 1 && BlockProtoLoc &&
3745 BlockProtoLoc.getTypePtr()->isVariadic())
3746 PlaceholderStr += ", ...";
3747
3748 // Add the placeholder string.
3749 Builder.AddPlaceholderChunk(
3750 Builder.getAllocator().CopyString(PlaceholderStr));
3751 }
3752 }
3753
3754 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3755}
3756
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003757static void AddObjCProperties(
3758 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3759 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3760 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3761 bool IsBaseExprStatement = false, bool IsClassProperty = false) {
John McCall276321a2010-08-25 06:19:51 +00003762 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003763
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003764 // Retrieve the definition.
3765 Container = getContainerDef(Container);
3766
Douglas Gregor9291bad2009-11-18 01:29:26 +00003767 // Add properties in this container.
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003768 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003769 if (!AddedProperties.insert(P->getIdentifier()).second)
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003770 return;
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003771
Alex Lorenzbaef8022016-11-09 13:43:18 +00003772 // FIXME: Provide block invocation completion for non-statement
3773 // expressions.
3774 if (!P->getType().getTypePtr()->isBlockPointerType() ||
3775 !IsBaseExprStatement) {
3776 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3777 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003778 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003779 }
3780
3781 // Block setter and invocation completion is provided only when we are able
3782 // to find the FunctionProtoTypeLoc with parameter names for the block.
3783 FunctionTypeLoc BlockLoc;
3784 FunctionProtoTypeLoc BlockProtoLoc;
3785 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3786 BlockProtoLoc);
3787 if (!BlockLoc) {
3788 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3789 CurContext);
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003790 return;
Alex Lorenzbaef8022016-11-09 13:43:18 +00003791 }
3792
3793 // The default completion result for block properties should be the block
3794 // invocation completion when the base expression is a statement.
3795 CodeCompletionBuilder Builder(Results.getAllocator(),
3796 Results.getCodeCompletionTUInfo());
3797 AddObjCBlockCall(Container->getASTContext(),
3798 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3799 BlockLoc, BlockProtoLoc);
3800 Results.MaybeAddResult(
3801 Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3802 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003803
3804 // Provide additional block setter completion iff the base expression is a
Alex Lorenzbaef8022016-11-09 13:43:18 +00003805 // statement and the block property is mutable.
3806 if (!P->isReadOnly()) {
3807 CodeCompletionBuilder Builder(Results.getAllocator(),
3808 Results.getCodeCompletionTUInfo());
3809 AddResultTypeChunk(Container->getASTContext(),
3810 getCompletionPrintingPolicy(Results.getSema()), P,
3811 CCContext.getBaseType(), Builder);
3812 Builder.AddTypedTextChunk(
3813 Results.getAllocator().CopyString(P->getName()));
3814 Builder.AddChunk(CodeCompletionString::CK_Equal);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003815
Alex Lorenzbaef8022016-11-09 13:43:18 +00003816 std::string PlaceholderStr = formatBlockPlaceholder(
3817 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3818 BlockProtoLoc, /*SuppressBlockName=*/true);
3819 // Add the placeholder string.
3820 Builder.AddPlaceholderChunk(
3821 Builder.getAllocator().CopyString(PlaceholderStr));
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003822
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003823 // When completing blocks properties that return void the default
3824 // property completion result should show up before the setter,
3825 // otherwise the setter completion should show up before the default
3826 // property completion, as we normally want to use the result of the
3827 // call.
Alex Lorenzbaef8022016-11-09 13:43:18 +00003828 Results.MaybeAddResult(
3829 Result(Builder.TakeString(), P,
Alex Lorenz6e0f3932017-01-06 12:00:44 +00003830 Results.getBasePriority(P) +
3831 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3832 ? CCD_BlockPropertySetter
3833 : -CCD_BlockPropertySetter)),
Alex Lorenzbaef8022016-11-09 13:43:18 +00003834 CurContext);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003835 }
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003836 };
3837
3838 if (IsClassProperty) {
3839 for (const auto *P : Container->class_properties())
3840 AddProperty(P);
3841 } else {
3842 for (const auto *P : Container->instance_properties())
3843 AddProperty(P);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003844 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003845
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003846 // Add nullary methods or implicit class properties
Douglas Gregor95147142011-05-05 15:50:42 +00003847 if (AllowNullaryMethods) {
3848 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003849 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003850 // Adds a method result
3851 const auto AddMethod = [&](const ObjCMethodDecl *M) {
3852 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3853 if (!Name)
3854 return;
3855 if (!AddedProperties.insert(Name).second)
3856 return;
3857 CodeCompletionBuilder Builder(Results.getAllocator(),
3858 Results.getCodeCompletionTUInfo());
3859 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3860 Builder.AddTypedTextChunk(
3861 Results.getAllocator().CopyString(Name->getName()));
3862 Results.MaybeAddResult(
3863 Result(Builder.TakeString(), M,
3864 CCP_MemberDeclaration + CCD_MethodAsProperty),
3865 CurContext);
3866 };
3867
3868 if (IsClassProperty) {
3869 for (const auto *M : Container->methods()) {
3870 // Gather the class method that can be used as implicit property
3871 // getters. Methods with arguments or methods that return void aren't
3872 // added to the results as they can't be used as a getter.
3873 if (!M->getSelector().isUnarySelector() ||
3874 M->getReturnType()->isVoidType() || M->isInstanceMethod())
3875 continue;
3876 AddMethod(M);
3877 }
3878 } else {
3879 for (auto *M : Container->methods()) {
3880 if (M->getSelector().isUnarySelector())
3881 AddMethod(M);
3882 }
Douglas Gregor95147142011-05-05 15:50:42 +00003883 }
3884 }
Douglas Gregor95147142011-05-05 15:50:42 +00003885
Douglas Gregor9291bad2009-11-18 01:29:26 +00003886 // Add properties in referenced protocols.
3887 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003888 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003889 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003890 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003891 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003892 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003893 if (AllowCategories) {
3894 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003895 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003896 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003897 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003898 IsBaseExprStatement, IsClassProperty);
Douglas Gregor5d649882009-11-18 22:32:06 +00003899 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003900
Douglas Gregor9291bad2009-11-18 01:29:26 +00003901 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003902 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003903 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003904 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003905 IsBaseExprStatement, IsClassProperty);
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003906
Douglas Gregor9291bad2009-11-18 01:29:26 +00003907 // Look in the superclass.
3908 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003909 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003910 AllowNullaryMethods, CurContext, AddedProperties,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003911 Results, IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003912 } else if (const ObjCCategoryDecl *Category
3913 = dyn_cast<ObjCCategoryDecl>(Container)) {
3914 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003915 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003916 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003917 CurContext, AddedProperties, Results,
Alex Lorenzfeafdf62016-12-08 15:09:40 +00003918 IsBaseExprStatement, IsClassProperty);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003919 }
3920}
3921
Alex Lorenz0fe0d982017-05-11 13:41:00 +00003922static void AddRecordMembersCompletionResults(Sema &SemaRef,
3923 ResultBuilder &Results, Scope *S,
3924 QualType BaseType,
3925 RecordDecl *RD) {
3926 // Indicate that we are performing a member access, and the cv-qualifiers
3927 // for the base object type.
3928 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3929
3930 // Access to a C/C++ class, struct, or union.
3931 Results.allowNestedNameSpecifiers();
3932 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3933 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003934 SemaRef.CodeCompleter->includeGlobals(),
3935 /*IncludeDependentBases=*/true);
Alex Lorenz0fe0d982017-05-11 13:41:00 +00003936
3937 if (SemaRef.getLangOpts().CPlusPlus) {
3938 if (!Results.empty()) {
3939 // The "template" keyword can follow "->" or "." in the grammar.
3940 // However, we only want to suggest the template keyword if something
3941 // is dependent.
3942 bool IsDependent = BaseType->isDependentType();
3943 if (!IsDependent) {
3944 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3945 if (DeclContext *Ctx = DepScope->getEntity()) {
3946 IsDependent = Ctx->isDependentContext();
3947 break;
3948 }
3949 }
3950
3951 if (IsDependent)
3952 Results.AddResult(CodeCompletionResult("template"));
3953 }
3954 }
3955}
3956
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003957void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00003958 SourceLocation OpLoc, bool IsArrow,
3959 bool IsBaseExprStatement) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003960 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003961 return;
3962
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003963 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3964 if (ConvertedBase.isInvalid())
3965 return;
3966 Base = ConvertedBase.get();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003967
Douglas Gregor2436e712009-09-17 21:32:03 +00003968 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003969
3970 if (IsArrow) {
3971 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3972 BaseType = Ptr->getPointeeType();
3973 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003974 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003975 else
3976 return;
3977 }
3978
Douglas Gregor21325842011-07-07 16:03:39 +00003979 enum CodeCompletionContext::Kind contextKind;
3980
3981 if (IsArrow) {
3982 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3983 }
3984 else {
3985 if (BaseType->isObjCObjectPointerType() ||
3986 BaseType->isObjCObjectOrInterfaceType()) {
3987 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3988 }
3989 else {
3990 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3991 }
3992 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003993
3994 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003995 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003996 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003997 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003998 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003999 Results.EnterNewScope();
4000 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Alex Lorenz0fe0d982017-05-11 13:41:00 +00004001 AddRecordMembersCompletionResults(*this, Results, S, BaseType,
4002 Record->getDecl());
Alex Lorenze6afa392017-05-11 13:48:57 +00004003 } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
4004 TemplateName TN = TST->getTemplateName();
4005 if (const auto *TD =
4006 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4007 CXXRecordDecl *RD = TD->getTemplatedDecl();
4008 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4009 }
4010 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4011 if (auto *RD = ICNT->getDecl())
4012 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
Alex Lorenz06cfa992016-10-12 11:40:15 +00004013 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00004014 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00004015 AddedPropertiesSet AddedProperties;
Alex Lorenz06cfa992016-10-12 11:40:15 +00004016
4017 if (const ObjCObjectPointerType *ObjCPtr =
4018 BaseType->getAsObjCInterfacePointerType()) {
4019 // Add property results based on our interface.
4020 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4021 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4022 /*AllowNullaryMethods=*/true, CurContext,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00004023 AddedProperties, Results, IsBaseExprStatement);
Alex Lorenz06cfa992016-10-12 11:40:15 +00004024 }
4025
Douglas Gregor9291bad2009-11-18 01:29:26 +00004026 // Add properties from the protocols in a qualified interface.
Alex Lorenz06cfa992016-10-12 11:40:15 +00004027 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00004028 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +00004029 CurContext, AddedProperties, Results,
4030 IsBaseExprStatement);
Douglas Gregor9291bad2009-11-18 01:29:26 +00004031 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00004032 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00004033 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00004034 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00004035 if (const ObjCObjectPointerType *ObjCPtr
4036 = BaseType->getAs<ObjCObjectPointerType>())
4037 Class = ObjCPtr->getInterfaceDecl();
4038 else
John McCall8b07ec22010-05-15 11:32:37 +00004039 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00004040
4041 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00004042 if (Class) {
4043 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4044 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00004045 LookupVisibleDecls(Class, LookupMemberName, Consumer,
4046 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00004047 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004048 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00004049
4050 // FIXME: How do we cope with isa?
4051
4052 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00004053
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00004054 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004055 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004056 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004057 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004058}
4059
Alex Lorenzfeafdf62016-12-08 15:09:40 +00004060void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4061 IdentifierInfo &ClassName,
4062 SourceLocation ClassNameLoc,
4063 bool IsBaseExprStatement) {
4064 IdentifierInfo *ClassNamePtr = &ClassName;
4065 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4066 if (!IFace)
4067 return;
4068 CodeCompletionContext CCContext(
4069 CodeCompletionContext::CCC_ObjCPropertyAccess);
4070 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4071 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4072 &ResultBuilder::IsMember);
4073 Results.EnterNewScope();
4074 AddedPropertiesSet AddedProperties;
4075 AddObjCProperties(CCContext, IFace, true,
4076 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4077 Results, IsBaseExprStatement,
4078 /*IsClassProperty=*/true);
4079 Results.ExitScope();
4080 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4081 Results.data(), Results.size());
4082}
4083
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004084void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4085 if (!CodeCompleter)
4086 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00004087
4088 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004089 enum CodeCompletionContext::Kind ContextKind
4090 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004091 switch ((DeclSpec::TST)TagSpec) {
4092 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004093 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004094 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004095 break;
4096
4097 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004098 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004099 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004100 break;
4101
4102 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004103 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00004104 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00004105 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004106 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004107 break;
4108
4109 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004110 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004111 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004112
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004113 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4114 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004115 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00004116
4117 // First pass: look for tags.
4118 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00004119 LookupVisibleDecls(S, LookupTagName, Consumer,
4120 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00004121
Douglas Gregor39982192010-08-15 06:18:01 +00004122 if (CodeCompleter->includeGlobals()) {
4123 // Second pass: look for nested name specifiers.
4124 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4125 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4126 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00004127
Douglas Gregor0ac41382010-09-23 23:01:17 +00004128 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004129 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004130}
4131
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004132static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4133 const LangOptions &LangOpts) {
4134 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4135 Results.AddResult("const");
4136 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4137 Results.AddResult("volatile");
4138 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4139 Results.AddResult("restrict");
4140 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4141 Results.AddResult("_Atomic");
4142 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4143 Results.AddResult("__unaligned");
4144}
4145
Douglas Gregor28c78432010-08-27 17:35:51 +00004146void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004147 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004148 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004149 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00004150 Results.EnterNewScope();
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004151 AddTypeQualifierResults(DS, Results, LangOpts);
Douglas Gregor28c78432010-08-27 17:35:51 +00004152 Results.ExitScope();
4153 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004154 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00004155 Results.data(), Results.size());
4156}
4157
Alex Lorenz8f4d3992017-02-13 23:19:40 +00004158void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4159 const VirtSpecifiers *VS) {
4160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4161 CodeCompleter->getCodeCompletionTUInfo(),
4162 CodeCompletionContext::CCC_TypeQualifiers);
4163 Results.EnterNewScope();
4164 AddTypeQualifierResults(DS, Results, LangOpts);
4165 if (LangOpts.CPlusPlus11) {
4166 Results.AddResult("noexcept");
4167 if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() &&
4168 !D.isStaticMember()) {
4169 if (!VS || !VS->isFinalSpecified())
4170 Results.AddResult("final");
4171 if (!VS || !VS->isOverrideSpecified())
4172 Results.AddResult("override");
4173 }
4174 }
4175 Results.ExitScope();
4176 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4177 Results.data(), Results.size());
4178}
4179
Benjamin Kramer72dae622016-02-18 15:30:24 +00004180void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4181 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4182}
4183
Douglas Gregord328d572009-09-21 18:10:23 +00004184void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00004185 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00004186 return;
John McCall5939b162011-08-06 07:30:58 +00004187
John McCallaab3e412010-08-25 08:40:02 +00004188 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00004189 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4190 if (!type->isEnumeralType()) {
4191 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00004192 Data.IntegralConstantExpression = true;
4193 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00004194 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00004195 }
Douglas Gregord328d572009-09-21 18:10:23 +00004196
4197 // Code-complete the cases of a switch statement over an enumeration type
4198 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00004199 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004200 if (EnumDecl *Def = Enum->getDefinition())
4201 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00004202
4203 // Determine which enumerators we have already seen in the switch statement.
4204 // FIXME: Ideally, we would also be able to look *past* the code-completion
4205 // token, in case we are code-completing in the middle of the switch and not
4206 // at the end. However, we aren't able to do so at the moment.
4207 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00004208 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00004209 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4210 SC = SC->getNextSwitchCase()) {
4211 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4212 if (!Case)
4213 continue;
4214
4215 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4216 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4217 if (EnumConstantDecl *Enumerator
4218 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4219 // We look into the AST of the case statement to determine which
4220 // enumerator was named. Alternatively, we could compute the value of
4221 // the integral constant expression, then compare it against the
4222 // values of each enumerator. However, value-based approach would not
4223 // work as well with C++ templates where enumerators declared within a
4224 // template are type- and value-dependent.
4225 EnumeratorsSeen.insert(Enumerator);
4226
Douglas Gregorf2510672009-09-21 19:57:38 +00004227 // If this is a qualified-id, keep track of the nested-name-specifier
4228 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00004229 //
4230 // switch (TagD.getKind()) {
4231 // case TagDecl::TK_enum:
4232 // break;
4233 // case XXX
4234 //
Douglas Gregorf2510672009-09-21 19:57:38 +00004235 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00004236 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4237 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004238 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00004239 }
4240 }
4241
David Blaikiebbafb8a2012-03-11 07:00:24 +00004242 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00004243 // If there are no prior enumerators in C++, check whether we have to
4244 // qualify the names of the enumerators that we suggest, because they
4245 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00004246 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00004247 }
4248
Douglas Gregord328d572009-09-21 18:10:23 +00004249 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004250 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004251 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004252 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00004253 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004254 for (auto *E : Enum->enumerators()) {
4255 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00004256 continue;
4257
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00004258 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00004259 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00004260 }
4261 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00004262
Douglas Gregor21325842011-07-07 16:03:39 +00004263 //We need to make sure we're setting the right context,
4264 //so only say we include macros if the code completer says we do
4265 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4266 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00004267 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00004268 kind = CodeCompletionContext::CCC_OtherWithMacros;
4269 }
4270
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004271 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00004272 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004273 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00004274}
4275
Robert Wilhelm16e94b92013-08-09 18:02:13 +00004276static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004277 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004278 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004279
4280 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004281 if (!Args[I])
4282 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004283
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00004284 return false;
4285}
4286
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004287typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4288
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004289static void mergeCandidatesWithResults(Sema &SemaRef,
4290 SmallVectorImpl<ResultCandidate> &Results,
4291 OverloadCandidateSet &CandidateSet,
4292 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004293 if (!CandidateSet.empty()) {
4294 // Sort the overload candidate set by placing the best overloads first.
4295 std::stable_sort(
4296 CandidateSet.begin(), CandidateSet.end(),
4297 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
Richard Smith67ef14f2017-09-26 18:37:55 +00004298 return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
4299 CandidateSet.getKind());
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004300 });
4301
4302 // Add the remaining viable overload candidates as code-completion results.
Erik Verbruggen7ec91072017-09-08 10:23:08 +00004303 for (auto &Candidate : CandidateSet) {
4304 if (Candidate.Function && Candidate.Function->isDeleted())
4305 continue;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004306 if (Candidate.Viable)
4307 Results.push_back(ResultCandidate(Candidate.Function));
Erik Verbruggen7ec91072017-09-08 10:23:08 +00004308 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004309 }
4310}
4311
4312/// \brief Get the type of the Nth parameter from a given set of overload
4313/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004314static QualType getParamType(Sema &SemaRef,
4315 ArrayRef<ResultCandidate> Candidates,
4316 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004317
4318 // Given the overloads 'Candidates' for a function call matching all arguments
4319 // up to N, return the type of the Nth parameter if it is the same for all
4320 // overload candidates.
4321 QualType ParamType;
4322 for (auto &Candidate : Candidates) {
4323 if (auto FType = Candidate.getFunctionType())
4324 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4325 if (N < Proto->getNumParams()) {
4326 if (ParamType.isNull())
4327 ParamType = Proto->getParamType(N);
4328 else if (!SemaRef.Context.hasSameUnqualifiedType(
4329 ParamType.getNonReferenceType(),
4330 Proto->getParamType(N).getNonReferenceType()))
4331 // Otherwise return a default-constructed QualType.
4332 return QualType();
4333 }
4334 }
4335
4336 return ParamType;
4337}
4338
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00004339static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4340 MutableArrayRef<ResultCandidate> Candidates,
4341 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004342 bool CompleteExpressionWithCurrentArg = true) {
4343 QualType ParamType;
4344 if (CompleteExpressionWithCurrentArg)
4345 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4346
4347 if (ParamType.isNull())
4348 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4349 else
4350 SemaRef.CodeCompleteExpression(S, ParamType);
4351
4352 if (!Candidates.empty())
4353 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4354 Candidates.data(),
4355 Candidates.size());
4356}
4357
4358void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004359 if (!CodeCompleter)
4360 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004361
4362 // When we're code-completing for a call, we fall back to ordinary
4363 // name code-completion whenever we can't produce specific
4364 // results. We may want to revisit this strategy in the future,
4365 // e.g., by merging the two kinds of results.
4366
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004367 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004368
Douglas Gregorcabea402009-09-22 15:41:20 +00004369 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004370 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4371 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004372 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004373 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004374 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004375
John McCall57500772009-12-16 12:17:52 +00004376 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004377 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004378 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004379
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004380 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004381
John McCall57500772009-12-16 12:17:52 +00004382 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004383 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004384 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004385 /*PartialOverloading=*/true);
4386 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4387 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4388 if (UME->hasExplicitTemplateArgs()) {
4389 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4390 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004391 }
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00004392
4393 // Add the base as first argument (use a nullptr if the base is implicit).
4394 SmallVector<Expr *, 12> ArgExprs(
4395 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004396 ArgExprs.append(Args.begin(), Args.end());
4397 UnresolvedSet<8> Decls;
4398 Decls.append(UME->decls_begin(), UME->decls_end());
Benjamin Kramere3962ae2017-10-26 08:41:28 +00004399 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004400 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4401 /*SuppressUsedConversions=*/false,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00004402 /*PartialOverloading=*/true,
4403 FirstArgumentIsBase);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004404 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004405 FunctionDecl *FD = nullptr;
4406 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4407 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4408 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4409 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004410 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004411 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004412 !FD->getType()->getAs<FunctionProtoType>())
4413 Results.push_back(ResultCandidate(FD));
4414 else
4415 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4416 Args, CandidateSet,
4417 /*SuppressUsedConversions=*/false,
4418 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004419
4420 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4421 // If expression's type is CXXRecordDecl, it may overload the function
4422 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004423 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004424 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004425 DeclarationName OpName = Context.DeclarationNames
4426 .getCXXOperatorName(OO_Call);
4427 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4428 LookupQualifiedName(R, DC);
4429 R.suppressDiagnostics();
4430 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4431 ArgExprs.append(Args.begin(), Args.end());
4432 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4433 /*ExplicitArgs=*/nullptr,
4434 /*SuppressUsedConversions=*/false,
4435 /*PartialOverloading=*/true);
4436 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004437 } else {
4438 // Lastly we check whether expression's type is function pointer or
4439 // function.
4440 QualType T = NakedFn->getType();
4441 if (!T->getPointeeType().isNull())
4442 T = T->getPointeeType();
4443
4444 if (auto FP = T->getAs<FunctionProtoType>()) {
4445 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004446 /*PartialOverloading=*/true) ||
4447 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004448 Results.push_back(ResultCandidate(FP));
4449 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004450 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004451 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004452 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004453 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004454
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004455 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4456 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4457 !CandidateSet.empty());
4458}
4459
4460void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4461 ArrayRef<Expr *> Args) {
4462 if (!CodeCompleter)
4463 return;
4464
4465 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004466 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004467 return;
4468
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004469 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4470 if (!RD) {
4471 CodeCompleteExpression(S, Type);
4472 return;
4473 }
4474
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004475 // FIXME: Provide support for member initializers.
4476 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004477
4478 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4479
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004480 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004481 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4482 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4483 Args, CandidateSet,
4484 /*SuppressUsedConversions=*/false,
4485 /*PartialOverloading=*/true);
4486 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4487 AddTemplateOverloadCandidate(FTD,
4488 DeclAccessPair::make(FTD, C->getAccess()),
4489 /*ExplicitTemplateArgs=*/nullptr,
4490 Args, CandidateSet,
4491 /*SuppressUsedConversions=*/false,
4492 /*PartialOverloading=*/true);
4493 }
4494 }
4495
4496 SmallVector<ResultCandidate, 8> Results;
4497 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4498 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004499}
4500
John McCall48871652010-08-21 09:40:31 +00004501void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4502 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004503 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004504 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004505 return;
4506 }
4507
4508 CodeCompleteExpression(S, VD->getType());
4509}
4510
4511void Sema::CodeCompleteReturn(Scope *S) {
4512 QualType ResultType;
4513 if (isa<BlockDecl>(CurContext)) {
4514 if (BlockScopeInfo *BSI = getCurBlock())
4515 ResultType = BSI->ReturnType;
4516 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004517 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004518 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004519 ResultType = Method->getReturnType();
4520
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004521 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004522 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004523 else
4524 CodeCompleteExpression(S, ResultType);
4525}
4526
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004527void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004528 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004529 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004530 mapCodeCompletionContext(*this, PCC_Statement));
4531 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4532 Results.EnterNewScope();
4533
4534 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4535 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4536 CodeCompleter->includeGlobals());
4537
4538 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4539
4540 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004541 CodeCompletionBuilder Builder(Results.getAllocator(),
4542 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004543 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004544 if (Results.includeCodePatterns()) {
4545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4546 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4548 Builder.AddPlaceholderChunk("statements");
4549 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4550 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4551 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004552 Results.AddResult(Builder.TakeString());
4553
4554 // "else if" block
4555 Builder.AddTypedTextChunk("else");
4556 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4557 Builder.AddTextChunk("if");
4558 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4559 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004560 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004561 Builder.AddPlaceholderChunk("condition");
4562 else
4563 Builder.AddPlaceholderChunk("expression");
4564 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004565 if (Results.includeCodePatterns()) {
4566 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4567 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4568 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4569 Builder.AddPlaceholderChunk("statements");
4570 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4571 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4572 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004573 Results.AddResult(Builder.TakeString());
4574
4575 Results.ExitScope();
4576
4577 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004578 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004579
4580 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004581 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004582
4583 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4584 Results.data(),Results.size());
4585}
4586
Richard Trieu2bd04012011-09-09 02:00:50 +00004587void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004588 if (LHS)
4589 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4590 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004591 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004592}
4593
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004594void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004595 bool EnteringContext) {
4596 if (!SS.getScopeRep() || !CodeCompleter)
4597 return;
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004598
4599 // Always pretend to enter a context to ensure that a dependent type
4600 // resolves to a dependent record.
4601 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +00004602 if (!Ctx)
4603 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004604
4605 // Try to instantiate any non-dependent declaration contexts before
4606 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004607 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004608 return;
4609
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004610 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004611 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004612 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004613 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004614
Douglas Gregor3545ff42009-09-21 16:56:56 +00004615 // The "template" keyword can follow "::" in the grammar, but only
4616 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004617 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004618 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004619 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004620
4621 // Add calls to overridden virtual functions, if there are any.
4622 //
4623 // FIXME: This isn't wonderful, because we don't know whether we're actually
4624 // in a context that permits expressions. This is a general issue with
4625 // qualified-id completions.
4626 if (!EnteringContext)
4627 MaybeAddOverrideCalls(*this, Ctx, Results);
4628 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004629
Douglas Gregorac322ec2010-08-27 21:18:54 +00004630 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004631 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4632 /*IncludeGlobalScope=*/true,
4633 /*IncludeDependentBases=*/true);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004634
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004635 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004636 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004637 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004638}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004639
4640void Sema::CodeCompleteUsing(Scope *S) {
4641 if (!CodeCompleter)
4642 return;
4643
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004644 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004645 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004646 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4647 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004648 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004649
4650 // If we aren't in class scope, we could see the "namespace" keyword.
4651 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004652 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004653
4654 // After "using", we can see anything that would start a
4655 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004656 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004657 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4658 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004659 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004660
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004661 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004662 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004663 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004664}
4665
4666void Sema::CodeCompleteUsingDirective(Scope *S) {
4667 if (!CodeCompleter)
4668 return;
4669
Douglas Gregor3545ff42009-09-21 16:56:56 +00004670 // After "using namespace", we expect to see a namespace name or namespace
4671 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004672 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004673 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004674 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004675 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004676 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004677 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004678 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4679 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004680 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004681 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004682 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004683 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004684}
4685
4686void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4687 if (!CodeCompleter)
4688 return;
4689
Ted Kremenekc37877d2013-10-08 17:08:03 +00004690 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004691 if (!S->getParent())
4692 Ctx = Context.getTranslationUnitDecl();
4693
Douglas Gregor0ac41382010-09-23 23:01:17 +00004694 bool SuppressedGlobalResults
4695 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4696
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004697 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004698 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004699 SuppressedGlobalResults
4700 ? CodeCompletionContext::CCC_Namespace
4701 : CodeCompletionContext::CCC_Other,
4702 &ResultBuilder::IsNamespace);
4703
4704 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004705 // We only want to see those namespaces that have already been defined
4706 // within this scope, because its likely that the user is creating an
4707 // extended namespace declaration. Keep track of the most recent
4708 // definition of each namespace.
4709 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4710 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4711 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4712 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004713 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004714
4715 // Add the most recent definition (or extended definition) of each
4716 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004717 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004718 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004719 NS = OrigToLatest.begin(),
4720 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004721 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004722 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004723 NS->second, Results.getBasePriority(NS->second),
4724 nullptr),
4725 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004726 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004727 }
4728
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004729 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004730 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004731 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004732}
4733
4734void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4735 if (!CodeCompleter)
4736 return;
4737
Douglas Gregor3545ff42009-09-21 16:56:56 +00004738 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004739 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004740 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004741 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004742 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004743 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004744 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4745 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004746 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004747 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004748 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004749}
4750
Douglas Gregorc811ede2009-09-18 20:05:18 +00004751void Sema::CodeCompleteOperatorName(Scope *S) {
4752 if (!CodeCompleter)
4753 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004754
John McCall276321a2010-08-25 06:19:51 +00004755 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004756 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004757 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004758 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004759 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004760 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004761
Douglas Gregor3545ff42009-09-21 16:56:56 +00004762 // Add the names of overloadable operators.
4763#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4764 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004765 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004766#include "clang/Basic/OperatorKinds.def"
4767
4768 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004769 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004770 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004771 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4772 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004773
4774 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004775 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004776 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004777
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004778 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004779 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004780 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004781}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004782
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004783void Sema::CodeCompleteConstructorInitializer(
4784 Decl *ConstructorD,
4785 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004786 if (!ConstructorD)
4787 return;
4788
4789 AdjustDeclIfTemplate(ConstructorD);
4790
4791 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004792 if (!Constructor)
4793 return;
4794
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004795 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004796 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004797 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004798 Results.EnterNewScope();
4799
4800 // Fill in any already-initialized fields or base classes.
4801 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4802 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004803 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004804 if (Initializers[I]->isBaseInitializer())
4805 InitializedBases.insert(
4806 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4807 else
Francois Pichetd583da02010-12-04 09:14:42 +00004808 InitializedFields.insert(cast<FieldDecl>(
4809 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004810 }
4811
4812 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004813 CodeCompletionBuilder Builder(Results.getAllocator(),
4814 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004815 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004816 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004817 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004818 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004819 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4820 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004821 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004822 = !Initializers.empty() &&
4823 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004824 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004825 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004826 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004827 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004828
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004829 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004830 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004831 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4833 Builder.AddPlaceholderChunk("args");
4834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4835 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004836 SawLastInitializer? CCP_NextInitializer
4837 : CCP_MemberDeclaration));
4838 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004839 }
4840
4841 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004842 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004843 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4844 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004845 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004846 = !Initializers.empty() &&
4847 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004848 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004849 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004850 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004851 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004852
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004853 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004854 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004855 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004856 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4857 Builder.AddPlaceholderChunk("args");
4858 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4859 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004860 SawLastInitializer? CCP_NextInitializer
4861 : CCP_MemberDeclaration));
4862 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004863 }
4864
4865 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004866 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004867 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4868 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004869 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004870 = !Initializers.empty() &&
4871 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004872 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004873 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004874 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004875
4876 if (!Field->getDeclName())
4877 continue;
4878
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004879 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004880 Field->getIdentifier()->getName()));
4881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4882 Builder.AddPlaceholderChunk("args");
4883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4884 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004885 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004886 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004887 CXCursor_MemberRef,
4888 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004889 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004890 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004891 }
4892 Results.ExitScope();
4893
Douglas Gregor0ac41382010-09-23 23:01:17 +00004894 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004895 Results.data(), Results.size());
4896}
4897
Douglas Gregord8c61782012-02-15 15:34:24 +00004898/// \brief Determine whether this scope denotes a namespace.
4899static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004900 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004901 if (!DC)
4902 return false;
4903
4904 return DC->isFileContext();
4905}
4906
4907void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4908 bool AfterAmpersand) {
4909 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004910 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004911 CodeCompletionContext::CCC_Other);
4912 Results.EnterNewScope();
4913
4914 // Note what has already been captured.
4915 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4916 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004917 for (const auto &C : Intro.Captures) {
4918 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004919 IncludedThis = true;
4920 continue;
4921 }
4922
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004923 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004924 }
4925
4926 // Look for other capturable variables.
4927 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004928 for (const auto *D : S->decls()) {
4929 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004930 if (!Var ||
4931 !Var->hasLocalStorage() ||
4932 Var->hasAttr<BlocksAttr>())
4933 continue;
4934
David Blaikie82e95a32014-11-19 07:49:47 +00004935 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004936 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004937 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004938 }
4939 }
4940
4941 // Add 'this', if it would be valid.
4942 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4943 addThisCompletion(*this, Results);
4944
4945 Results.ExitScope();
4946
4947 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4948 Results.data(), Results.size());
4949}
4950
James Dennett596e4752012-06-14 03:11:41 +00004951/// Macro that optionally prepends an "@" to the string literal passed in via
4952/// Keyword, depending on whether NeedAt is true or false.
4953#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4954
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004955static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004956 ResultBuilder &Results,
4957 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004958 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004959 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004960 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004961
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004962 CodeCompletionBuilder Builder(Results.getAllocator(),
4963 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004964 if (LangOpts.ObjC2) {
4965 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004966 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004967 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4968 Builder.AddPlaceholderChunk("property");
4969 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004970
4971 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004972 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004973 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4974 Builder.AddPlaceholderChunk("property");
4975 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004976 }
4977}
4978
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004979static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004980 ResultBuilder &Results,
4981 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004982 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004983
4984 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004985 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004986
4987 if (LangOpts.ObjC2) {
4988 // @property
James Dennett596e4752012-06-14 03:11:41 +00004989 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004990
4991 // @required
James Dennett596e4752012-06-14 03:11:41 +00004992 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004993
4994 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004995 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004996 }
4997}
4998
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004999static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005000 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005001 CodeCompletionBuilder Builder(Results.getAllocator(),
5002 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00005003
5004 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00005005 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005006 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5007 Builder.AddPlaceholderChunk("name");
5008 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005009
Douglas Gregorf4c33342010-05-28 00:22:41 +00005010 if (Results.includeCodePatterns()) {
5011 // @interface name
5012 // FIXME: Could introduce the whole pattern, including superclasses and
5013 // such.
James Dennett596e4752012-06-14 03:11:41 +00005014 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005015 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5016 Builder.AddPlaceholderChunk("class");
5017 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005018
Douglas Gregorf4c33342010-05-28 00:22:41 +00005019 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00005020 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005021 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5022 Builder.AddPlaceholderChunk("protocol");
5023 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005024
5025 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00005026 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005027 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5028 Builder.AddPlaceholderChunk("class");
5029 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005030 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005031
5032 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00005033 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005034 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5035 Builder.AddPlaceholderChunk("alias");
5036 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5037 Builder.AddPlaceholderChunk("class");
5038 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00005039
5040 if (Results.getSema().getLangOpts().Modules) {
5041 // @import name
5042 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5044 Builder.AddPlaceholderChunk("module");
5045 Results.AddResult(Result(Builder.TakeString()));
5046 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005047}
5048
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005049void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005050 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005051 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005052 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005053 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005054 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00005055 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005056 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00005057 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00005058 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005059 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005060 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005061 HandleCodeCompleteResults(this, CodeCompleter,
5062 CodeCompletionContext::CCC_Other,
5063 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00005064}
5065
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005066static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005067 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005068 CodeCompletionBuilder Builder(Results.getAllocator(),
5069 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005070
5071 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005072 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00005073 if (Results.getSema().getLangOpts().CPlusPlus ||
5074 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00005075 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00005076 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00005077 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5079 Builder.AddPlaceholderChunk("type-name");
5080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5081 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005082
5083 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005084 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00005085 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5087 Builder.AddPlaceholderChunk("protocol-name");
5088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5089 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005090
5091 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005092 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00005093 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005094 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5095 Builder.AddPlaceholderChunk("selector");
5096 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5097 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005098
5099 // @"string"
5100 Builder.AddResultTypeChunk("NSString *");
5101 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5102 Builder.AddPlaceholderChunk("string");
5103 Builder.AddTextChunk("\"");
5104 Results.AddResult(Result(Builder.TakeString()));
5105
Douglas Gregor951de302012-07-17 23:24:47 +00005106 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00005107 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00005108 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005109 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005110 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5111 Results.AddResult(Result(Builder.TakeString()));
5112
Douglas Gregor951de302012-07-17 23:24:47 +00005113 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00005114 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00005115 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005116 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005117 Builder.AddChunk(CodeCompletionString::CK_Colon);
5118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5119 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005120 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5121 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005122
Douglas Gregor951de302012-07-17 23:24:47 +00005123 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00005124 Builder.AddResultTypeChunk("id");
5125 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00005126 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00005127 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5128 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005129}
5130
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005131static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005132 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005133 CodeCompletionBuilder Builder(Results.getAllocator(),
5134 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00005135
Douglas Gregorf4c33342010-05-28 00:22:41 +00005136 if (Results.includeCodePatterns()) {
5137 // @try { statements } @catch ( declaration ) { statements } @finally
5138 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00005139 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005140 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5141 Builder.AddPlaceholderChunk("statements");
5142 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5143 Builder.AddTextChunk("@catch");
5144 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5145 Builder.AddPlaceholderChunk("parameter");
5146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5147 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5148 Builder.AddPlaceholderChunk("statements");
5149 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5150 Builder.AddTextChunk("@finally");
5151 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5152 Builder.AddPlaceholderChunk("statements");
5153 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5154 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005155 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005156
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005157 // @throw
James Dennett596e4752012-06-14 03:11:41 +00005158 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005159 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5160 Builder.AddPlaceholderChunk("expression");
5161 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005162
Douglas Gregorf4c33342010-05-28 00:22:41 +00005163 if (Results.includeCodePatterns()) {
5164 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00005165 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005166 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5167 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5168 Builder.AddPlaceholderChunk("expression");
5169 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5170 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5171 Builder.AddPlaceholderChunk("statements");
5172 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5173 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005174 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005175}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005176
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005177static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00005178 ResultBuilder &Results,
5179 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005180 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00005181 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5182 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5183 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005184 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00005185 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005186}
5187
5188void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005189 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005190 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005191 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00005192 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005193 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00005194 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005195 HandleCodeCompleteResults(this, CodeCompleter,
5196 CodeCompletionContext::CCC_Other,
5197 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00005198}
5199
5200void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005201 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005202 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005203 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00005204 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005205 AddObjCStatementResults(Results, false);
5206 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005207 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005208 HandleCodeCompleteResults(this, CodeCompleter,
5209 CodeCompletionContext::CCC_Other,
5210 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005211}
5212
5213void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005214 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005215 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005216 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005217 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005218 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005219 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005220 HandleCodeCompleteResults(this, CodeCompleter,
5221 CodeCompletionContext::CCC_Other,
5222 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005223}
5224
Douglas Gregore6078da2009-11-19 00:14:45 +00005225/// \brief Determine whether the addition of the given flag to an Objective-C
5226/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00005227static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00005228 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00005229 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00005230 return true;
5231
Bill Wendling44426052012-12-20 19:22:21 +00005232 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00005233
5234 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00005235 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5236 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00005237 return true;
5238
Jordan Rose53cb2f32012-08-20 20:01:13 +00005239 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00005240 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00005241 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00005242 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00005243 ObjCDeclSpec::DQ_PR_retain |
5244 ObjCDeclSpec::DQ_PR_strong |
5245 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00005246 if (AssignCopyRetMask &&
5247 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00005248 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00005249 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00005250 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00005251 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5252 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00005253 return true;
5254
5255 return false;
5256}
5257
Douglas Gregor36029f42009-11-18 23:08:07 +00005258void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00005259 if (!CodeCompleter)
5260 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005261
Bill Wendling44426052012-12-20 19:22:21 +00005262 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00005263
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005264 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005265 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005266 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00005267 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00005268 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00005269 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00005270 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00005271 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00005272 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00005273 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5274 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00005275 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00005276 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00005277 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00005278 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00005279 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00005280 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00005281 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00005282 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00005283 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00005284 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00005285 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00005286 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00005287
5288 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00005289 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00005290 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00005291 Results.AddResult(CodeCompletionResult("weak"));
5292
Bill Wendling44426052012-12-20 19:22:21 +00005293 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005294 CodeCompletionBuilder Setter(Results.getAllocator(),
5295 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005296 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005297 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005298 Setter.AddPlaceholderChunk("method");
5299 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005300 }
Bill Wendling44426052012-12-20 19:22:21 +00005301 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005302 CodeCompletionBuilder Getter(Results.getAllocator(),
5303 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005304 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005305 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005306 Getter.AddPlaceholderChunk("method");
5307 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005308 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005309 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5310 Results.AddResult(CodeCompletionResult("nonnull"));
5311 Results.AddResult(CodeCompletionResult("nullable"));
5312 Results.AddResult(CodeCompletionResult("null_unspecified"));
5313 Results.AddResult(CodeCompletionResult("null_resettable"));
5314 }
Steve Naroff936354c2009-10-08 21:55:05 +00005315 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005316 HandleCodeCompleteResults(this, CodeCompleter,
5317 CodeCompletionContext::CCC_Other,
5318 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00005319}
Steve Naroffeae65032009-11-07 02:08:14 +00005320
James Dennettf1243872012-06-17 05:33:25 +00005321/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00005322/// via code completion.
5323enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00005324 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5325 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5326 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005327};
5328
Douglas Gregor67c692c2010-08-26 15:07:07 +00005329static bool isAcceptableObjCSelector(Selector Sel,
5330 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005331 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005332 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005333 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00005334 if (NumSelIdents > Sel.getNumArgs())
5335 return false;
5336
5337 switch (WantKind) {
5338 case MK_Any: break;
5339 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5340 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5341 }
5342
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005343 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5344 return false;
5345
Douglas Gregor67c692c2010-08-26 15:07:07 +00005346 for (unsigned I = 0; I != NumSelIdents; ++I)
5347 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5348 return false;
5349
5350 return true;
5351}
5352
Douglas Gregorc8537c52009-11-19 07:41:15 +00005353static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5354 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005355 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005356 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005357 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005358 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005359}
Douglas Gregor1154e272010-09-16 16:06:31 +00005360
5361namespace {
5362 /// \brief A set of selectors, which is used to avoid introducing multiple
5363 /// completions with the same selector into the result set.
5364 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5365}
5366
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005367/// \brief Add all of the Objective-C methods in the given Objective-C
5368/// container to the set of results.
5369///
5370/// The container will be a class, protocol, category, or implementation of
5371/// any of the above. This mether will recurse to include methods from
5372/// the superclasses of classes along with their categories, protocols, and
5373/// implementations.
5374///
5375/// \param Container the container in which we'll look to find methods.
5376///
James Dennett596e4752012-06-14 03:11:41 +00005377/// \param WantInstanceMethods Whether to add instance methods (only); if
5378/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005379///
5380/// \param CurContext the context in which we're performing the lookup that
5381/// finds methods.
5382///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005383/// \param AllowSameLength Whether we allow a method to be added to the list
5384/// when it has the same number of parameters as we have selector identifiers.
5385///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005386/// \param Results the structure into which we'll add results.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005387static void AddObjCMethods(ObjCContainerDecl *Container,
5388 bool WantInstanceMethods, ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005389 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005390 DeclContext *CurContext,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005391 VisitedSelectorSet &Selectors, bool AllowSameLength,
5392 ResultBuilder &Results, bool InOriginalClass = true,
5393 bool IsRootClass = false) {
John McCall276321a2010-08-25 06:19:51 +00005394 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005395 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005396 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Alex Lorenz638dbc32017-01-24 14:15:08 +00005397 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005398 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005399 // The instance methods on the root class can be messaged via the
5400 // metaclass.
5401 if (M->isInstanceMethod() == WantInstanceMethods ||
Alex Lorenz638dbc32017-01-24 14:15:08 +00005402 (IsRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005403 // Check whether the selector identifiers we've been given are a
5404 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005405 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005406 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005407
David Blaikie82e95a32014-11-19 07:49:47 +00005408 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005409 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005410
5411 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005412 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005413 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005414 if (!InOriginalClass)
5415 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005416 Results.MaybeAddResult(R, CurContext);
5417 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005418 }
5419
Douglas Gregorf37c9492010-09-16 15:34:59 +00005420 // Visit the protocols of protocols.
5421 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005422 if (Protocol->hasDefinition()) {
5423 const ObjCList<ObjCProtocolDecl> &Protocols
5424 = Protocol->getReferencedProtocols();
5425 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5426 E = Protocols.end();
5427 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005428 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5429 Selectors, AllowSameLength, Results, false, IsRootClass);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005430 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005431 }
5432
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005433 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005434 return;
5435
5436 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005437 for (auto *I : IFace->protocols())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005438 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5439 Selectors, AllowSameLength, Results, false, IsRootClass);
5440
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005441 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005442 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005443 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005444 CurContext, Selectors, AllowSameLength, Results,
5445 InOriginalClass, IsRootClass);
5446
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005447 // Add a categories protocol methods.
5448 const ObjCList<ObjCProtocolDecl> &Protocols
5449 = CatDecl->getReferencedProtocols();
5450 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5451 E = Protocols.end();
5452 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005453 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5454 Selectors, AllowSameLength, Results, false, IsRootClass);
5455
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005456 // Add methods in category implementations.
5457 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005458 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5459 Selectors, AllowSameLength, Results, InOriginalClass,
5460 IsRootClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005461 }
5462
5463 // Add methods in superclass.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005464 // Avoid passing in IsRootClass since root classes won't have super classes.
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005465 if (IFace->getSuperClass())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005466 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5467 SelIdents, CurContext, Selectors, AllowSameLength, Results,
5468 /*IsRootClass=*/false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005469
5470 // Add methods in our implementation, if any.
5471 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005472 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5473 Selectors, AllowSameLength, Results, InOriginalClass,
5474 IsRootClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005475}
5476
5477
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005478void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005479 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005480 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005481 if (!Class) {
5482 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005483 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005484 Class = Category->getClassInterface();
5485
5486 if (!Class)
5487 return;
5488 }
5489
5490 // Find all of the potential getters.
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_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005494 Results.EnterNewScope();
5495
Douglas Gregor1154e272010-09-16 16:06:31 +00005496 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005497 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005498 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005499 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005500 HandleCodeCompleteResults(this, CodeCompleter,
5501 CodeCompletionContext::CCC_Other,
5502 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005503}
5504
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005505void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005506 // Try to find the interface where setters might live.
5507 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005508 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005509 if (!Class) {
5510 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005511 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005512 Class = Category->getClassInterface();
5513
5514 if (!Class)
5515 return;
5516 }
5517
5518 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005519 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005520 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005521 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005522 Results.EnterNewScope();
5523
Douglas Gregor1154e272010-09-16 16:06:31 +00005524 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005525 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005526 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005527
5528 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005529 HandleCodeCompleteResults(this, CodeCompleter,
5530 CodeCompletionContext::CCC_Other,
5531 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005532}
5533
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005534void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5535 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005536 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005537 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005538 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005539 Results.EnterNewScope();
5540
5541 // Add context-sensitive, Objective-C parameter-passing keywords.
5542 bool AddedInOut = false;
5543 if ((DS.getObjCDeclQualifier() &
5544 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5545 Results.AddResult("in");
5546 Results.AddResult("inout");
5547 AddedInOut = true;
5548 }
5549 if ((DS.getObjCDeclQualifier() &
5550 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5551 Results.AddResult("out");
5552 if (!AddedInOut)
5553 Results.AddResult("inout");
5554 }
5555 if ((DS.getObjCDeclQualifier() &
5556 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5557 ObjCDeclSpec::DQ_Oneway)) == 0) {
5558 Results.AddResult("bycopy");
5559 Results.AddResult("byref");
5560 Results.AddResult("oneway");
5561 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005562 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5563 Results.AddResult("nonnull");
5564 Results.AddResult("nullable");
5565 Results.AddResult("null_unspecified");
5566 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005567
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005568 // If we're completing the return type of an Objective-C method and the
5569 // identifier IBAction refers to a macro, provide a completion item for
5570 // an action, e.g.,
5571 // IBAction)<#selector#>:(id)sender
5572 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005573 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005574 CodeCompletionBuilder Builder(Results.getAllocator(),
5575 Results.getCodeCompletionTUInfo(),
5576 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005577 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005578 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005579 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005580 Builder.AddChunk(CodeCompletionString::CK_Colon);
5581 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005582 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005583 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005584 Builder.AddTextChunk("sender");
5585 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5586 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005587
5588 // If we're completing the return type, provide 'instancetype'.
5589 if (!IsParameter) {
5590 Results.AddResult(CodeCompletionResult("instancetype"));
5591 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005592
Douglas Gregor99fa2642010-08-24 01:06:58 +00005593 // Add various builtin type names and specifiers.
5594 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5595 Results.ExitScope();
5596
5597 // Add the various type names
5598 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5599 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5600 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5601 CodeCompleter->includeGlobals());
5602
5603 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005604 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005605
5606 HandleCodeCompleteResults(this, CodeCompleter,
5607 CodeCompletionContext::CCC_Type,
5608 Results.data(), Results.size());
5609}
5610
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005611/// \brief When we have an expression with type "id", we may assume
5612/// that it has some more-specific class type based on knowledge of
5613/// common uses of Objective-C. This routine returns that class type,
5614/// or NULL if no better result could be determined.
5615static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005616 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005617 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005618 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005619
5620 Selector Sel = Msg->getSelector();
5621 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005622 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005623
5624 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5625 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005626 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005627
5628 ObjCMethodDecl *Method = Msg->getMethodDecl();
5629 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005630 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005631
5632 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005633 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005634 switch (Msg->getReceiverKind()) {
5635 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005636 if (const ObjCObjectType *ObjType
5637 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5638 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005639 break;
5640
5641 case ObjCMessageExpr::Instance: {
5642 QualType T = Msg->getInstanceReceiver()->getType();
5643 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5644 IFace = Ptr->getInterfaceDecl();
5645 break;
5646 }
5647
5648 case ObjCMessageExpr::SuperInstance:
5649 case ObjCMessageExpr::SuperClass:
5650 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005651 }
5652
5653 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005654 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005655
5656 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5657 if (Method->isInstanceMethod())
5658 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5659 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005660 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005661 .Case("autorelease", IFace)
5662 .Case("copy", IFace)
5663 .Case("copyWithZone", IFace)
5664 .Case("mutableCopy", IFace)
5665 .Case("mutableCopyWithZone", IFace)
5666 .Case("awakeFromCoder", IFace)
5667 .Case("replacementObjectFromCoder", IFace)
5668 .Case("class", IFace)
5669 .Case("classForCoder", IFace)
5670 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005671 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005672
5673 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5674 .Case("new", IFace)
5675 .Case("alloc", IFace)
5676 .Case("allocWithZone", IFace)
5677 .Case("class", IFace)
5678 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005679 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005680}
5681
Douglas Gregor6fc04132010-08-27 15:10:57 +00005682// Add a special completion for a message send to "super", which fills in the
5683// most likely case of forwarding all of our arguments to the superclass
5684// function.
5685///
5686/// \param S The semantic analysis object.
5687///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005688/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005689/// the "super" keyword. Otherwise, we just need to provide the arguments.
5690///
5691/// \param SelIdents The identifiers in the selector that have already been
5692/// provided as arguments for a send to "super".
5693///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005694/// \param Results The set of results to augment.
5695///
5696/// \returns the Objective-C method declaration that would be invoked by
5697/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005698static ObjCMethodDecl *AddSuperSendCompletion(
5699 Sema &S, bool NeedSuperKeyword,
5700 ArrayRef<IdentifierInfo *> SelIdents,
5701 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005702 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5703 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005704 return nullptr;
5705
Douglas Gregor6fc04132010-08-27 15:10:57 +00005706 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5707 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005708 return nullptr;
5709
Douglas Gregor6fc04132010-08-27 15:10:57 +00005710 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005711 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005712 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5713 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005714 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5715 CurMethod->isInstanceMethod());
5716
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005717 // Check in categories or class extensions.
5718 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005719 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005720 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005721 CurMethod->isInstanceMethod())))
5722 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005723 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005724 }
5725 }
5726
Douglas Gregor6fc04132010-08-27 15:10:57 +00005727 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005728 return nullptr;
5729
Douglas Gregor6fc04132010-08-27 15:10:57 +00005730 // Check whether the superclass method has the same signature.
5731 if (CurMethod->param_size() != SuperMethod->param_size() ||
5732 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005733 return nullptr;
5734
Douglas Gregor6fc04132010-08-27 15:10:57 +00005735 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5736 CurPEnd = CurMethod->param_end(),
5737 SuperP = SuperMethod->param_begin();
5738 CurP != CurPEnd; ++CurP, ++SuperP) {
5739 // Make sure the parameter types are compatible.
5740 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5741 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005742 return nullptr;
5743
Douglas Gregor6fc04132010-08-27 15:10:57 +00005744 // Make sure we have a parameter name to forward!
5745 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005746 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005747 }
5748
5749 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005750 CodeCompletionBuilder Builder(Results.getAllocator(),
5751 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005752
5753 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005754 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5755 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005756 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005757
5758 // If we need the "super" keyword, add it (plus some spacing).
5759 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005760 Builder.AddTypedTextChunk("super");
5761 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005762 }
5763
5764 Selector Sel = CurMethod->getSelector();
5765 if (Sel.isUnarySelector()) {
5766 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005767 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005768 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005769 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005770 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005771 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005772 } else {
5773 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5774 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005775 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005776 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005777
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005778 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005779 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005780 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005781 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005782 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005783 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005784 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005785 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005786 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005787 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005788 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005789 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005790 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005791 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005792 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005793 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005794 }
5795 }
5796 }
5797
Douglas Gregor78254c82012-03-27 23:34:16 +00005798 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5799 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005800 return SuperMethod;
5801}
5802
Douglas Gregora817a192010-05-27 23:06:34 +00005803void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005804 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005805 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005806 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005807 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005808 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005809 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5810 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005811
Douglas Gregora817a192010-05-27 23:06:34 +00005812 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5813 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005814 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5815 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005816
5817 // If we are in an Objective-C method inside a class that has a superclass,
5818 // add "super" as an option.
5819 if (ObjCMethodDecl *Method = getCurMethodDecl())
5820 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005821 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005822 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005823
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005824 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005825 }
Douglas Gregora817a192010-05-27 23:06:34 +00005826
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005827 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005828 addThisCompletion(*this, Results);
5829
Douglas Gregora817a192010-05-27 23:06:34 +00005830 Results.ExitScope();
5831
5832 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005833 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005834 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005835 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005836
5837}
5838
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005839void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005840 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005841 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005842 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005843 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5844 // Figure out which interface we're in.
5845 CDecl = CurMethod->getClassInterface();
5846 if (!CDecl)
5847 return;
5848
5849 // Find the superclass of this class.
5850 CDecl = CDecl->getSuperClass();
5851 if (!CDecl)
5852 return;
5853
5854 if (CurMethod->isInstanceMethod()) {
5855 // We are inside an instance method, which means that the message
5856 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005857 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005858 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005859 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005860 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005861 }
5862
5863 // Fall through to send to the superclass in CDecl.
5864 } else {
5865 // "super" may be the name of a type or variable. Figure out which
5866 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005867 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005868 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5869 LookupOrdinaryName);
5870 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5871 // "super" names an interface. Use it.
5872 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005873 if (const ObjCObjectType *Iface
5874 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5875 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005876 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5877 // "super" names an unresolved type; we can't be more specific.
5878 } else {
5879 // Assume that "super" names some kind of value and parse that way.
5880 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005881 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005882 UnqualifiedId id;
5883 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005884 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5885 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005886 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005887 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005888 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005889 }
5890
5891 // Fall through
5892 }
5893
John McCallba7bf592010-08-24 05:47:05 +00005894 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005895 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005896 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005897 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005898 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005899 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005900}
5901
Douglas Gregor74661272010-09-21 00:03:25 +00005902/// \brief Given a set of code-completion results for the argument of a message
5903/// send, determine the preferred type (if any) for that argument expression.
5904static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5905 unsigned NumSelIdents) {
5906 typedef CodeCompletionResult Result;
5907 ASTContext &Context = Results.getSema().Context;
5908
5909 QualType PreferredType;
5910 unsigned BestPriority = CCP_Unlikely * 2;
5911 Result *ResultsData = Results.data();
5912 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5913 Result &R = ResultsData[I];
5914 if (R.Kind == Result::RK_Declaration &&
5915 isa<ObjCMethodDecl>(R.Declaration)) {
5916 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005917 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005918 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005919 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005920 ->getType();
5921 if (R.Priority < BestPriority || PreferredType.isNull()) {
5922 BestPriority = R.Priority;
5923 PreferredType = MyPreferredType;
5924 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5925 MyPreferredType)) {
5926 PreferredType = QualType();
5927 }
5928 }
5929 }
5930 }
5931 }
5932
5933 return PreferredType;
5934}
5935
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005936static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5937 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005938 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005939 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005940 bool IsSuper,
5941 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005942 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005943 ObjCInterfaceDecl *CDecl = nullptr;
5944
Douglas Gregor8ce33212009-11-17 17:59:40 +00005945 // If the given name refers to an interface type, retrieve the
5946 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005947 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005948 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005949 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005950 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5951 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005952 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005953
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005954 // Add all of the factory methods in this Objective-C class, its protocols,
5955 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005956 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005957
Douglas Gregor6fc04132010-08-27 15:10:57 +00005958 // If this is a send-to-super, try to add the special "super" send
5959 // completion.
5960 if (IsSuper) {
5961 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005962 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005963 Results.Ignore(SuperMethod);
5964 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005965
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005966 // If we're inside an Objective-C method definition, prefer its selector to
5967 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005968 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005969 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005970
Douglas Gregor1154e272010-09-16 16:06:31 +00005971 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005972 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005973 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005974 SemaRef.CurContext, Selectors, AtArgumentExpression,
5975 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005976 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005977 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005978
Douglas Gregord720daf2010-04-06 17:30:22 +00005979 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005980 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005981 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005982 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005983 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005984 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005985 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005986 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005987 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005988
5989 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005990 }
5991 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005992
5993 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5994 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005995 M != MEnd; ++M) {
5996 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005997 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005998 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005999 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00006000 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00006001
Nico Weber2e0c8f72014-12-27 03:58:08 +00006002 Result R(MethList->getMethod(),
6003 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006004 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006005 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006006 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00006007 }
6008 }
6009 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006010
6011 Results.ExitScope();
6012}
Douglas Gregor6285f752010-04-06 16:40:00 +00006013
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006014void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006015 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006016 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006017 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00006018
6019 QualType T = this->GetTypeFromParser(Receiver);
6020
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006021 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006022 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006023 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006024 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006025
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006026 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006027 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00006028
6029 // If we're actually at the argument expression (rather than prior to the
6030 // selector), we're actually performing code completion for an expression.
6031 // Determine whether we have a single, best method. If so, we can
6032 // code-complete the expression using the corresponding parameter type as
6033 // our preferred type, improving completion results.
6034 if (AtArgumentExpression) {
6035 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006036 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006037 if (PreferredType.isNull())
6038 CodeCompleteOrdinaryName(S, PCC_Expression);
6039 else
6040 CodeCompleteExpression(S, PreferredType);
6041 return;
6042 }
6043
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006044 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006045 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00006046 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006047}
6048
Richard Trieu2bd04012011-09-09 02:00:50 +00006049void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006050 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006051 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00006052 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00006053 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00006054
6055 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00006056
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006057 // If necessary, apply function/array conversion to the receiver.
6058 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00006059 if (RecExpr) {
6060 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6061 if (Conv.isInvalid()) // conversion failed. bail.
6062 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006063 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00006064 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00006065 QualType ReceiverType = RecExpr? RecExpr->getType()
6066 : Super? Context.getObjCObjectPointerType(
6067 Context.getObjCInterfaceType(Super))
6068 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00006069
Douglas Gregordc520b02010-11-08 21:12:30 +00006070 // If we're messaging an expression with type "id" or "Class", check
6071 // whether we know something special about the receiver that allows
6072 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00006073 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00006074 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6075 if (ReceiverType->isObjCClassType())
6076 return CodeCompleteObjCClassMessage(S,
6077 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006078 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00006079 AtArgumentExpression, Super);
6080
6081 ReceiverType = Context.getObjCObjectPointerType(
6082 Context.getObjCInterfaceType(IFace));
6083 }
Anders Carlsson382ba412014-02-28 19:07:22 +00006084 } else if (RecExpr && getLangOpts().CPlusPlus) {
6085 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6086 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006087 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00006088 ReceiverType = RecExpr->getType();
6089 }
6090 }
Douglas Gregordc520b02010-11-08 21:12:30 +00006091
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006092 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006093 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006094 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006095 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006096 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006097
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006098 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00006099
Douglas Gregor6fc04132010-08-27 15:10:57 +00006100 // If this is a send-to-super, try to add the special "super" send
6101 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00006102 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00006103 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006104 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00006105 Results.Ignore(SuperMethod);
6106 }
6107
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00006108 // If we're inside an Objective-C method definition, prefer its selector to
6109 // others.
6110 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6111 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006112
Douglas Gregor1154e272010-09-16 16:06:31 +00006113 // Keep track of the selectors we've already added.
6114 VisitedSelectorSet Selectors;
6115
Douglas Gregora3329fa2009-11-18 00:06:18 +00006116 // Handle messages to Class. This really isn't a message to an instance
6117 // method, so we treat it the same way we would treat a message send to a
6118 // class method.
6119 if (ReceiverType->isObjCClassType() ||
6120 ReceiverType->isObjCQualifiedClassType()) {
6121 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6122 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006123 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006124 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006125 }
6126 }
6127 // Handle messages to a qualified ID ("id<foo>").
6128 else if (const ObjCObjectPointerType *QualID
6129 = ReceiverType->getAsObjCQualifiedIdType()) {
6130 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006131 for (auto *I : QualID->quals())
6132 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006133 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006134 }
6135 // Handle messages to a pointer to interface type.
6136 else if (const ObjCObjectPointerType *IFacePtr
6137 = ReceiverType->getAsObjCInterfacePointerType()) {
6138 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00006139 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006140 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006141 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006142
6143 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006144 for (auto *I : IFacePtr->quals())
6145 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006146 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006147 }
Douglas Gregor6285f752010-04-06 16:40:00 +00006148 // Handle messages to "id".
6149 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00006150 // We're messaging "id", so provide all instance methods we know
6151 // about as code-completion results.
6152
6153 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006154 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00006155 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00006156 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6157 I != N; ++I) {
6158 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006159 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00006160 continue;
6161
Sebastian Redl75d8a322010-08-02 23:18:59 +00006162 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00006163 }
6164 }
6165
Sebastian Redl75d8a322010-08-02 23:18:59 +00006166 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6167 MEnd = MethodPool.end();
6168 M != MEnd; ++M) {
6169 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00006170 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006171 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00006172 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00006173 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00006174
Nico Weber2e0c8f72014-12-27 03:58:08 +00006175 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00006176 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00006177
Nico Weber2e0c8f72014-12-27 03:58:08 +00006178 Result R(MethList->getMethod(),
6179 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006180 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006181 R.AllParametersAreInformative = false;
6182 Results.MaybeAddResult(R, CurContext);
6183 }
6184 }
6185 }
Steve Naroffeae65032009-11-07 02:08:14 +00006186 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00006187
6188
6189 // If we're actually at the argument expression (rather than prior to the
6190 // selector), we're actually performing code completion for an expression.
6191 // Determine whether we have a single, best method. If so, we can
6192 // code-complete the expression using the corresponding parameter type as
6193 // our preferred type, improving completion results.
6194 if (AtArgumentExpression) {
6195 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006196 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006197 if (PreferredType.isNull())
6198 CodeCompleteOrdinaryName(S, PCC_Expression);
6199 else
6200 CodeCompleteExpression(S, PreferredType);
6201 return;
6202 }
6203
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006204 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006205 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006206 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006207}
Douglas Gregorbaf69612009-11-18 04:19:12 +00006208
Douglas Gregor68762e72010-08-23 21:17:50 +00006209void Sema::CodeCompleteObjCForCollection(Scope *S,
6210 DeclGroupPtrTy IterationVar) {
6211 CodeCompleteExpressionData Data;
6212 Data.ObjCCollection = true;
6213
6214 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00006215 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00006216 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6217 if (*I)
6218 Data.IgnoreDecls.push_back(*I);
6219 }
6220 }
6221
6222 CodeCompleteExpression(S, Data);
6223}
6224
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006225void Sema::CodeCompleteObjCSelector(Scope *S,
6226 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00006227 // If we have an external source, load the entire class method
6228 // pool from the AST file.
6229 if (ExternalSource) {
6230 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6231 I != N; ++I) {
6232 Selector Sel = ExternalSource->GetExternalSelector(I);
6233 if (Sel.isNull() || MethodPool.count(Sel))
6234 continue;
6235
6236 ReadMethodPool(Sel);
6237 }
6238 }
6239
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006240 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006241 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006242 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00006243 Results.EnterNewScope();
6244 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6245 MEnd = MethodPool.end();
6246 M != MEnd; ++M) {
6247
6248 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006249 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00006250 continue;
6251
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006252 CodeCompletionBuilder Builder(Results.getAllocator(),
6253 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006254 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006255 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006256 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006257 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006258 continue;
6259 }
6260
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006261 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00006262 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006263 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006264 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006265 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006266 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006267 Accumulator.clear();
6268 }
6269 }
6270
Benjamin Kramer632500c2011-07-26 16:59:25 +00006271 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006272 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00006273 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006274 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006275 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006276 }
6277 Results.ExitScope();
6278
6279 HandleCodeCompleteResults(this, CodeCompleter,
6280 CodeCompletionContext::CCC_SelectorName,
6281 Results.data(), Results.size());
6282}
6283
Douglas Gregorbaf69612009-11-18 04:19:12 +00006284/// \brief Add all of the protocol declarations that we find in the given
6285/// (translation unit) context.
6286static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006287 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00006288 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006289 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00006290
Aaron Ballman629afae2014-03-07 19:56:05 +00006291 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00006292 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006293 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00006294 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00006295 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6296 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006297 }
6298}
6299
Craig Topper883dd332015-12-24 23:58:11 +00006300void Sema::CodeCompleteObjCProtocolReferences(
6301 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006302 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006303 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006304 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006305
Chandler Carruthede11632016-11-04 06:06:50 +00006306 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006307 Results.EnterNewScope();
6308
6309 // Tell the result set to ignore all of the protocols we have
6310 // already seen.
6311 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00006312 for (const IdentifierLocPair &Pair : Protocols)
6313 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6314 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00006315 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006316
Douglas Gregora3b23b02010-12-09 21:44:02 +00006317 // Add all protocols.
6318 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6319 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006320
Douglas Gregora3b23b02010-12-09 21:44:02 +00006321 Results.ExitScope();
6322 }
6323
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006324 HandleCodeCompleteResults(this, CodeCompleter,
6325 CodeCompletionContext::CCC_ObjCProtocolName,
6326 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006327}
6328
6329void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006330 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006331 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006332 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006333
Chandler Carruthede11632016-11-04 06:06:50 +00006334 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006335 Results.EnterNewScope();
6336
6337 // Add all protocols.
6338 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6339 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006340
Douglas Gregora3b23b02010-12-09 21:44:02 +00006341 Results.ExitScope();
6342 }
6343
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006344 HandleCodeCompleteResults(this, CodeCompleter,
6345 CodeCompletionContext::CCC_ObjCProtocolName,
6346 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00006347}
Douglas Gregor49c22a72009-11-18 16:26:39 +00006348
6349/// \brief Add all of the Objective-C interface declarations that we find in
6350/// the given (translation unit) context.
6351static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6352 bool OnlyForwardDeclarations,
6353 bool OnlyUnimplemented,
6354 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006355 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00006356
Aaron Ballman629afae2014-03-07 19:56:05 +00006357 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00006358 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006359 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00006360 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00006361 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00006362 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6363 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006364 }
6365}
6366
6367void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006368 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006369 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006370 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006371 Results.EnterNewScope();
6372
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006373 if (CodeCompleter->includeGlobals()) {
6374 // Add all classes.
6375 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6376 false, Results);
6377 }
6378
Douglas Gregor49c22a72009-11-18 16:26:39 +00006379 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006380
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006381 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006382 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006383 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006384}
6385
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006386void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6387 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006388 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006389 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006390 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006391 Results.EnterNewScope();
6392
6393 // Make sure that we ignore the class we're currently defining.
6394 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006395 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006396 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006397 Results.Ignore(CurClass);
6398
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006399 if (CodeCompleter->includeGlobals()) {
6400 // Add all classes.
6401 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6402 false, Results);
6403 }
6404
Douglas Gregor49c22a72009-11-18 16:26:39 +00006405 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006406
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006407 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006408 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006409 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006410}
6411
6412void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006413 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006414 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006415 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006416 Results.EnterNewScope();
6417
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006418 if (CodeCompleter->includeGlobals()) {
6419 // Add all unimplemented classes.
6420 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6421 true, Results);
6422 }
6423
Douglas Gregor49c22a72009-11-18 16:26:39 +00006424 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006425
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006426 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006427 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006428 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006429}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006430
6431void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006432 IdentifierInfo *ClassName,
6433 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006434 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006435
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006436 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006437 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006438 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006439
6440 // Ignore any categories we find that have already been implemented by this
6441 // interface.
6442 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6443 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006444 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006445 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006446 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006447 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006448 }
6449
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006450 // Add all of the categories we know about.
6451 Results.EnterNewScope();
6452 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006453 for (const auto *D : TU->decls())
6454 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006455 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006456 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6457 nullptr),
6458 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006459 Results.ExitScope();
6460
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006461 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006462 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006463 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006464}
6465
6466void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006467 IdentifierInfo *ClassName,
6468 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006469 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006470
6471 // Find the corresponding interface. If we couldn't find the interface, the
6472 // program itself is ill-formed. However, we'll try to be helpful still by
6473 // providing the list of all of the categories we know about.
6474 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006475 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006476 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6477 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006478 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006479
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006480 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006481 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006482 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006483
6484 // Add all of the categories that have have corresponding interface
6485 // declarations in this class and any of its superclasses, except for
6486 // already-implemented categories in the class itself.
6487 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6488 Results.EnterNewScope();
6489 bool IgnoreImplemented = true;
6490 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006491 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006492 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006493 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006494 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6495 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006496 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006497
6498 Class = Class->getSuperClass();
6499 IgnoreImplemented = false;
6500 }
6501 Results.ExitScope();
6502
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006503 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006504 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006505 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006506}
Douglas Gregor5d649882009-11-18 22:32:06 +00006507
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006508void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006509 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006510 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006511 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006512 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006513
6514 // Figure out where this @synthesize lives.
6515 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006516 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006517 if (!Container ||
6518 (!isa<ObjCImplementationDecl>(Container) &&
6519 !isa<ObjCCategoryImplDecl>(Container)))
6520 return;
6521
6522 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006523 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006524 for (const auto *D : Container->decls())
6525 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006526 Results.Ignore(PropertyImpl->getPropertyDecl());
6527
6528 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006529 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006530 Results.EnterNewScope();
6531 if (ObjCImplementationDecl *ClassImpl
6532 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006533 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006534 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006535 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006536 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006537 AddObjCProperties(CCContext,
6538 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006539 false, /*AllowNullaryMethods=*/false, CurContext,
6540 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006541 Results.ExitScope();
6542
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006543 HandleCodeCompleteResults(this, CodeCompleter,
6544 CodeCompletionContext::CCC_Other,
6545 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006546}
6547
6548void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006549 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006550 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006551 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006552 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006553 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006554
6555 // Figure out where this @synthesize lives.
6556 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006557 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006558 if (!Container ||
6559 (!isa<ObjCImplementationDecl>(Container) &&
6560 !isa<ObjCCategoryImplDecl>(Container)))
6561 return;
6562
6563 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006564 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006565 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006566 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006567 Class = ClassImpl->getClassInterface();
6568 else
6569 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6570 ->getClassInterface();
6571
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006572 // Determine the type of the property we're synthesizing.
6573 QualType PropertyType = Context.getObjCIdType();
6574 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006575 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6576 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006577 PropertyType
6578 = Property->getType().getNonReferenceType().getUnqualifiedType();
6579
6580 // Give preference to ivars
6581 Results.setPreferredType(PropertyType);
6582 }
6583 }
6584
Douglas Gregor5d649882009-11-18 22:32:06 +00006585 // Add all of the instance variables in this class and its superclasses.
6586 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006587 bool SawSimilarlyNamedIvar = false;
6588 std::string NameWithPrefix;
6589 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006590 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006591 std::string NameWithSuffix = PropertyName->getName().str();
6592 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006593 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006594 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6595 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006596 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6597 CurContext, nullptr, false);
6598
Douglas Gregor331faa02011-04-18 14:13:53 +00006599 // Determine whether we've seen an ivar with a name similar to the
6600 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006601 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006602 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006603 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006604 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006605
6606 // Reduce the priority of this result by one, to give it a slight
6607 // advantage over other results whose names don't match so closely.
6608 if (Results.size() &&
6609 Results.data()[Results.size() - 1].Kind
6610 == CodeCompletionResult::RK_Declaration &&
6611 Results.data()[Results.size() - 1].Declaration == Ivar)
6612 Results.data()[Results.size() - 1].Priority--;
6613 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006614 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006615 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006616
6617 if (!SawSimilarlyNamedIvar) {
6618 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006619 // an ivar of the appropriate type.
6620 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006621 typedef CodeCompletionResult Result;
6622 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006623 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6624 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006625
Douglas Gregor75acd922011-09-27 23:30:47 +00006626 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006627 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006628 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006629 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6630 Results.AddResult(Result(Builder.TakeString(), Priority,
6631 CXCursor_ObjCIvarDecl));
6632 }
6633
Douglas Gregor5d649882009-11-18 22:32:06 +00006634 Results.ExitScope();
6635
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006636 HandleCodeCompleteResults(this, CodeCompleter,
6637 CodeCompletionContext::CCC_Other,
6638 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006639}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006640
Douglas Gregor416b5752010-08-25 01:08:01 +00006641// Mapping from selectors to the methods that implement that selector, along
6642// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006643typedef llvm::DenseMap<
6644 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006645
6646/// \brief Find all of the methods that reside in the given container
6647/// (and its superclasses, protocols, etc.) that meet the given
6648/// criteria. Insert those methods into the map of known methods,
6649/// indexed by selector so they can be easily found.
6650static void FindImplementableMethods(ASTContext &Context,
6651 ObjCContainerDecl *Container,
Alex Lorenzb8740422017-10-24 16:39:37 +00006652 Optional<bool> WantInstanceMethods,
Douglas Gregor636a61e2010-04-07 00:21:17 +00006653 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006654 KnownMethodsMap &KnownMethods,
6655 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006656 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006657 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006658 if (!IFace->hasDefinition())
6659 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006660
6661 IFace = IFace->getDefinition();
6662 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006663
Douglas Gregor636a61e2010-04-07 00:21:17 +00006664 const ObjCList<ObjCProtocolDecl> &Protocols
6665 = IFace->getReferencedProtocols();
6666 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006667 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006668 I != E; ++I)
6669 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006670 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006671
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006672 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006673 for (auto *Cat : IFace->visible_categories()) {
6674 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006675 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006676 }
6677
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006678 // Visit the superclass.
6679 if (IFace->getSuperClass())
6680 FindImplementableMethods(Context, IFace->getSuperClass(),
6681 WantInstanceMethods, ReturnType,
6682 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006683 }
6684
6685 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6686 // Recurse into protocols.
6687 const ObjCList<ObjCProtocolDecl> &Protocols
6688 = Category->getReferencedProtocols();
6689 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006690 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006691 I != E; ++I)
6692 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006693 KnownMethods, InOriginalClass);
6694
6695 // If this category is the original class, jump to the interface.
6696 if (InOriginalClass && Category->getClassInterface())
6697 FindImplementableMethods(Context, Category->getClassInterface(),
6698 WantInstanceMethods, ReturnType, KnownMethods,
6699 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006700 }
6701
6702 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006703 // Make sure we have a definition; that's what we'll walk.
6704 if (!Protocol->hasDefinition())
6705 return;
6706 Protocol = Protocol->getDefinition();
6707 Container = Protocol;
6708
6709 // Recurse into protocols.
6710 const ObjCList<ObjCProtocolDecl> &Protocols
6711 = Protocol->getReferencedProtocols();
6712 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6713 E = Protocols.end();
6714 I != E; ++I)
6715 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6716 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006717 }
6718
6719 // Add methods in this container. This operation occurs last because
6720 // we want the methods from this container to override any methods
6721 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006722 for (auto *M : Container->methods()) {
Alex Lorenzb8740422017-10-24 16:39:37 +00006723 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006724 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006725 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006726 continue;
6727
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006728 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006729 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006730 }
6731 }
6732}
6733
Douglas Gregor669a25a2011-02-17 00:22:45 +00006734/// \brief Add the parenthesized return or parameter type chunk to a code
6735/// completion string.
6736static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006737 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006738 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006739 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006740 CodeCompletionBuilder &Builder) {
6741 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006742 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006743 if (!Quals.empty())
6744 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006745 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006746 Builder.getAllocator()));
6747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6748}
6749
6750/// \brief Determine whether the given class is or inherits from a class by
6751/// the given name.
6752static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006753 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006754 if (!Class)
6755 return false;
6756
6757 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6758 return true;
6759
6760 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6761}
6762
6763/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6764/// Key-Value Observing (KVO).
6765static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6766 bool IsInstanceMethod,
6767 QualType ReturnType,
6768 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006769 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006770 ResultBuilder &Results) {
6771 IdentifierInfo *PropName = Property->getIdentifier();
6772 if (!PropName || PropName->getLength() == 0)
6773 return;
6774
Douglas Gregor75acd922011-09-27 23:30:47 +00006775 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6776
Douglas Gregor669a25a2011-02-17 00:22:45 +00006777 // Builder that will create each code completion.
6778 typedef CodeCompletionResult Result;
6779 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006780 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006781
6782 // The selector table.
6783 SelectorTable &Selectors = Context.Selectors;
6784
6785 // The property name, copied into the code completion allocation region
6786 // on demand.
6787 struct KeyHolder {
6788 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006789 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006790 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006791
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006792 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006793 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6794
Douglas Gregor669a25a2011-02-17 00:22:45 +00006795 operator const char *() {
6796 if (CopiedKey)
6797 return CopiedKey;
6798
6799 return CopiedKey = Allocator.CopyString(Key);
6800 }
6801 } Key(Allocator, PropName->getName());
6802
6803 // The uppercased name of the property name.
6804 std::string UpperKey = PropName->getName();
6805 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006806 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006807
6808 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6809 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6810 Property->getType());
6811 bool ReturnTypeMatchesVoid
6812 = ReturnType.isNull() || ReturnType->isVoidType();
6813
6814 // Add the normal accessor -(type)key.
6815 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006816 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006817 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6818 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006819 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6820 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006821
6822 Builder.AddTypedTextChunk(Key);
6823 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6824 CXCursor_ObjCInstanceMethodDecl));
6825 }
6826
6827 // If we have an integral or boolean property (or the user has provided
6828 // an integral or boolean return type), add the accessor -(type)isKey.
6829 if (IsInstanceMethod &&
6830 ((!ReturnType.isNull() &&
6831 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6832 (ReturnType.isNull() &&
6833 (Property->getType()->isIntegerType() ||
6834 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006835 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006836 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006837 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6838 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006839 if (ReturnType.isNull()) {
6840 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6841 Builder.AddTextChunk("BOOL");
6842 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6843 }
6844
6845 Builder.AddTypedTextChunk(
6846 Allocator.CopyString(SelectorId->getName()));
6847 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6848 CXCursor_ObjCInstanceMethodDecl));
6849 }
6850 }
6851
6852 // Add the normal mutator.
6853 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6854 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006855 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006856 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006857 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006858 if (ReturnType.isNull()) {
6859 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6860 Builder.AddTextChunk("void");
6861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6862 }
6863
6864 Builder.AddTypedTextChunk(
6865 Allocator.CopyString(SelectorId->getName()));
6866 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006867 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6868 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006869 Builder.AddTextChunk(Key);
6870 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6871 CXCursor_ObjCInstanceMethodDecl));
6872 }
6873 }
6874
6875 // Indexed and unordered accessors
6876 unsigned IndexedGetterPriority = CCP_CodePattern;
6877 unsigned IndexedSetterPriority = CCP_CodePattern;
6878 unsigned UnorderedGetterPriority = CCP_CodePattern;
6879 unsigned UnorderedSetterPriority = CCP_CodePattern;
6880 if (const ObjCObjectPointerType *ObjCPointer
6881 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6882 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6883 // If this interface type is not provably derived from a known
6884 // collection, penalize the corresponding completions.
6885 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6886 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6887 if (!InheritsFromClassNamed(IFace, "NSArray"))
6888 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6889 }
6890
6891 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6892 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6893 if (!InheritsFromClassNamed(IFace, "NSSet"))
6894 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6895 }
6896 }
6897 } else {
6898 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6899 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6900 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6901 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6902 }
6903
6904 // Add -(NSUInteger)countOf<key>
6905 if (IsInstanceMethod &&
6906 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006907 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006908 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006909 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6910 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006911 if (ReturnType.isNull()) {
6912 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6913 Builder.AddTextChunk("NSUInteger");
6914 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6915 }
6916
6917 Builder.AddTypedTextChunk(
6918 Allocator.CopyString(SelectorId->getName()));
6919 Results.AddResult(Result(Builder.TakeString(),
6920 std::min(IndexedGetterPriority,
6921 UnorderedGetterPriority),
6922 CXCursor_ObjCInstanceMethodDecl));
6923 }
6924 }
6925
6926 // Indexed getters
6927 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6928 if (IsInstanceMethod &&
6929 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006930 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006931 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006932 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006933 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006934 if (ReturnType.isNull()) {
6935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6936 Builder.AddTextChunk("id");
6937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6938 }
6939
6940 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942 Builder.AddTextChunk("NSUInteger");
6943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 Builder.AddTextChunk("index");
6945 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6946 CXCursor_ObjCInstanceMethodDecl));
6947 }
6948 }
6949
6950 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6951 if (IsInstanceMethod &&
6952 (ReturnType.isNull() ||
6953 (ReturnType->isObjCObjectPointerType() &&
6954 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6955 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6956 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006957 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006958 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006959 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006960 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006961 if (ReturnType.isNull()) {
6962 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6963 Builder.AddTextChunk("NSArray *");
6964 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6965 }
6966
6967 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6968 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6969 Builder.AddTextChunk("NSIndexSet *");
6970 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6971 Builder.AddTextChunk("indexes");
6972 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6973 CXCursor_ObjCInstanceMethodDecl));
6974 }
6975 }
6976
6977 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6978 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006979 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006980 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006981 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006982 &Context.Idents.get("range")
6983 };
6984
David Blaikie82e95a32014-11-19 07:49:47 +00006985 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006986 if (ReturnType.isNull()) {
6987 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6988 Builder.AddTextChunk("void");
6989 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6990 }
6991
6992 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6993 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6994 Builder.AddPlaceholderChunk("object-type");
6995 Builder.AddTextChunk(" **");
6996 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6997 Builder.AddTextChunk("buffer");
6998 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6999 Builder.AddTypedTextChunk("range:");
7000 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7001 Builder.AddTextChunk("NSRange");
7002 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7003 Builder.AddTextChunk("inRange");
7004 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7005 CXCursor_ObjCInstanceMethodDecl));
7006 }
7007 }
7008
7009 // Mutable indexed accessors
7010
7011 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
7012 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007013 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007014 IdentifierInfo *SelectorIds[2] = {
7015 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007016 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007017 };
7018
David Blaikie82e95a32014-11-19 07:49:47 +00007019 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007020 if (ReturnType.isNull()) {
7021 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7022 Builder.AddTextChunk("void");
7023 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7024 }
7025
7026 Builder.AddTypedTextChunk("insertObject:");
7027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7028 Builder.AddPlaceholderChunk("object-type");
7029 Builder.AddTextChunk(" *");
7030 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7031 Builder.AddTextChunk("object");
7032 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7033 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7034 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7035 Builder.AddPlaceholderChunk("NSUInteger");
7036 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7037 Builder.AddTextChunk("index");
7038 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7039 CXCursor_ObjCInstanceMethodDecl));
7040 }
7041 }
7042
7043 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7044 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007045 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007046 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007047 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007048 &Context.Idents.get("atIndexes")
7049 };
7050
David Blaikie82e95a32014-11-19 07:49:47 +00007051 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007052 if (ReturnType.isNull()) {
7053 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7054 Builder.AddTextChunk("void");
7055 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7056 }
7057
7058 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7059 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7060 Builder.AddTextChunk("NSArray *");
7061 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7062 Builder.AddTextChunk("array");
7063 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7064 Builder.AddTypedTextChunk("atIndexes:");
7065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7066 Builder.AddPlaceholderChunk("NSIndexSet *");
7067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7068 Builder.AddTextChunk("indexes");
7069 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7070 CXCursor_ObjCInstanceMethodDecl));
7071 }
7072 }
7073
7074 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7075 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007076 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007077 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007078 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007079 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007080 if (ReturnType.isNull()) {
7081 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7082 Builder.AddTextChunk("void");
7083 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7084 }
7085
7086 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7088 Builder.AddTextChunk("NSUInteger");
7089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7090 Builder.AddTextChunk("index");
7091 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7092 CXCursor_ObjCInstanceMethodDecl));
7093 }
7094 }
7095
7096 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7097 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007098 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007099 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007100 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007101 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007102 if (ReturnType.isNull()) {
7103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7104 Builder.AddTextChunk("void");
7105 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7106 }
7107
7108 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7110 Builder.AddTextChunk("NSIndexSet *");
7111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7112 Builder.AddTextChunk("indexes");
7113 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7114 CXCursor_ObjCInstanceMethodDecl));
7115 }
7116 }
7117
7118 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7119 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007120 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007121 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007122 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007123 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007124 &Context.Idents.get("withObject")
7125 };
7126
David Blaikie82e95a32014-11-19 07:49:47 +00007127 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007128 if (ReturnType.isNull()) {
7129 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7130 Builder.AddTextChunk("void");
7131 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7132 }
7133
7134 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7135 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7136 Builder.AddPlaceholderChunk("NSUInteger");
7137 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7138 Builder.AddTextChunk("index");
7139 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7140 Builder.AddTypedTextChunk("withObject:");
7141 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7142 Builder.AddTextChunk("id");
7143 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7144 Builder.AddTextChunk("object");
7145 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7146 CXCursor_ObjCInstanceMethodDecl));
7147 }
7148 }
7149
7150 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7151 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007152 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007153 = (Twine("replace") + UpperKey + "AtIndexes").str();
7154 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007155 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007156 &Context.Idents.get(SelectorName1),
7157 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007158 };
7159
David Blaikie82e95a32014-11-19 07:49:47 +00007160 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007161 if (ReturnType.isNull()) {
7162 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7163 Builder.AddTextChunk("void");
7164 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7165 }
7166
7167 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7168 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7169 Builder.AddPlaceholderChunk("NSIndexSet *");
7170 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7171 Builder.AddTextChunk("indexes");
7172 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7173 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7175 Builder.AddTextChunk("NSArray *");
7176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7177 Builder.AddTextChunk("array");
7178 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7179 CXCursor_ObjCInstanceMethodDecl));
7180 }
7181 }
7182
7183 // Unordered getters
7184 // - (NSEnumerator *)enumeratorOfKey
7185 if (IsInstanceMethod &&
7186 (ReturnType.isNull() ||
7187 (ReturnType->isObjCObjectPointerType() &&
7188 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7189 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7190 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007191 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007192 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007193 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7194 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007195 if (ReturnType.isNull()) {
7196 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7197 Builder.AddTextChunk("NSEnumerator *");
7198 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7199 }
7200
7201 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7202 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7203 CXCursor_ObjCInstanceMethodDecl));
7204 }
7205 }
7206
7207 // - (type *)memberOfKey:(type *)object
7208 if (IsInstanceMethod &&
7209 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007210 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007211 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007212 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007213 if (ReturnType.isNull()) {
7214 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7215 Builder.AddPlaceholderChunk("object-type");
7216 Builder.AddTextChunk(" *");
7217 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7218 }
7219
7220 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7221 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7222 if (ReturnType.isNull()) {
7223 Builder.AddPlaceholderChunk("object-type");
7224 Builder.AddTextChunk(" *");
7225 } else {
7226 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00007227 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00007228 Builder.getAllocator()));
7229 }
7230 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7231 Builder.AddTextChunk("object");
7232 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7233 CXCursor_ObjCInstanceMethodDecl));
7234 }
7235 }
7236
7237 // Mutable unordered accessors
7238 // - (void)addKeyObject:(type *)object
7239 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007240 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007241 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007242 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007243 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007244 if (ReturnType.isNull()) {
7245 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7246 Builder.AddTextChunk("void");
7247 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7248 }
7249
7250 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7251 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7252 Builder.AddPlaceholderChunk("object-type");
7253 Builder.AddTextChunk(" *");
7254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7255 Builder.AddTextChunk("object");
7256 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7257 CXCursor_ObjCInstanceMethodDecl));
7258 }
7259 }
7260
7261 // - (void)addKey:(NSSet *)objects
7262 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007263 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007264 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007265 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007266 if (ReturnType.isNull()) {
7267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7268 Builder.AddTextChunk("void");
7269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7270 }
7271
7272 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274 Builder.AddTextChunk("NSSet *");
7275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276 Builder.AddTextChunk("objects");
7277 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7278 CXCursor_ObjCInstanceMethodDecl));
7279 }
7280 }
7281
7282 // - (void)removeKeyObject:(type *)object
7283 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007284 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007285 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007286 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007287 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007288 if (ReturnType.isNull()) {
7289 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7290 Builder.AddTextChunk("void");
7291 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7292 }
7293
7294 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7295 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7296 Builder.AddPlaceholderChunk("object-type");
7297 Builder.AddTextChunk(" *");
7298 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7299 Builder.AddTextChunk("object");
7300 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7301 CXCursor_ObjCInstanceMethodDecl));
7302 }
7303 }
7304
7305 // - (void)removeKey:(NSSet *)objects
7306 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007307 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007308 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007309 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007310 if (ReturnType.isNull()) {
7311 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7312 Builder.AddTextChunk("void");
7313 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7314 }
7315
7316 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7317 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7318 Builder.AddTextChunk("NSSet *");
7319 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7320 Builder.AddTextChunk("objects");
7321 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7322 CXCursor_ObjCInstanceMethodDecl));
7323 }
7324 }
7325
7326 // - (void)intersectKey:(NSSet *)objects
7327 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007328 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007329 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007330 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007331 if (ReturnType.isNull()) {
7332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7333 Builder.AddTextChunk("void");
7334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7335 }
7336
7337 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7338 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7339 Builder.AddTextChunk("NSSet *");
7340 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7341 Builder.AddTextChunk("objects");
7342 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7343 CXCursor_ObjCInstanceMethodDecl));
7344 }
7345 }
7346
7347 // Key-Value Observing
7348 // + (NSSet *)keyPathsForValuesAffectingKey
7349 if (!IsInstanceMethod &&
7350 (ReturnType.isNull() ||
7351 (ReturnType->isObjCObjectPointerType() &&
7352 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7353 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7354 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007355 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007356 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007357 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007358 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7359 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007360 if (ReturnType.isNull()) {
7361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Alex Lorenz71ecb072016-12-08 16:49:05 +00007362 Builder.AddTextChunk("NSSet<NSString *> *");
Douglas Gregor669a25a2011-02-17 00:22:45 +00007363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7364 }
7365
7366 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7367 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007368 CXCursor_ObjCClassMethodDecl));
7369 }
7370 }
7371
7372 // + (BOOL)automaticallyNotifiesObserversForKey
7373 if (!IsInstanceMethod &&
7374 (ReturnType.isNull() ||
7375 ReturnType->isIntegerType() ||
7376 ReturnType->isBooleanType())) {
7377 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007378 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007379 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007380 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7381 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007382 if (ReturnType.isNull()) {
7383 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7384 Builder.AddTextChunk("BOOL");
7385 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7386 }
7387
7388 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7389 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7390 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007391 }
7392 }
7393}
7394
Alex Lorenzb8740422017-10-24 16:39:37 +00007395void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007396 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007397 // Determine the return type of the method we're declaring, if
7398 // provided.
7399 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007400 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007401 if (CurContext->isObjCContainer()) {
7402 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7403 IDecl = cast<Decl>(OCD);
7404 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007405 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007406 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007407 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007408 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007409 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7410 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007411 IsInImplementation = true;
7412 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007413 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007414 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007415 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007416 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007417 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007418 }
7419
7420 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007421 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007422 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007423 }
7424
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007425 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007426 HandleCodeCompleteResults(this, CodeCompleter,
7427 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007428 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007429 return;
7430 }
7431
7432 // Find all of the methods that we could declare/implement here.
7433 KnownMethodsMap KnownMethods;
7434 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007435 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007436
Douglas Gregor636a61e2010-04-07 00:21:17 +00007437 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007438 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007439 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007440 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007441 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007442 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007443 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007444 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7445 MEnd = KnownMethods.end();
7446 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007447 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007448 CodeCompletionBuilder Builder(Results.getAllocator(),
7449 Results.getCodeCompletionTUInfo());
Alex Lorenzb8740422017-10-24 16:39:37 +00007450
7451 // Add the '-'/'+' prefix if it wasn't provided yet.
7452 if (!IsInstanceMethod) {
7453 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
7454 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7455 }
7456
Douglas Gregor636a61e2010-04-07 00:21:17 +00007457 // If the result type was not already provided, add it to the
7458 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007459 if (ReturnType.isNull()) {
7460 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7461 AttributedType::stripOuterNullability(ResTy);
7462 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007463 Method->getObjCDeclQualifier(), Context, Policy,
7464 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007465 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007466
7467 Selector Sel = Method->getSelector();
7468
7469 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007470 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007471 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007472
7473 // Add parameters to the pattern.
7474 unsigned I = 0;
7475 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7476 PEnd = Method->param_end();
7477 P != PEnd; (void)++P, ++I) {
7478 // Add the part of the selector name.
7479 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007480 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007481 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007482 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7483 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007484 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007485 } else
7486 break;
7487
7488 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007489 QualType ParamType;
7490 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7491 ParamType = (*P)->getType();
7492 else
7493 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007494 ParamType = ParamType.substObjCTypeArgs(Context, {},
7495 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007496 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007497 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007498 (*P)->getObjCDeclQualifier(),
7499 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007500 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007501
7502 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007503 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007504 }
7505
7506 if (Method->isVariadic()) {
7507 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007508 Builder.AddChunk(CodeCompletionString::CK_Comma);
7509 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007510 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007511
Douglas Gregord37c59d2010-05-28 00:57:46 +00007512 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007513 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007514 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7515 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7516 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007517 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007518 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007519 Builder.AddTextChunk("return");
7520 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7521 Builder.AddPlaceholderChunk("expression");
7522 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007523 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007524 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007525
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007526 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7527 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007528 }
7529
Douglas Gregor416b5752010-08-25 01:08:01 +00007530 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007531 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007532 Priority += CCD_InBaseClass;
7533
Douglas Gregor78254c82012-03-27 23:34:16 +00007534 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007535 }
7536
Douglas Gregor669a25a2011-02-17 00:22:45 +00007537 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7538 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007539 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007540 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007541 Containers.push_back(SearchDecl);
7542
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007543 VisitedSelectorSet KnownSelectors;
7544 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7545 MEnd = KnownMethods.end();
7546 M != MEnd; ++M)
7547 KnownSelectors.insert(M->first);
7548
7549
Douglas Gregor669a25a2011-02-17 00:22:45 +00007550 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7551 if (!IFace)
7552 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7553 IFace = Category->getClassInterface();
7554
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007555 if (IFace)
7556 for (auto *Cat : IFace->visible_categories())
7557 Containers.push_back(Cat);
Alex Lorenzb8740422017-10-24 16:39:37 +00007558
7559 if (IsInstanceMethod) {
7560 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7561 for (auto *P : Containers[I]->instance_properties())
7562 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
7563 KnownSelectors, Results);
7564 }
Douglas Gregor669a25a2011-02-17 00:22:45 +00007565 }
7566
Douglas Gregor636a61e2010-04-07 00:21:17 +00007567 Results.ExitScope();
7568
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007569 HandleCodeCompleteResults(this, CodeCompleter,
7570 CodeCompletionContext::CCC_Other,
7571 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007572}
Douglas Gregor95887f92010-07-08 23:20:03 +00007573
7574void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7575 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007576 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007577 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007578 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007579 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007580 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007581 if (ExternalSource) {
7582 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7583 I != N; ++I) {
7584 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007585 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007586 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007587
7588 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007589 }
7590 }
7591
7592 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007593 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007594 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007595 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007596 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007597
7598 if (ReturnTy)
7599 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007600
Douglas Gregor95887f92010-07-08 23:20:03 +00007601 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007602 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7603 MEnd = MethodPool.end();
7604 M != MEnd; ++M) {
7605 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7606 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007607 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007608 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007609 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007610 continue;
7611
Douglas Gregor45879692010-07-08 23:37:41 +00007612 if (AtParameterName) {
7613 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007614 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007615 if (NumSelIdents &&
7616 NumSelIdents <= MethList->getMethod()->param_size()) {
7617 ParmVarDecl *Param =
7618 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007619 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007620 CodeCompletionBuilder Builder(Results.getAllocator(),
7621 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007622 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007623 Param->getIdentifier()->getName()));
7624 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007625 }
7626 }
7627
7628 continue;
7629 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007630
Nico Weber2e0c8f72014-12-27 03:58:08 +00007631 Result R(MethList->getMethod(),
7632 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007633 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007634 R.AllParametersAreInformative = false;
7635 R.DeclaringEntity = true;
7636 Results.MaybeAddResult(R, CurContext);
7637 }
7638 }
7639
7640 Results.ExitScope();
Alex Lorenz847fda12017-01-03 11:56:40 +00007641
7642 if (!AtParameterName && !SelIdents.empty() &&
7643 SelIdents.front()->getName().startswith("init")) {
7644 for (const auto &M : PP.macros()) {
7645 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7646 continue;
7647 Results.EnterNewScope();
7648 CodeCompletionBuilder Builder(Results.getAllocator(),
7649 Results.getCodeCompletionTUInfo());
7650 Builder.AddTypedTextChunk(
7651 Builder.getAllocator().CopyString(M.first->getName()));
7652 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7653 CXCursor_MacroDefinition));
7654 Results.ExitScope();
7655 }
7656 }
7657
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007658 HandleCodeCompleteResults(this, CodeCompleter,
7659 CodeCompletionContext::CCC_Other,
7660 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007661}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007662
Douglas Gregorec00a262010-08-24 22:20:20 +00007663void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007664 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007665 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007666 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007667 Results.EnterNewScope();
7668
7669 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007670 CodeCompletionBuilder Builder(Results.getAllocator(),
7671 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007672 Builder.AddTypedTextChunk("if");
7673 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7674 Builder.AddPlaceholderChunk("condition");
7675 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007676
7677 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007678 Builder.AddTypedTextChunk("ifdef");
7679 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7680 Builder.AddPlaceholderChunk("macro");
7681 Results.AddResult(Builder.TakeString());
7682
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007683 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007684 Builder.AddTypedTextChunk("ifndef");
7685 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7686 Builder.AddPlaceholderChunk("macro");
7687 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007688
7689 if (InConditional) {
7690 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007691 Builder.AddTypedTextChunk("elif");
7692 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7693 Builder.AddPlaceholderChunk("condition");
7694 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007695
7696 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007697 Builder.AddTypedTextChunk("else");
7698 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007699
7700 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007701 Builder.AddTypedTextChunk("endif");
7702 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007703 }
7704
7705 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007706 Builder.AddTypedTextChunk("include");
7707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7708 Builder.AddTextChunk("\"");
7709 Builder.AddPlaceholderChunk("header");
7710 Builder.AddTextChunk("\"");
7711 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007712
7713 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007714 Builder.AddTypedTextChunk("include");
7715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7716 Builder.AddTextChunk("<");
7717 Builder.AddPlaceholderChunk("header");
7718 Builder.AddTextChunk(">");
7719 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007720
7721 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007722 Builder.AddTypedTextChunk("define");
7723 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7724 Builder.AddPlaceholderChunk("macro");
7725 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007726
7727 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007728 Builder.AddTypedTextChunk("define");
7729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7730 Builder.AddPlaceholderChunk("macro");
7731 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7732 Builder.AddPlaceholderChunk("args");
7733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7734 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007735
7736 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007737 Builder.AddTypedTextChunk("undef");
7738 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7739 Builder.AddPlaceholderChunk("macro");
7740 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007741
7742 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007743 Builder.AddTypedTextChunk("line");
7744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7745 Builder.AddPlaceholderChunk("number");
7746 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007747
7748 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007749 Builder.AddTypedTextChunk("line");
7750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7751 Builder.AddPlaceholderChunk("number");
7752 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7753 Builder.AddTextChunk("\"");
7754 Builder.AddPlaceholderChunk("filename");
7755 Builder.AddTextChunk("\"");
7756 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007757
7758 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007759 Builder.AddTypedTextChunk("error");
7760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7761 Builder.AddPlaceholderChunk("message");
7762 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007763
7764 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007765 Builder.AddTypedTextChunk("pragma");
7766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7767 Builder.AddPlaceholderChunk("arguments");
7768 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007769
David Blaikiebbafb8a2012-03-11 07:00:24 +00007770 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007771 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007772 Builder.AddTypedTextChunk("import");
7773 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7774 Builder.AddTextChunk("\"");
7775 Builder.AddPlaceholderChunk("header");
7776 Builder.AddTextChunk("\"");
7777 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007778
7779 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007780 Builder.AddTypedTextChunk("import");
7781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7782 Builder.AddTextChunk("<");
7783 Builder.AddPlaceholderChunk("header");
7784 Builder.AddTextChunk(">");
7785 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007786 }
7787
7788 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007789 Builder.AddTypedTextChunk("include_next");
7790 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7791 Builder.AddTextChunk("\"");
7792 Builder.AddPlaceholderChunk("header");
7793 Builder.AddTextChunk("\"");
7794 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007795
7796 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007797 Builder.AddTypedTextChunk("include_next");
7798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7799 Builder.AddTextChunk("<");
7800 Builder.AddPlaceholderChunk("header");
7801 Builder.AddTextChunk(">");
7802 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007803
7804 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007805 Builder.AddTypedTextChunk("warning");
7806 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7807 Builder.AddPlaceholderChunk("message");
7808 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007809
7810 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7811 // completions for them. And __include_macros is a Clang-internal extension
7812 // that we don't want to encourage anyone to use.
7813
7814 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7815 Results.ExitScope();
7816
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007817 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007818 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007819 Results.data(), Results.size());
7820}
7821
7822void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007823 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007824 S->getFnParent()? Sema::PCC_RecoveryInFunction
7825 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007826}
7827
Douglas Gregorec00a262010-08-24 22:20:20 +00007828void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007829 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007830 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007831 IsDefinition? CodeCompletionContext::CCC_MacroName
7832 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007833 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7834 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007835 CodeCompletionBuilder Builder(Results.getAllocator(),
7836 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007837 Results.EnterNewScope();
7838 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7839 MEnd = PP.macro_end();
7840 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007841 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007842 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007843 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7844 CCP_CodePattern,
7845 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007846 }
7847 Results.ExitScope();
7848 } else if (IsDefinition) {
7849 // FIXME: Can we detect when the user just wrote an include guard above?
7850 }
7851
Douglas Gregor0ac41382010-09-23 23:01:17 +00007852 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007853 Results.data(), Results.size());
7854}
7855
Douglas Gregorec00a262010-08-24 22:20:20 +00007856void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007857 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007858 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007859 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007860
7861 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007862 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007863
7864 // defined (<macro>)
7865 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007866 CodeCompletionBuilder Builder(Results.getAllocator(),
7867 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007868 Builder.AddTypedTextChunk("defined");
7869 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7870 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7871 Builder.AddPlaceholderChunk("macro");
7872 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7873 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007874 Results.ExitScope();
7875
7876 HandleCodeCompleteResults(this, CodeCompleter,
7877 CodeCompletionContext::CCC_PreprocessorExpression,
7878 Results.data(), Results.size());
7879}
7880
7881void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7882 IdentifierInfo *Macro,
7883 MacroInfo *MacroInfo,
7884 unsigned Argument) {
7885 // FIXME: In the future, we could provide "overload" results, much like we
7886 // do for function calls.
7887
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007888 // Now just ignore this. There will be another code-completion callback
7889 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007890}
7891
Douglas Gregor11583702010-08-25 17:04:25 +00007892void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007893 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007894 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007895 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007896}
7897
Alex Lorenzf7f6f822017-05-09 16:05:04 +00007898void Sema::CodeCompleteAvailabilityPlatformName() {
7899 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7900 CodeCompleter->getCodeCompletionTUInfo(),
7901 CodeCompletionContext::CCC_Other);
7902 Results.EnterNewScope();
7903 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7904 for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7905 Results.AddResult(CodeCompletionResult(Platform));
7906 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7907 Twine(Platform) + "ApplicationExtension")));
7908 }
7909 Results.ExitScope();
7910 HandleCodeCompleteResults(this, CodeCompleter,
7911 CodeCompletionContext::CCC_Other, Results.data(),
7912 Results.size());
7913}
7914
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007915void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007916 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007917 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007918 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7919 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007920 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7921 CodeCompletionDeclConsumer Consumer(Builder,
7922 Context.getTranslationUnitDecl());
7923 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7924 Consumer);
7925 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007926
7927 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007928 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007929
7930 Results.clear();
7931 Results.insert(Results.end(),
7932 Builder.data(), Builder.data() + Builder.size());
7933}