blob: fdfc39993ded98b7d45dc11c58e412e8e0e56089 [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;
Douglas Gregor3545ff42009-09-21 16:56:56 +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());
4399 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4400 /*SuppressUsedConversions=*/false,
4401 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004402 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004403 FunctionDecl *FD = nullptr;
4404 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4405 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4406 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4407 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004408 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004409 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004410 !FD->getType()->getAs<FunctionProtoType>())
4411 Results.push_back(ResultCandidate(FD));
4412 else
4413 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4414 Args, CandidateSet,
4415 /*SuppressUsedConversions=*/false,
4416 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004417
4418 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4419 // If expression's type is CXXRecordDecl, it may overload the function
4420 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004421 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004422 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004423 DeclarationName OpName = Context.DeclarationNames
4424 .getCXXOperatorName(OO_Call);
4425 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4426 LookupQualifiedName(R, DC);
4427 R.suppressDiagnostics();
4428 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4429 ArgExprs.append(Args.begin(), Args.end());
4430 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4431 /*ExplicitArgs=*/nullptr,
4432 /*SuppressUsedConversions=*/false,
4433 /*PartialOverloading=*/true);
4434 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004435 } else {
4436 // Lastly we check whether expression's type is function pointer or
4437 // function.
4438 QualType T = NakedFn->getType();
4439 if (!T->getPointeeType().isNull())
4440 T = T->getPointeeType();
4441
4442 if (auto FP = T->getAs<FunctionProtoType>()) {
4443 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004444 /*PartialOverloading=*/true) ||
4445 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004446 Results.push_back(ResultCandidate(FP));
4447 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004448 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004449 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004450 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004451 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004452
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004453 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4454 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4455 !CandidateSet.empty());
4456}
4457
4458void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4459 ArrayRef<Expr *> Args) {
4460 if (!CodeCompleter)
4461 return;
4462
4463 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004464 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004465 return;
4466
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004467 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4468 if (!RD) {
4469 CodeCompleteExpression(S, Type);
4470 return;
4471 }
4472
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004473 // FIXME: Provide support for member initializers.
4474 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004475
4476 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4477
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004478 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004479 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4480 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4481 Args, CandidateSet,
4482 /*SuppressUsedConversions=*/false,
4483 /*PartialOverloading=*/true);
4484 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4485 AddTemplateOverloadCandidate(FTD,
4486 DeclAccessPair::make(FTD, C->getAccess()),
4487 /*ExplicitTemplateArgs=*/nullptr,
4488 Args, CandidateSet,
4489 /*SuppressUsedConversions=*/false,
4490 /*PartialOverloading=*/true);
4491 }
4492 }
4493
4494 SmallVector<ResultCandidate, 8> Results;
4495 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4496 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004497}
4498
John McCall48871652010-08-21 09:40:31 +00004499void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4500 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004501 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004502 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004503 return;
4504 }
4505
4506 CodeCompleteExpression(S, VD->getType());
4507}
4508
4509void Sema::CodeCompleteReturn(Scope *S) {
4510 QualType ResultType;
4511 if (isa<BlockDecl>(CurContext)) {
4512 if (BlockScopeInfo *BSI = getCurBlock())
4513 ResultType = BSI->ReturnType;
4514 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004515 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004516 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004517 ResultType = Method->getReturnType();
4518
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004519 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004520 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004521 else
4522 CodeCompleteExpression(S, ResultType);
4523}
4524
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004525void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004526 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004527 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004528 mapCodeCompletionContext(*this, PCC_Statement));
4529 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4530 Results.EnterNewScope();
4531
4532 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4533 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4534 CodeCompleter->includeGlobals());
4535
4536 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4537
4538 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004539 CodeCompletionBuilder Builder(Results.getAllocator(),
4540 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004541 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004542 if (Results.includeCodePatterns()) {
4543 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4544 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4545 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4546 Builder.AddPlaceholderChunk("statements");
4547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4548 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4549 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004550 Results.AddResult(Builder.TakeString());
4551
4552 // "else if" block
4553 Builder.AddTypedTextChunk("else");
4554 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4555 Builder.AddTextChunk("if");
4556 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004558 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004559 Builder.AddPlaceholderChunk("condition");
4560 else
4561 Builder.AddPlaceholderChunk("expression");
4562 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004563 if (Results.includeCodePatterns()) {
4564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4565 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4566 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4567 Builder.AddPlaceholderChunk("statements");
4568 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4569 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4570 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004571 Results.AddResult(Builder.TakeString());
4572
4573 Results.ExitScope();
4574
4575 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004576 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004577
4578 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004579 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004580
4581 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4582 Results.data(),Results.size());
4583}
4584
Richard Trieu2bd04012011-09-09 02:00:50 +00004585void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004586 if (LHS)
4587 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4588 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004589 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004590}
4591
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004592void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004593 bool EnteringContext) {
4594 if (!SS.getScopeRep() || !CodeCompleter)
4595 return;
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004596
4597 // Always pretend to enter a context to ensure that a dependent type
4598 // resolves to a dependent record.
4599 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +00004600 if (!Ctx)
4601 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004602
4603 // Try to instantiate any non-dependent declaration contexts before
4604 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004605 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004606 return;
4607
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004608 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004609 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004610 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004611 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004612
Douglas Gregor3545ff42009-09-21 16:56:56 +00004613 // The "template" keyword can follow "::" in the grammar, but only
4614 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004615 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004616 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004617 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004618
4619 // Add calls to overridden virtual functions, if there are any.
4620 //
4621 // FIXME: This isn't wonderful, because we don't know whether we're actually
4622 // in a context that permits expressions. This is a general issue with
4623 // qualified-id completions.
4624 if (!EnteringContext)
4625 MaybeAddOverrideCalls(*this, Ctx, Results);
4626 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004627
Douglas Gregorac322ec2010-08-27 21:18:54 +00004628 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Alex Lorenz8a7a4cf2017-06-15 21:40:54 +00004629 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4630 /*IncludeGlobalScope=*/true,
4631 /*IncludeDependentBases=*/true);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004632
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004633 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004634 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004635 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004636}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004637
4638void Sema::CodeCompleteUsing(Scope *S) {
4639 if (!CodeCompleter)
4640 return;
4641
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004642 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004643 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004644 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4645 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004646 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004647
4648 // If we aren't in class scope, we could see the "namespace" keyword.
4649 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004650 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004651
4652 // After "using", we can see anything that would start a
4653 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004654 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004655 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4656 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004657 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004658
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004659 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004660 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004661 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004662}
4663
4664void Sema::CodeCompleteUsingDirective(Scope *S) {
4665 if (!CodeCompleter)
4666 return;
4667
Douglas Gregor3545ff42009-09-21 16:56:56 +00004668 // After "using namespace", we expect to see a namespace name or namespace
4669 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004670 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004671 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004672 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004673 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004674 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004675 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004676 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4677 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004678 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004679 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004680 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004681 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004682}
4683
4684void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4685 if (!CodeCompleter)
4686 return;
4687
Ted Kremenekc37877d2013-10-08 17:08:03 +00004688 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004689 if (!S->getParent())
4690 Ctx = Context.getTranslationUnitDecl();
4691
Douglas Gregor0ac41382010-09-23 23:01:17 +00004692 bool SuppressedGlobalResults
4693 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4694
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004695 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004696 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004697 SuppressedGlobalResults
4698 ? CodeCompletionContext::CCC_Namespace
4699 : CodeCompletionContext::CCC_Other,
4700 &ResultBuilder::IsNamespace);
4701
4702 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004703 // We only want to see those namespaces that have already been defined
4704 // within this scope, because its likely that the user is creating an
4705 // extended namespace declaration. Keep track of the most recent
4706 // definition of each namespace.
4707 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4708 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4709 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4710 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004711 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004712
4713 // Add the most recent definition (or extended definition) of each
4714 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004715 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004716 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004717 NS = OrigToLatest.begin(),
4718 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004719 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004720 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004721 NS->second, Results.getBasePriority(NS->second),
4722 nullptr),
4723 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004724 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004725 }
4726
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004727 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004728 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004729 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004730}
4731
4732void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4733 if (!CodeCompleter)
4734 return;
4735
Douglas Gregor3545ff42009-09-21 16:56:56 +00004736 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004737 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004738 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004739 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004740 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004741 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004742 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4743 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004744 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004745 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004746 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004747}
4748
Douglas Gregorc811ede2009-09-18 20:05:18 +00004749void Sema::CodeCompleteOperatorName(Scope *S) {
4750 if (!CodeCompleter)
4751 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004752
John McCall276321a2010-08-25 06:19:51 +00004753 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004754 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004755 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004756 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004757 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004758 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004759
Douglas Gregor3545ff42009-09-21 16:56:56 +00004760 // Add the names of overloadable operators.
4761#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4762 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004763 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004764#include "clang/Basic/OperatorKinds.def"
4765
4766 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004767 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004768 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004769 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4770 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004771
4772 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004773 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004774 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004775
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004776 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004777 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004778 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004779}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004780
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004781void Sema::CodeCompleteConstructorInitializer(
4782 Decl *ConstructorD,
4783 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004784 if (!ConstructorD)
4785 return;
4786
4787 AdjustDeclIfTemplate(ConstructorD);
4788
4789 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004790 if (!Constructor)
4791 return;
4792
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004793 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004794 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004795 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004796 Results.EnterNewScope();
4797
4798 // Fill in any already-initialized fields or base classes.
4799 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4800 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004801 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004802 if (Initializers[I]->isBaseInitializer())
4803 InitializedBases.insert(
4804 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4805 else
Francois Pichetd583da02010-12-04 09:14:42 +00004806 InitializedFields.insert(cast<FieldDecl>(
4807 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004808 }
4809
4810 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004811 CodeCompletionBuilder Builder(Results.getAllocator(),
4812 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004813 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004814 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004815 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004816 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004817 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4818 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004819 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004820 = !Initializers.empty() &&
4821 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004822 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004823 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004824 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004825 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004826
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004827 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004828 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004829 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4831 Builder.AddPlaceholderChunk("args");
4832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4833 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004834 SawLastInitializer? CCP_NextInitializer
4835 : CCP_MemberDeclaration));
4836 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004837 }
4838
4839 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004840 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004841 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4842 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004843 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004844 = !Initializers.empty() &&
4845 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004846 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004847 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004848 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004849 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004850
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004851 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004852 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004853 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4855 Builder.AddPlaceholderChunk("args");
4856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4857 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004858 SawLastInitializer? CCP_NextInitializer
4859 : CCP_MemberDeclaration));
4860 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004861 }
4862
4863 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004864 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004865 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4866 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004867 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004868 = !Initializers.empty() &&
4869 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004870 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004871 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004872 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004873
4874 if (!Field->getDeclName())
4875 continue;
4876
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004877 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004878 Field->getIdentifier()->getName()));
4879 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4880 Builder.AddPlaceholderChunk("args");
4881 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4882 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004883 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004884 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004885 CXCursor_MemberRef,
4886 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004887 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004888 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004889 }
4890 Results.ExitScope();
4891
Douglas Gregor0ac41382010-09-23 23:01:17 +00004892 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004893 Results.data(), Results.size());
4894}
4895
Douglas Gregord8c61782012-02-15 15:34:24 +00004896/// \brief Determine whether this scope denotes a namespace.
4897static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004898 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004899 if (!DC)
4900 return false;
4901
4902 return DC->isFileContext();
4903}
4904
4905void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4906 bool AfterAmpersand) {
4907 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004908 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004909 CodeCompletionContext::CCC_Other);
4910 Results.EnterNewScope();
4911
4912 // Note what has already been captured.
4913 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4914 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004915 for (const auto &C : Intro.Captures) {
4916 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004917 IncludedThis = true;
4918 continue;
4919 }
4920
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004921 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004922 }
4923
4924 // Look for other capturable variables.
4925 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004926 for (const auto *D : S->decls()) {
4927 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004928 if (!Var ||
4929 !Var->hasLocalStorage() ||
4930 Var->hasAttr<BlocksAttr>())
4931 continue;
4932
David Blaikie82e95a32014-11-19 07:49:47 +00004933 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004934 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004935 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004936 }
4937 }
4938
4939 // Add 'this', if it would be valid.
4940 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4941 addThisCompletion(*this, Results);
4942
4943 Results.ExitScope();
4944
4945 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4946 Results.data(), Results.size());
4947}
4948
James Dennett596e4752012-06-14 03:11:41 +00004949/// Macro that optionally prepends an "@" to the string literal passed in via
4950/// Keyword, depending on whether NeedAt is true or false.
4951#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4952
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004953static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004954 ResultBuilder &Results,
4955 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004956 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004957 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004958 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004959
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004960 CodeCompletionBuilder Builder(Results.getAllocator(),
4961 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004962 if (LangOpts.ObjC2) {
4963 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004964 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004965 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4966 Builder.AddPlaceholderChunk("property");
4967 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004968
4969 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004970 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004971 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4972 Builder.AddPlaceholderChunk("property");
4973 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004974 }
4975}
4976
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004977static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004978 ResultBuilder &Results,
4979 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004980 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004981
4982 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004983 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004984
4985 if (LangOpts.ObjC2) {
4986 // @property
James Dennett596e4752012-06-14 03:11:41 +00004987 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004988
4989 // @required
James Dennett596e4752012-06-14 03:11:41 +00004990 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004991
4992 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004993 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004994 }
4995}
4996
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004997static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004998 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004999 CodeCompletionBuilder Builder(Results.getAllocator(),
5000 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00005001
5002 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00005003 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5005 Builder.AddPlaceholderChunk("name");
5006 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005007
Douglas Gregorf4c33342010-05-28 00:22:41 +00005008 if (Results.includeCodePatterns()) {
5009 // @interface name
5010 // FIXME: Could introduce the whole pattern, including superclasses and
5011 // such.
James Dennett596e4752012-06-14 03:11:41 +00005012 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5014 Builder.AddPlaceholderChunk("class");
5015 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005016
Douglas Gregorf4c33342010-05-28 00:22:41 +00005017 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00005018 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005019 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5020 Builder.AddPlaceholderChunk("protocol");
5021 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005022
5023 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00005024 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005025 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5026 Builder.AddPlaceholderChunk("class");
5027 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005028 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005029
5030 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00005031 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005032 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5033 Builder.AddPlaceholderChunk("alias");
5034 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5035 Builder.AddPlaceholderChunk("class");
5036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00005037
5038 if (Results.getSema().getLangOpts().Modules) {
5039 // @import name
5040 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5041 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5042 Builder.AddPlaceholderChunk("module");
5043 Results.AddResult(Result(Builder.TakeString()));
5044 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005045}
5046
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005047void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005048 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005049 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005050 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005051 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005052 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00005053 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005054 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00005055 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00005056 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005057 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00005058 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005059 HandleCodeCompleteResults(this, CodeCompleter,
5060 CodeCompletionContext::CCC_Other,
5061 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00005062}
5063
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005064static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005065 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005066 CodeCompletionBuilder Builder(Results.getAllocator(),
5067 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005068
5069 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005070 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00005071 if (Results.getSema().getLangOpts().CPlusPlus ||
5072 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00005073 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00005074 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00005075 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005076 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5077 Builder.AddPlaceholderChunk("type-name");
5078 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5079 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005080
5081 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005082 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00005083 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005084 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5085 Builder.AddPlaceholderChunk("protocol-name");
5086 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5087 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005088
5089 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00005090 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00005091 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005092 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5093 Builder.AddPlaceholderChunk("selector");
5094 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5095 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005096
5097 // @"string"
5098 Builder.AddResultTypeChunk("NSString *");
5099 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5100 Builder.AddPlaceholderChunk("string");
5101 Builder.AddTextChunk("\"");
5102 Results.AddResult(Result(Builder.TakeString()));
5103
Douglas Gregor951de302012-07-17 23:24:47 +00005104 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00005105 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00005106 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005107 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005108 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5109 Results.AddResult(Result(Builder.TakeString()));
5110
Douglas Gregor951de302012-07-17 23:24:47 +00005111 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00005112 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00005113 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00005114 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005115 Builder.AddChunk(CodeCompletionString::CK_Colon);
5116 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5117 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00005118 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5119 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00005120
Douglas Gregor951de302012-07-17 23:24:47 +00005121 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00005122 Builder.AddResultTypeChunk("id");
5123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00005124 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00005125 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5126 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005127}
5128
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005129static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005130 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005131 CodeCompletionBuilder Builder(Results.getAllocator(),
5132 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00005133
Douglas Gregorf4c33342010-05-28 00:22:41 +00005134 if (Results.includeCodePatterns()) {
5135 // @try { statements } @catch ( declaration ) { statements } @finally
5136 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00005137 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005138 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5139 Builder.AddPlaceholderChunk("statements");
5140 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5141 Builder.AddTextChunk("@catch");
5142 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5143 Builder.AddPlaceholderChunk("parameter");
5144 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5145 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5146 Builder.AddPlaceholderChunk("statements");
5147 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5148 Builder.AddTextChunk("@finally");
5149 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5150 Builder.AddPlaceholderChunk("statements");
5151 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5152 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005153 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005154
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005155 // @throw
James Dennett596e4752012-06-14 03:11:41 +00005156 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5158 Builder.AddPlaceholderChunk("expression");
5159 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00005160
Douglas Gregorf4c33342010-05-28 00:22:41 +00005161 if (Results.includeCodePatterns()) {
5162 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00005163 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005164 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5165 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5166 Builder.AddPlaceholderChunk("expression");
5167 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5168 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5169 Builder.AddPlaceholderChunk("statements");
5170 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5171 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00005172 }
Douglas Gregorf1934162010-01-13 21:24:21 +00005173}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005174
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005175static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00005176 ResultBuilder &Results,
5177 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00005178 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00005179 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5180 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5181 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005182 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00005183 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00005184}
5185
5186void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005187 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005188 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005189 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00005190 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005191 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00005192 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005193 HandleCodeCompleteResults(this, CodeCompleter,
5194 CodeCompletionContext::CCC_Other,
5195 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00005196}
5197
5198void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005199 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005200 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005201 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00005202 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005203 AddObjCStatementResults(Results, false);
5204 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005205 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005206 HandleCodeCompleteResults(this, CodeCompleter,
5207 CodeCompletionContext::CCC_Other,
5208 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005209}
5210
5211void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005212 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005213 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005214 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005215 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00005216 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005217 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005218 HandleCodeCompleteResults(this, CodeCompleter,
5219 CodeCompletionContext::CCC_Other,
5220 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00005221}
5222
Douglas Gregore6078da2009-11-19 00:14:45 +00005223/// \brief Determine whether the addition of the given flag to an Objective-C
5224/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00005225static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00005226 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00005227 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00005228 return true;
5229
Bill Wendling44426052012-12-20 19:22:21 +00005230 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00005231
5232 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00005233 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5234 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00005235 return true;
5236
Jordan Rose53cb2f32012-08-20 20:01:13 +00005237 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00005238 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00005239 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00005240 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00005241 ObjCDeclSpec::DQ_PR_retain |
5242 ObjCDeclSpec::DQ_PR_strong |
5243 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00005244 if (AssignCopyRetMask &&
5245 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00005246 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00005247 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00005248 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00005249 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5250 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00005251 return true;
5252
5253 return false;
5254}
5255
Douglas Gregor36029f42009-11-18 23:08:07 +00005256void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00005257 if (!CodeCompleter)
5258 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005259
Bill Wendling44426052012-12-20 19:22:21 +00005260 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00005261
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005262 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005263 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005264 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00005265 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00005266 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00005267 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00005268 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00005269 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00005270 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00005271 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5272 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00005273 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00005274 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00005275 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00005276 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00005277 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00005278 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00005279 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00005280 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00005281 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00005282 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00005283 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00005284 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00005285
5286 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00005287 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00005288 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00005289 Results.AddResult(CodeCompletionResult("weak"));
5290
Bill Wendling44426052012-12-20 19:22:21 +00005291 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005292 CodeCompletionBuilder Setter(Results.getAllocator(),
5293 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005294 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005295 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005296 Setter.AddPlaceholderChunk("method");
5297 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005298 }
Bill Wendling44426052012-12-20 19:22:21 +00005299 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005300 CodeCompletionBuilder Getter(Results.getAllocator(),
5301 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005302 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00005303 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005304 Getter.AddPlaceholderChunk("method");
5305 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00005306 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005307 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5308 Results.AddResult(CodeCompletionResult("nonnull"));
5309 Results.AddResult(CodeCompletionResult("nullable"));
5310 Results.AddResult(CodeCompletionResult("null_unspecified"));
5311 Results.AddResult(CodeCompletionResult("null_resettable"));
5312 }
Steve Naroff936354c2009-10-08 21:55:05 +00005313 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005314 HandleCodeCompleteResults(this, CodeCompleter,
5315 CodeCompletionContext::CCC_Other,
5316 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00005317}
Steve Naroffeae65032009-11-07 02:08:14 +00005318
James Dennettf1243872012-06-17 05:33:25 +00005319/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00005320/// via code completion.
5321enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00005322 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5323 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5324 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005325};
5326
Douglas Gregor67c692c2010-08-26 15:07:07 +00005327static bool isAcceptableObjCSelector(Selector Sel,
5328 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005329 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005330 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005331 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00005332 if (NumSelIdents > Sel.getNumArgs())
5333 return false;
5334
5335 switch (WantKind) {
5336 case MK_Any: break;
5337 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5338 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5339 }
5340
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005341 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5342 return false;
5343
Douglas Gregor67c692c2010-08-26 15:07:07 +00005344 for (unsigned I = 0; I != NumSelIdents; ++I)
5345 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5346 return false;
5347
5348 return true;
5349}
5350
Douglas Gregorc8537c52009-11-19 07:41:15 +00005351static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5352 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005353 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005354 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005355 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005356 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005357}
Douglas Gregor1154e272010-09-16 16:06:31 +00005358
5359namespace {
5360 /// \brief A set of selectors, which is used to avoid introducing multiple
5361 /// completions with the same selector into the result set.
5362 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5363}
5364
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005365/// \brief Add all of the Objective-C methods in the given Objective-C
5366/// container to the set of results.
5367///
5368/// The container will be a class, protocol, category, or implementation of
5369/// any of the above. This mether will recurse to include methods from
5370/// the superclasses of classes along with their categories, protocols, and
5371/// implementations.
5372///
5373/// \param Container the container in which we'll look to find methods.
5374///
James Dennett596e4752012-06-14 03:11:41 +00005375/// \param WantInstanceMethods Whether to add instance methods (only); if
5376/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005377///
5378/// \param CurContext the context in which we're performing the lookup that
5379/// finds methods.
5380///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005381/// \param AllowSameLength Whether we allow a method to be added to the list
5382/// when it has the same number of parameters as we have selector identifiers.
5383///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005384/// \param Results the structure into which we'll add results.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005385static void AddObjCMethods(ObjCContainerDecl *Container,
5386 bool WantInstanceMethods, ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005387 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005388 DeclContext *CurContext,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005389 VisitedSelectorSet &Selectors, bool AllowSameLength,
5390 ResultBuilder &Results, bool InOriginalClass = true,
5391 bool IsRootClass = false) {
John McCall276321a2010-08-25 06:19:51 +00005392 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005393 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005394 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Alex Lorenz638dbc32017-01-24 14:15:08 +00005395 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005396 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005397 // The instance methods on the root class can be messaged via the
5398 // metaclass.
5399 if (M->isInstanceMethod() == WantInstanceMethods ||
Alex Lorenz638dbc32017-01-24 14:15:08 +00005400 (IsRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005401 // Check whether the selector identifiers we've been given are a
5402 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005403 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005404 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005405
David Blaikie82e95a32014-11-19 07:49:47 +00005406 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005407 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005408
5409 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005410 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005411 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005412 if (!InOriginalClass)
5413 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005414 Results.MaybeAddResult(R, CurContext);
5415 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005416 }
5417
Douglas Gregorf37c9492010-09-16 15:34:59 +00005418 // Visit the protocols of protocols.
5419 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005420 if (Protocol->hasDefinition()) {
5421 const ObjCList<ObjCProtocolDecl> &Protocols
5422 = Protocol->getReferencedProtocols();
5423 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5424 E = Protocols.end();
5425 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005426 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5427 Selectors, AllowSameLength, Results, false, IsRootClass);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005428 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005429 }
5430
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005431 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005432 return;
5433
5434 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005435 for (auto *I : IFace->protocols())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005436 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5437 Selectors, AllowSameLength, Results, false, IsRootClass);
5438
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005439 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005440 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005441 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Alex Lorenz638dbc32017-01-24 14:15:08 +00005442 CurContext, Selectors, AllowSameLength, Results,
5443 InOriginalClass, IsRootClass);
5444
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005445 // Add a categories protocol methods.
5446 const ObjCList<ObjCProtocolDecl> &Protocols
5447 = CatDecl->getReferencedProtocols();
5448 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5449 E = Protocols.end();
5450 I != E; ++I)
Alex Lorenz638dbc32017-01-24 14:15:08 +00005451 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5452 Selectors, AllowSameLength, Results, false, IsRootClass);
5453
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005454 // Add methods in category implementations.
5455 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005456 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5457 Selectors, AllowSameLength, Results, InOriginalClass,
5458 IsRootClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005459 }
5460
5461 // Add methods in superclass.
Alex Lorenz638dbc32017-01-24 14:15:08 +00005462 // Avoid passing in IsRootClass since root classes won't have super classes.
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005463 if (IFace->getSuperClass())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005464 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5465 SelIdents, CurContext, Selectors, AllowSameLength, Results,
5466 /*IsRootClass=*/false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005467
5468 // Add methods in our implementation, if any.
5469 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Alex Lorenz638dbc32017-01-24 14:15:08 +00005470 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5471 Selectors, AllowSameLength, Results, InOriginalClass,
5472 IsRootClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005473}
5474
5475
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005476void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005477 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005478 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005479 if (!Class) {
5480 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005481 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005482 Class = Category->getClassInterface();
5483
5484 if (!Class)
5485 return;
5486 }
5487
5488 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005489 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005490 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005491 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005492 Results.EnterNewScope();
5493
Douglas Gregor1154e272010-09-16 16:06:31 +00005494 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005495 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005496 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005497 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005498 HandleCodeCompleteResults(this, CodeCompleter,
5499 CodeCompletionContext::CCC_Other,
5500 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005501}
5502
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005503void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005504 // Try to find the interface where setters might live.
5505 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005506 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005507 if (!Class) {
5508 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005509 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005510 Class = Category->getClassInterface();
5511
5512 if (!Class)
5513 return;
5514 }
5515
5516 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005517 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005518 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005519 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005520 Results.EnterNewScope();
5521
Douglas Gregor1154e272010-09-16 16:06:31 +00005522 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005523 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005524 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005525
5526 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005527 HandleCodeCompleteResults(this, CodeCompleter,
5528 CodeCompletionContext::CCC_Other,
5529 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005530}
5531
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005532void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5533 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005534 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005535 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005536 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005537 Results.EnterNewScope();
5538
5539 // Add context-sensitive, Objective-C parameter-passing keywords.
5540 bool AddedInOut = false;
5541 if ((DS.getObjCDeclQualifier() &
5542 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5543 Results.AddResult("in");
5544 Results.AddResult("inout");
5545 AddedInOut = true;
5546 }
5547 if ((DS.getObjCDeclQualifier() &
5548 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5549 Results.AddResult("out");
5550 if (!AddedInOut)
5551 Results.AddResult("inout");
5552 }
5553 if ((DS.getObjCDeclQualifier() &
5554 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5555 ObjCDeclSpec::DQ_Oneway)) == 0) {
5556 Results.AddResult("bycopy");
5557 Results.AddResult("byref");
5558 Results.AddResult("oneway");
5559 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005560 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5561 Results.AddResult("nonnull");
5562 Results.AddResult("nullable");
5563 Results.AddResult("null_unspecified");
5564 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005565
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005566 // If we're completing the return type of an Objective-C method and the
5567 // identifier IBAction refers to a macro, provide a completion item for
5568 // an action, e.g.,
5569 // IBAction)<#selector#>:(id)sender
5570 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005571 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005572 CodeCompletionBuilder Builder(Results.getAllocator(),
5573 Results.getCodeCompletionTUInfo(),
5574 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005575 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005576 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005577 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005578 Builder.AddChunk(CodeCompletionString::CK_Colon);
5579 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005580 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005581 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005582 Builder.AddTextChunk("sender");
5583 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5584 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005585
5586 // If we're completing the return type, provide 'instancetype'.
5587 if (!IsParameter) {
5588 Results.AddResult(CodeCompletionResult("instancetype"));
5589 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005590
Douglas Gregor99fa2642010-08-24 01:06:58 +00005591 // Add various builtin type names and specifiers.
5592 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5593 Results.ExitScope();
5594
5595 // Add the various type names
5596 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5597 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5598 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5599 CodeCompleter->includeGlobals());
5600
5601 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005602 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005603
5604 HandleCodeCompleteResults(this, CodeCompleter,
5605 CodeCompletionContext::CCC_Type,
5606 Results.data(), Results.size());
5607}
5608
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005609/// \brief When we have an expression with type "id", we may assume
5610/// that it has some more-specific class type based on knowledge of
5611/// common uses of Objective-C. This routine returns that class type,
5612/// or NULL if no better result could be determined.
5613static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005614 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005615 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005616 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005617
5618 Selector Sel = Msg->getSelector();
5619 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005620 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005621
5622 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5623 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005624 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005625
5626 ObjCMethodDecl *Method = Msg->getMethodDecl();
5627 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005628 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005629
5630 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005631 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005632 switch (Msg->getReceiverKind()) {
5633 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005634 if (const ObjCObjectType *ObjType
5635 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5636 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005637 break;
5638
5639 case ObjCMessageExpr::Instance: {
5640 QualType T = Msg->getInstanceReceiver()->getType();
5641 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5642 IFace = Ptr->getInterfaceDecl();
5643 break;
5644 }
5645
5646 case ObjCMessageExpr::SuperInstance:
5647 case ObjCMessageExpr::SuperClass:
5648 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005649 }
5650
5651 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005652 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005653
5654 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5655 if (Method->isInstanceMethod())
5656 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5657 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005658 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005659 .Case("autorelease", IFace)
5660 .Case("copy", IFace)
5661 .Case("copyWithZone", IFace)
5662 .Case("mutableCopy", IFace)
5663 .Case("mutableCopyWithZone", IFace)
5664 .Case("awakeFromCoder", IFace)
5665 .Case("replacementObjectFromCoder", IFace)
5666 .Case("class", IFace)
5667 .Case("classForCoder", IFace)
5668 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005669 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005670
5671 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5672 .Case("new", IFace)
5673 .Case("alloc", IFace)
5674 .Case("allocWithZone", IFace)
5675 .Case("class", IFace)
5676 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005677 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005678}
5679
Douglas Gregor6fc04132010-08-27 15:10:57 +00005680// Add a special completion for a message send to "super", which fills in the
5681// most likely case of forwarding all of our arguments to the superclass
5682// function.
5683///
5684/// \param S The semantic analysis object.
5685///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005686/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005687/// the "super" keyword. Otherwise, we just need to provide the arguments.
5688///
5689/// \param SelIdents The identifiers in the selector that have already been
5690/// provided as arguments for a send to "super".
5691///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005692/// \param Results The set of results to augment.
5693///
5694/// \returns the Objective-C method declaration that would be invoked by
5695/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005696static ObjCMethodDecl *AddSuperSendCompletion(
5697 Sema &S, bool NeedSuperKeyword,
5698 ArrayRef<IdentifierInfo *> SelIdents,
5699 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005700 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5701 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005702 return nullptr;
5703
Douglas Gregor6fc04132010-08-27 15:10:57 +00005704 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5705 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005706 return nullptr;
5707
Douglas Gregor6fc04132010-08-27 15:10:57 +00005708 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005709 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005710 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5711 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005712 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5713 CurMethod->isInstanceMethod());
5714
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005715 // Check in categories or class extensions.
5716 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005717 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005718 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005719 CurMethod->isInstanceMethod())))
5720 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005721 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005722 }
5723 }
5724
Douglas Gregor6fc04132010-08-27 15:10:57 +00005725 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005726 return nullptr;
5727
Douglas Gregor6fc04132010-08-27 15:10:57 +00005728 // Check whether the superclass method has the same signature.
5729 if (CurMethod->param_size() != SuperMethod->param_size() ||
5730 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005731 return nullptr;
5732
Douglas Gregor6fc04132010-08-27 15:10:57 +00005733 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5734 CurPEnd = CurMethod->param_end(),
5735 SuperP = SuperMethod->param_begin();
5736 CurP != CurPEnd; ++CurP, ++SuperP) {
5737 // Make sure the parameter types are compatible.
5738 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5739 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005740 return nullptr;
5741
Douglas Gregor6fc04132010-08-27 15:10:57 +00005742 // Make sure we have a parameter name to forward!
5743 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005744 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005745 }
5746
5747 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005748 CodeCompletionBuilder Builder(Results.getAllocator(),
5749 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005750
5751 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005752 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5753 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005754 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005755
5756 // If we need the "super" keyword, add it (plus some spacing).
5757 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005758 Builder.AddTypedTextChunk("super");
5759 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005760 }
5761
5762 Selector Sel = CurMethod->getSelector();
5763 if (Sel.isUnarySelector()) {
5764 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005765 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005766 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005767 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005768 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005769 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005770 } else {
5771 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5772 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005773 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005774 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005775
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005776 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005777 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005778 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005779 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005780 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005781 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005782 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005783 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005784 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005785 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005786 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005787 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005788 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005789 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005790 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005791 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005792 }
5793 }
5794 }
5795
Douglas Gregor78254c82012-03-27 23:34:16 +00005796 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5797 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005798 return SuperMethod;
5799}
5800
Douglas Gregora817a192010-05-27 23:06:34 +00005801void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005802 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005803 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005804 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005805 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005806 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005807 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5808 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005809
Douglas Gregora817a192010-05-27 23:06:34 +00005810 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5811 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005812 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5813 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005814
5815 // If we are in an Objective-C method inside a class that has a superclass,
5816 // add "super" as an option.
5817 if (ObjCMethodDecl *Method = getCurMethodDecl())
5818 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005819 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005820 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005821
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005822 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005823 }
Douglas Gregora817a192010-05-27 23:06:34 +00005824
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005825 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005826 addThisCompletion(*this, Results);
5827
Douglas Gregora817a192010-05-27 23:06:34 +00005828 Results.ExitScope();
5829
5830 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005831 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005832 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005833 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005834
5835}
5836
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005837void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005838 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005839 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005840 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005841 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5842 // Figure out which interface we're in.
5843 CDecl = CurMethod->getClassInterface();
5844 if (!CDecl)
5845 return;
5846
5847 // Find the superclass of this class.
5848 CDecl = CDecl->getSuperClass();
5849 if (!CDecl)
5850 return;
5851
5852 if (CurMethod->isInstanceMethod()) {
5853 // We are inside an instance method, which means that the message
5854 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005855 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005856 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005857 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005858 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005859 }
5860
5861 // Fall through to send to the superclass in CDecl.
5862 } else {
5863 // "super" may be the name of a type or variable. Figure out which
5864 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005865 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005866 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5867 LookupOrdinaryName);
5868 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5869 // "super" names an interface. Use it.
5870 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005871 if (const ObjCObjectType *Iface
5872 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5873 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005874 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5875 // "super" names an unresolved type; we can't be more specific.
5876 } else {
5877 // Assume that "super" names some kind of value and parse that way.
5878 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005879 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005880 UnqualifiedId id;
5881 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005882 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5883 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005884 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005885 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005886 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005887 }
5888
5889 // Fall through
5890 }
5891
John McCallba7bf592010-08-24 05:47:05 +00005892 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005893 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005894 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005895 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005896 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005897 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005898}
5899
Douglas Gregor74661272010-09-21 00:03:25 +00005900/// \brief Given a set of code-completion results for the argument of a message
5901/// send, determine the preferred type (if any) for that argument expression.
5902static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5903 unsigned NumSelIdents) {
5904 typedef CodeCompletionResult Result;
5905 ASTContext &Context = Results.getSema().Context;
5906
5907 QualType PreferredType;
5908 unsigned BestPriority = CCP_Unlikely * 2;
5909 Result *ResultsData = Results.data();
5910 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5911 Result &R = ResultsData[I];
5912 if (R.Kind == Result::RK_Declaration &&
5913 isa<ObjCMethodDecl>(R.Declaration)) {
5914 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005915 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005916 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005917 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005918 ->getType();
5919 if (R.Priority < BestPriority || PreferredType.isNull()) {
5920 BestPriority = R.Priority;
5921 PreferredType = MyPreferredType;
5922 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5923 MyPreferredType)) {
5924 PreferredType = QualType();
5925 }
5926 }
5927 }
5928 }
5929 }
5930
5931 return PreferredType;
5932}
5933
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005934static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5935 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005936 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005937 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005938 bool IsSuper,
5939 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005940 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005941 ObjCInterfaceDecl *CDecl = nullptr;
5942
Douglas Gregor8ce33212009-11-17 17:59:40 +00005943 // If the given name refers to an interface type, retrieve the
5944 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005945 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005946 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005947 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005948 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5949 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005950 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005951
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005952 // Add all of the factory methods in this Objective-C class, its protocols,
5953 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005954 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005955
Douglas Gregor6fc04132010-08-27 15:10:57 +00005956 // If this is a send-to-super, try to add the special "super" send
5957 // completion.
5958 if (IsSuper) {
5959 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005960 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005961 Results.Ignore(SuperMethod);
5962 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005963
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005964 // If we're inside an Objective-C method definition, prefer its selector to
5965 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005966 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005967 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005968
Douglas Gregor1154e272010-09-16 16:06:31 +00005969 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005970 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005971 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005972 SemaRef.CurContext, Selectors, AtArgumentExpression,
5973 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005974 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005975 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005976
Douglas Gregord720daf2010-04-06 17:30:22 +00005977 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005978 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005979 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005980 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005981 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005982 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005983 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005984 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005985 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005986
5987 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005988 }
5989 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005990
5991 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5992 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005993 M != MEnd; ++M) {
5994 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005995 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005996 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005997 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005998 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005999
Nico Weber2e0c8f72014-12-27 03:58:08 +00006000 Result R(MethList->getMethod(),
6001 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006002 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006003 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006004 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00006005 }
6006 }
6007 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006008
6009 Results.ExitScope();
6010}
Douglas Gregor6285f752010-04-06 16:40:00 +00006011
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006012void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006013 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006014 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00006015 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00006016
6017 QualType T = this->GetTypeFromParser(Receiver);
6018
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006019 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006020 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006021 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006022 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006023
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006024 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006025 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00006026
6027 // If we're actually at the argument expression (rather than prior to the
6028 // selector), we're actually performing code completion for an expression.
6029 // Determine whether we have a single, best method. If so, we can
6030 // code-complete the expression using the corresponding parameter type as
6031 // our preferred type, improving completion results.
6032 if (AtArgumentExpression) {
6033 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006034 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006035 if (PreferredType.isNull())
6036 CodeCompleteOrdinaryName(S, PCC_Expression);
6037 else
6038 CodeCompleteExpression(S, PreferredType);
6039 return;
6040 }
6041
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006042 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006043 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00006044 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006045}
6046
Richard Trieu2bd04012011-09-09 02:00:50 +00006047void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006048 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00006049 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00006050 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00006051 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00006052
6053 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00006054
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006055 // If necessary, apply function/array conversion to the receiver.
6056 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00006057 if (RecExpr) {
6058 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6059 if (Conv.isInvalid()) // conversion failed. bail.
6060 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006061 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00006062 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00006063 QualType ReceiverType = RecExpr? RecExpr->getType()
6064 : Super? Context.getObjCObjectPointerType(
6065 Context.getObjCInterfaceType(Super))
6066 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00006067
Douglas Gregordc520b02010-11-08 21:12:30 +00006068 // If we're messaging an expression with type "id" or "Class", check
6069 // whether we know something special about the receiver that allows
6070 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00006071 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00006072 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6073 if (ReceiverType->isObjCClassType())
6074 return CodeCompleteObjCClassMessage(S,
6075 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006076 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00006077 AtArgumentExpression, Super);
6078
6079 ReceiverType = Context.getObjCObjectPointerType(
6080 Context.getObjCInterfaceType(IFace));
6081 }
Anders Carlsson382ba412014-02-28 19:07:22 +00006082 } else if (RecExpr && getLangOpts().CPlusPlus) {
6083 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6084 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006085 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00006086 ReceiverType = RecExpr->getType();
6087 }
6088 }
Douglas Gregordc520b02010-11-08 21:12:30 +00006089
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006090 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006091 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006092 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00006093 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006094 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00006095
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006096 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00006097
Douglas Gregor6fc04132010-08-27 15:10:57 +00006098 // If this is a send-to-super, try to add the special "super" send
6099 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00006100 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00006101 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006102 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00006103 Results.Ignore(SuperMethod);
6104 }
6105
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00006106 // If we're inside an Objective-C method definition, prefer its selector to
6107 // others.
6108 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6109 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00006110
Douglas Gregor1154e272010-09-16 16:06:31 +00006111 // Keep track of the selectors we've already added.
6112 VisitedSelectorSet Selectors;
6113
Douglas Gregora3329fa2009-11-18 00:06:18 +00006114 // Handle messages to Class. This really isn't a message to an instance
6115 // method, so we treat it the same way we would treat a message send to a
6116 // class method.
6117 if (ReceiverType->isObjCClassType() ||
6118 ReceiverType->isObjCQualifiedClassType()) {
6119 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6120 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006121 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006122 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006123 }
6124 }
6125 // Handle messages to a qualified ID ("id<foo>").
6126 else if (const ObjCObjectPointerType *QualID
6127 = ReceiverType->getAsObjCQualifiedIdType()) {
6128 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006129 for (auto *I : QualID->quals())
6130 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006131 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006132 }
6133 // Handle messages to a pointer to interface type.
6134 else if (const ObjCObjectPointerType *IFacePtr
6135 = ReceiverType->getAsObjCInterfacePointerType()) {
6136 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00006137 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006138 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006139 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006140
6141 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00006142 for (auto *I : IFacePtr->quals())
6143 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00006144 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00006145 }
Douglas Gregor6285f752010-04-06 16:40:00 +00006146 // Handle messages to "id".
6147 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00006148 // We're messaging "id", so provide all instance methods we know
6149 // about as code-completion results.
6150
6151 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00006152 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00006153 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00006154 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6155 I != N; ++I) {
6156 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00006157 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00006158 continue;
6159
Sebastian Redl75d8a322010-08-02 23:18:59 +00006160 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00006161 }
6162 }
6163
Sebastian Redl75d8a322010-08-02 23:18:59 +00006164 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6165 MEnd = MethodPool.end();
6166 M != MEnd; ++M) {
6167 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00006168 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006169 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00006170 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00006171 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00006172
Nico Weber2e0c8f72014-12-27 03:58:08 +00006173 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00006174 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00006175
Nico Weber2e0c8f72014-12-27 03:58:08 +00006176 Result R(MethList->getMethod(),
6177 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006178 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00006179 R.AllParametersAreInformative = false;
6180 Results.MaybeAddResult(R, CurContext);
6181 }
6182 }
6183 }
Steve Naroffeae65032009-11-07 02:08:14 +00006184 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00006185
6186
6187 // If we're actually at the argument expression (rather than prior to the
6188 // selector), we're actually performing code completion for an expression.
6189 // Determine whether we have a single, best method. If so, we can
6190 // code-complete the expression using the corresponding parameter type as
6191 // our preferred type, improving completion results.
6192 if (AtArgumentExpression) {
6193 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006194 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00006195 if (PreferredType.isNull())
6196 CodeCompleteOrdinaryName(S, PCC_Expression);
6197 else
6198 CodeCompleteExpression(S, PreferredType);
6199 return;
6200 }
6201
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006202 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00006203 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006204 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00006205}
Douglas Gregorbaf69612009-11-18 04:19:12 +00006206
Douglas Gregor68762e72010-08-23 21:17:50 +00006207void Sema::CodeCompleteObjCForCollection(Scope *S,
6208 DeclGroupPtrTy IterationVar) {
6209 CodeCompleteExpressionData Data;
6210 Data.ObjCCollection = true;
6211
6212 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00006213 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00006214 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6215 if (*I)
6216 Data.IgnoreDecls.push_back(*I);
6217 }
6218 }
6219
6220 CodeCompleteExpression(S, Data);
6221}
6222
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006223void Sema::CodeCompleteObjCSelector(Scope *S,
6224 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00006225 // If we have an external source, load the entire class method
6226 // pool from the AST file.
6227 if (ExternalSource) {
6228 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6229 I != N; ++I) {
6230 Selector Sel = ExternalSource->GetExternalSelector(I);
6231 if (Sel.isNull() || MethodPool.count(Sel))
6232 continue;
6233
6234 ReadMethodPool(Sel);
6235 }
6236 }
6237
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006238 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006239 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006240 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00006241 Results.EnterNewScope();
6242 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6243 MEnd = MethodPool.end();
6244 M != MEnd; ++M) {
6245
6246 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006247 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00006248 continue;
6249
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006250 CodeCompletionBuilder Builder(Results.getAllocator(),
6251 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006252 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006253 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006254 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006255 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006256 continue;
6257 }
6258
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006259 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00006260 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00006261 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006262 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006263 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006264 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006265 Accumulator.clear();
6266 }
6267 }
6268
Benjamin Kramer632500c2011-07-26 16:59:25 +00006269 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00006270 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00006271 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006272 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006273 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00006274 }
6275 Results.ExitScope();
6276
6277 HandleCodeCompleteResults(this, CodeCompleter,
6278 CodeCompletionContext::CCC_SelectorName,
6279 Results.data(), Results.size());
6280}
6281
Douglas Gregorbaf69612009-11-18 04:19:12 +00006282/// \brief Add all of the protocol declarations that we find in the given
6283/// (translation unit) context.
6284static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006285 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00006286 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006287 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00006288
Aaron Ballman629afae2014-03-07 19:56:05 +00006289 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00006290 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006291 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00006292 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00006293 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6294 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006295 }
6296}
6297
Craig Topper883dd332015-12-24 23:58:11 +00006298void Sema::CodeCompleteObjCProtocolReferences(
6299 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006300 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006301 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006302 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006303
Chandler Carruthede11632016-11-04 06:06:50 +00006304 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006305 Results.EnterNewScope();
6306
6307 // Tell the result set to ignore all of the protocols we have
6308 // already seen.
6309 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00006310 for (const IdentifierLocPair &Pair : Protocols)
6311 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6312 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00006313 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006314
Douglas Gregora3b23b02010-12-09 21:44:02 +00006315 // Add all protocols.
6316 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6317 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006318
Douglas Gregora3b23b02010-12-09 21:44:02 +00006319 Results.ExitScope();
6320 }
6321
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006322 HandleCodeCompleteResults(this, CodeCompleter,
6323 CodeCompletionContext::CCC_ObjCProtocolName,
6324 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006325}
6326
6327void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006328 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006329 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006330 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00006331
Chandler Carruthede11632016-11-04 06:06:50 +00006332 if (CodeCompleter->includeGlobals()) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00006333 Results.EnterNewScope();
6334
6335 // Add all protocols.
6336 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6337 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00006338
Douglas Gregora3b23b02010-12-09 21:44:02 +00006339 Results.ExitScope();
6340 }
6341
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006342 HandleCodeCompleteResults(this, CodeCompleter,
6343 CodeCompletionContext::CCC_ObjCProtocolName,
6344 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00006345}
Douglas Gregor49c22a72009-11-18 16:26:39 +00006346
6347/// \brief Add all of the Objective-C interface declarations that we find in
6348/// the given (translation unit) context.
6349static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6350 bool OnlyForwardDeclarations,
6351 bool OnlyUnimplemented,
6352 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00006353 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00006354
Aaron Ballman629afae2014-03-07 19:56:05 +00006355 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00006356 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00006357 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00006358 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00006359 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00006360 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6361 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006362 }
6363}
6364
6365void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006366 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006367 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006368 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006369 Results.EnterNewScope();
6370
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006371 if (CodeCompleter->includeGlobals()) {
6372 // Add all classes.
6373 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6374 false, Results);
6375 }
6376
Douglas Gregor49c22a72009-11-18 16:26:39 +00006377 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006378
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006379 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006380 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006381 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006382}
6383
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006384void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6385 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006386 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006387 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006388 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006389 Results.EnterNewScope();
6390
6391 // Make sure that we ignore the class we're currently defining.
6392 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006393 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006394 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006395 Results.Ignore(CurClass);
6396
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006397 if (CodeCompleter->includeGlobals()) {
6398 // Add all classes.
6399 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6400 false, Results);
6401 }
6402
Douglas Gregor49c22a72009-11-18 16:26:39 +00006403 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006404
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006405 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006406 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006407 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006408}
6409
6410void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006411 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006412 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006413 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006414 Results.EnterNewScope();
6415
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006416 if (CodeCompleter->includeGlobals()) {
6417 // Add all unimplemented classes.
6418 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6419 true, Results);
6420 }
6421
Douglas Gregor49c22a72009-11-18 16:26:39 +00006422 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006423
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006424 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006425 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006426 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006427}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006428
6429void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006430 IdentifierInfo *ClassName,
6431 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006432 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006433
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006434 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006435 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006436 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006437
6438 // Ignore any categories we find that have already been implemented by this
6439 // interface.
6440 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6441 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006442 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006443 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006444 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006445 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006446 }
6447
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006448 // Add all of the categories we know about.
6449 Results.EnterNewScope();
6450 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006451 for (const auto *D : TU->decls())
6452 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006453 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006454 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6455 nullptr),
6456 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006457 Results.ExitScope();
6458
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006459 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006460 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006461 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006462}
6463
6464void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006465 IdentifierInfo *ClassName,
6466 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006467 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006468
6469 // Find the corresponding interface. If we couldn't find the interface, the
6470 // program itself is ill-formed. However, we'll try to be helpful still by
6471 // providing the list of all of the categories we know about.
6472 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006473 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006474 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6475 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006476 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006477
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006478 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006479 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006480 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006481
6482 // Add all of the categories that have have corresponding interface
6483 // declarations in this class and any of its superclasses, except for
6484 // already-implemented categories in the class itself.
6485 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6486 Results.EnterNewScope();
6487 bool IgnoreImplemented = true;
6488 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006489 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006490 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006491 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006492 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6493 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006494 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006495
6496 Class = Class->getSuperClass();
6497 IgnoreImplemented = false;
6498 }
6499 Results.ExitScope();
6500
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006501 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006502 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006503 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006504}
Douglas Gregor5d649882009-11-18 22:32:06 +00006505
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006506void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006507 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006508 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006509 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006510 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006511
6512 // Figure out where this @synthesize lives.
6513 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006514 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006515 if (!Container ||
6516 (!isa<ObjCImplementationDecl>(Container) &&
6517 !isa<ObjCCategoryImplDecl>(Container)))
6518 return;
6519
6520 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006521 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006522 for (const auto *D : Container->decls())
6523 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006524 Results.Ignore(PropertyImpl->getPropertyDecl());
6525
6526 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006527 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006528 Results.EnterNewScope();
6529 if (ObjCImplementationDecl *ClassImpl
6530 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006531 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006532 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006533 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006534 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006535 AddObjCProperties(CCContext,
6536 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006537 false, /*AllowNullaryMethods=*/false, CurContext,
6538 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006539 Results.ExitScope();
6540
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006541 HandleCodeCompleteResults(this, CodeCompleter,
6542 CodeCompletionContext::CCC_Other,
6543 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006544}
6545
6546void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006547 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006548 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006549 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006550 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006551 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006552
6553 // Figure out where this @synthesize lives.
6554 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006555 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006556 if (!Container ||
6557 (!isa<ObjCImplementationDecl>(Container) &&
6558 !isa<ObjCCategoryImplDecl>(Container)))
6559 return;
6560
6561 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006562 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006563 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006564 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006565 Class = ClassImpl->getClassInterface();
6566 else
6567 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6568 ->getClassInterface();
6569
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006570 // Determine the type of the property we're synthesizing.
6571 QualType PropertyType = Context.getObjCIdType();
6572 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006573 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6574 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006575 PropertyType
6576 = Property->getType().getNonReferenceType().getUnqualifiedType();
6577
6578 // Give preference to ivars
6579 Results.setPreferredType(PropertyType);
6580 }
6581 }
6582
Douglas Gregor5d649882009-11-18 22:32:06 +00006583 // Add all of the instance variables in this class and its superclasses.
6584 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006585 bool SawSimilarlyNamedIvar = false;
6586 std::string NameWithPrefix;
6587 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006588 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006589 std::string NameWithSuffix = PropertyName->getName().str();
6590 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006591 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006592 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6593 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006594 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6595 CurContext, nullptr, false);
6596
Douglas Gregor331faa02011-04-18 14:13:53 +00006597 // Determine whether we've seen an ivar with a name similar to the
6598 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006599 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006600 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006601 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006602 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006603
6604 // Reduce the priority of this result by one, to give it a slight
6605 // advantage over other results whose names don't match so closely.
6606 if (Results.size() &&
6607 Results.data()[Results.size() - 1].Kind
6608 == CodeCompletionResult::RK_Declaration &&
6609 Results.data()[Results.size() - 1].Declaration == Ivar)
6610 Results.data()[Results.size() - 1].Priority--;
6611 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006612 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006613 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006614
6615 if (!SawSimilarlyNamedIvar) {
6616 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006617 // an ivar of the appropriate type.
6618 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006619 typedef CodeCompletionResult Result;
6620 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006621 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6622 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006623
Douglas Gregor75acd922011-09-27 23:30:47 +00006624 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006625 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006626 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006627 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6628 Results.AddResult(Result(Builder.TakeString(), Priority,
6629 CXCursor_ObjCIvarDecl));
6630 }
6631
Douglas Gregor5d649882009-11-18 22:32:06 +00006632 Results.ExitScope();
6633
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006634 HandleCodeCompleteResults(this, CodeCompleter,
6635 CodeCompletionContext::CCC_Other,
6636 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006637}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006638
Douglas Gregor416b5752010-08-25 01:08:01 +00006639// Mapping from selectors to the methods that implement that selector, along
6640// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006641typedef llvm::DenseMap<
6642 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006643
6644/// \brief Find all of the methods that reside in the given container
6645/// (and its superclasses, protocols, etc.) that meet the given
6646/// criteria. Insert those methods into the map of known methods,
6647/// indexed by selector so they can be easily found.
6648static void FindImplementableMethods(ASTContext &Context,
6649 ObjCContainerDecl *Container,
6650 bool WantInstanceMethods,
6651 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006652 KnownMethodsMap &KnownMethods,
6653 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006654 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006655 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006656 if (!IFace->hasDefinition())
6657 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006658
6659 IFace = IFace->getDefinition();
6660 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006661
Douglas Gregor636a61e2010-04-07 00:21:17 +00006662 const ObjCList<ObjCProtocolDecl> &Protocols
6663 = IFace->getReferencedProtocols();
6664 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006665 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006666 I != E; ++I)
6667 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006668 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006669
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006670 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006671 for (auto *Cat : IFace->visible_categories()) {
6672 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006673 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006674 }
6675
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006676 // Visit the superclass.
6677 if (IFace->getSuperClass())
6678 FindImplementableMethods(Context, IFace->getSuperClass(),
6679 WantInstanceMethods, ReturnType,
6680 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006681 }
6682
6683 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6684 // Recurse into protocols.
6685 const ObjCList<ObjCProtocolDecl> &Protocols
6686 = Category->getReferencedProtocols();
6687 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006688 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006689 I != E; ++I)
6690 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006691 KnownMethods, InOriginalClass);
6692
6693 // If this category is the original class, jump to the interface.
6694 if (InOriginalClass && Category->getClassInterface())
6695 FindImplementableMethods(Context, Category->getClassInterface(),
6696 WantInstanceMethods, ReturnType, KnownMethods,
6697 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006698 }
6699
6700 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006701 // Make sure we have a definition; that's what we'll walk.
6702 if (!Protocol->hasDefinition())
6703 return;
6704 Protocol = Protocol->getDefinition();
6705 Container = Protocol;
6706
6707 // Recurse into protocols.
6708 const ObjCList<ObjCProtocolDecl> &Protocols
6709 = Protocol->getReferencedProtocols();
6710 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6711 E = Protocols.end();
6712 I != E; ++I)
6713 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6714 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006715 }
6716
6717 // Add methods in this container. This operation occurs last because
6718 // we want the methods from this container to override any methods
6719 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006720 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006721 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006722 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006723 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006724 continue;
6725
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006726 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006727 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006728 }
6729 }
6730}
6731
Douglas Gregor669a25a2011-02-17 00:22:45 +00006732/// \brief Add the parenthesized return or parameter type chunk to a code
6733/// completion string.
6734static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006735 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006736 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006737 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006738 CodeCompletionBuilder &Builder) {
6739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006740 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006741 if (!Quals.empty())
6742 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006743 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006744 Builder.getAllocator()));
6745 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6746}
6747
6748/// \brief Determine whether the given class is or inherits from a class by
6749/// the given name.
6750static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006751 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006752 if (!Class)
6753 return false;
6754
6755 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6756 return true;
6757
6758 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6759}
6760
6761/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6762/// Key-Value Observing (KVO).
6763static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6764 bool IsInstanceMethod,
6765 QualType ReturnType,
6766 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006767 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006768 ResultBuilder &Results) {
6769 IdentifierInfo *PropName = Property->getIdentifier();
6770 if (!PropName || PropName->getLength() == 0)
6771 return;
6772
Douglas Gregor75acd922011-09-27 23:30:47 +00006773 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6774
Douglas Gregor669a25a2011-02-17 00:22:45 +00006775 // Builder that will create each code completion.
6776 typedef CodeCompletionResult Result;
6777 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006778 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006779
6780 // The selector table.
6781 SelectorTable &Selectors = Context.Selectors;
6782
6783 // The property name, copied into the code completion allocation region
6784 // on demand.
6785 struct KeyHolder {
6786 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006787 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006788 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006789
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006790 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006791 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6792
Douglas Gregor669a25a2011-02-17 00:22:45 +00006793 operator const char *() {
6794 if (CopiedKey)
6795 return CopiedKey;
6796
6797 return CopiedKey = Allocator.CopyString(Key);
6798 }
6799 } Key(Allocator, PropName->getName());
6800
6801 // The uppercased name of the property name.
6802 std::string UpperKey = PropName->getName();
6803 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006804 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006805
6806 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6807 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6808 Property->getType());
6809 bool ReturnTypeMatchesVoid
6810 = ReturnType.isNull() || ReturnType->isVoidType();
6811
6812 // Add the normal accessor -(type)key.
6813 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006814 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006815 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6816 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006817 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6818 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006819
6820 Builder.AddTypedTextChunk(Key);
6821 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6822 CXCursor_ObjCInstanceMethodDecl));
6823 }
6824
6825 // If we have an integral or boolean property (or the user has provided
6826 // an integral or boolean return type), add the accessor -(type)isKey.
6827 if (IsInstanceMethod &&
6828 ((!ReturnType.isNull() &&
6829 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6830 (ReturnType.isNull() &&
6831 (Property->getType()->isIntegerType() ||
6832 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006833 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006834 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006835 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6836 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006837 if (ReturnType.isNull()) {
6838 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6839 Builder.AddTextChunk("BOOL");
6840 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6841 }
6842
6843 Builder.AddTypedTextChunk(
6844 Allocator.CopyString(SelectorId->getName()));
6845 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6846 CXCursor_ObjCInstanceMethodDecl));
6847 }
6848 }
6849
6850 // Add the normal mutator.
6851 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6852 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006853 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006854 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006855 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006856 if (ReturnType.isNull()) {
6857 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6858 Builder.AddTextChunk("void");
6859 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6860 }
6861
6862 Builder.AddTypedTextChunk(
6863 Allocator.CopyString(SelectorId->getName()));
6864 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006865 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6866 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006867 Builder.AddTextChunk(Key);
6868 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6869 CXCursor_ObjCInstanceMethodDecl));
6870 }
6871 }
6872
6873 // Indexed and unordered accessors
6874 unsigned IndexedGetterPriority = CCP_CodePattern;
6875 unsigned IndexedSetterPriority = CCP_CodePattern;
6876 unsigned UnorderedGetterPriority = CCP_CodePattern;
6877 unsigned UnorderedSetterPriority = CCP_CodePattern;
6878 if (const ObjCObjectPointerType *ObjCPointer
6879 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6880 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6881 // If this interface type is not provably derived from a known
6882 // collection, penalize the corresponding completions.
6883 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6884 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6885 if (!InheritsFromClassNamed(IFace, "NSArray"))
6886 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6887 }
6888
6889 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6890 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6891 if (!InheritsFromClassNamed(IFace, "NSSet"))
6892 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6893 }
6894 }
6895 } else {
6896 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6897 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6898 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6899 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6900 }
6901
6902 // Add -(NSUInteger)countOf<key>
6903 if (IsInstanceMethod &&
6904 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006905 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006906 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006907 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6908 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006909 if (ReturnType.isNull()) {
6910 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6911 Builder.AddTextChunk("NSUInteger");
6912 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6913 }
6914
6915 Builder.AddTypedTextChunk(
6916 Allocator.CopyString(SelectorId->getName()));
6917 Results.AddResult(Result(Builder.TakeString(),
6918 std::min(IndexedGetterPriority,
6919 UnorderedGetterPriority),
6920 CXCursor_ObjCInstanceMethodDecl));
6921 }
6922 }
6923
6924 // Indexed getters
6925 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6926 if (IsInstanceMethod &&
6927 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006928 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006929 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006930 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006931 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006932 if (ReturnType.isNull()) {
6933 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6934 Builder.AddTextChunk("id");
6935 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6936 }
6937
6938 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6939 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6940 Builder.AddTextChunk("NSUInteger");
6941 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6942 Builder.AddTextChunk("index");
6943 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6944 CXCursor_ObjCInstanceMethodDecl));
6945 }
6946 }
6947
6948 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6949 if (IsInstanceMethod &&
6950 (ReturnType.isNull() ||
6951 (ReturnType->isObjCObjectPointerType() &&
6952 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6953 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6954 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006955 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006956 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006957 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006958 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006959 if (ReturnType.isNull()) {
6960 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6961 Builder.AddTextChunk("NSArray *");
6962 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6963 }
6964
6965 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6966 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6967 Builder.AddTextChunk("NSIndexSet *");
6968 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6969 Builder.AddTextChunk("indexes");
6970 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6971 CXCursor_ObjCInstanceMethodDecl));
6972 }
6973 }
6974
6975 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6976 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006977 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006978 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006979 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006980 &Context.Idents.get("range")
6981 };
6982
David Blaikie82e95a32014-11-19 07:49:47 +00006983 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006984 if (ReturnType.isNull()) {
6985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6986 Builder.AddTextChunk("void");
6987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6988 }
6989
6990 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6992 Builder.AddPlaceholderChunk("object-type");
6993 Builder.AddTextChunk(" **");
6994 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6995 Builder.AddTextChunk("buffer");
6996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6997 Builder.AddTypedTextChunk("range:");
6998 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6999 Builder.AddTextChunk("NSRange");
7000 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7001 Builder.AddTextChunk("inRange");
7002 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7003 CXCursor_ObjCInstanceMethodDecl));
7004 }
7005 }
7006
7007 // Mutable indexed accessors
7008
7009 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
7010 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007011 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007012 IdentifierInfo *SelectorIds[2] = {
7013 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007014 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007015 };
7016
David Blaikie82e95a32014-11-19 07:49:47 +00007017 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007018 if (ReturnType.isNull()) {
7019 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7020 Builder.AddTextChunk("void");
7021 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7022 }
7023
7024 Builder.AddTypedTextChunk("insertObject:");
7025 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7026 Builder.AddPlaceholderChunk("object-type");
7027 Builder.AddTextChunk(" *");
7028 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7029 Builder.AddTextChunk("object");
7030 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7031 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7032 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7033 Builder.AddPlaceholderChunk("NSUInteger");
7034 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7035 Builder.AddTextChunk("index");
7036 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7037 CXCursor_ObjCInstanceMethodDecl));
7038 }
7039 }
7040
7041 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7042 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007043 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007044 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007045 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007046 &Context.Idents.get("atIndexes")
7047 };
7048
David Blaikie82e95a32014-11-19 07:49:47 +00007049 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007050 if (ReturnType.isNull()) {
7051 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7052 Builder.AddTextChunk("void");
7053 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7054 }
7055
7056 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7057 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7058 Builder.AddTextChunk("NSArray *");
7059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7060 Builder.AddTextChunk("array");
7061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7062 Builder.AddTypedTextChunk("atIndexes:");
7063 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7064 Builder.AddPlaceholderChunk("NSIndexSet *");
7065 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7066 Builder.AddTextChunk("indexes");
7067 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7068 CXCursor_ObjCInstanceMethodDecl));
7069 }
7070 }
7071
7072 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7073 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007074 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007075 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007076 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007077 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007078 if (ReturnType.isNull()) {
7079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7080 Builder.AddTextChunk("void");
7081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7082 }
7083
7084 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7085 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7086 Builder.AddTextChunk("NSUInteger");
7087 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7088 Builder.AddTextChunk("index");
7089 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7090 CXCursor_ObjCInstanceMethodDecl));
7091 }
7092 }
7093
7094 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7095 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007096 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007097 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007098 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007099 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007100 if (ReturnType.isNull()) {
7101 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7102 Builder.AddTextChunk("void");
7103 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7104 }
7105
7106 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7107 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7108 Builder.AddTextChunk("NSIndexSet *");
7109 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7110 Builder.AddTextChunk("indexes");
7111 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7112 CXCursor_ObjCInstanceMethodDecl));
7113 }
7114 }
7115
7116 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7117 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007118 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007119 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007120 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007121 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00007122 &Context.Idents.get("withObject")
7123 };
7124
David Blaikie82e95a32014-11-19 07:49:47 +00007125 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007126 if (ReturnType.isNull()) {
7127 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7128 Builder.AddTextChunk("void");
7129 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7130 }
7131
7132 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7133 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7134 Builder.AddPlaceholderChunk("NSUInteger");
7135 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7136 Builder.AddTextChunk("index");
7137 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7138 Builder.AddTypedTextChunk("withObject:");
7139 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7140 Builder.AddTextChunk("id");
7141 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7142 Builder.AddTextChunk("object");
7143 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7144 CXCursor_ObjCInstanceMethodDecl));
7145 }
7146 }
7147
7148 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7149 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007150 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007151 = (Twine("replace") + UpperKey + "AtIndexes").str();
7152 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00007153 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007154 &Context.Idents.get(SelectorName1),
7155 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00007156 };
7157
David Blaikie82e95a32014-11-19 07:49:47 +00007158 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007159 if (ReturnType.isNull()) {
7160 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7161 Builder.AddTextChunk("void");
7162 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7163 }
7164
7165 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7166 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7167 Builder.AddPlaceholderChunk("NSIndexSet *");
7168 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7169 Builder.AddTextChunk("indexes");
7170 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7171 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7172 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7173 Builder.AddTextChunk("NSArray *");
7174 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7175 Builder.AddTextChunk("array");
7176 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7177 CXCursor_ObjCInstanceMethodDecl));
7178 }
7179 }
7180
7181 // Unordered getters
7182 // - (NSEnumerator *)enumeratorOfKey
7183 if (IsInstanceMethod &&
7184 (ReturnType.isNull() ||
7185 (ReturnType->isObjCObjectPointerType() &&
7186 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7187 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7188 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007189 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007190 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007191 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7192 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007193 if (ReturnType.isNull()) {
7194 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7195 Builder.AddTextChunk("NSEnumerator *");
7196 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7197 }
7198
7199 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7200 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7201 CXCursor_ObjCInstanceMethodDecl));
7202 }
7203 }
7204
7205 // - (type *)memberOfKey:(type *)object
7206 if (IsInstanceMethod &&
7207 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007208 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007209 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007210 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007211 if (ReturnType.isNull()) {
7212 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7213 Builder.AddPlaceholderChunk("object-type");
7214 Builder.AddTextChunk(" *");
7215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7216 }
7217
7218 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7220 if (ReturnType.isNull()) {
7221 Builder.AddPlaceholderChunk("object-type");
7222 Builder.AddTextChunk(" *");
7223 } else {
7224 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00007225 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00007226 Builder.getAllocator()));
7227 }
7228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7229 Builder.AddTextChunk("object");
7230 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7231 CXCursor_ObjCInstanceMethodDecl));
7232 }
7233 }
7234
7235 // Mutable unordered accessors
7236 // - (void)addKeyObject:(type *)object
7237 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007238 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007239 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007240 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007241 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007242 if (ReturnType.isNull()) {
7243 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7244 Builder.AddTextChunk("void");
7245 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7246 }
7247
7248 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7249 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7250 Builder.AddPlaceholderChunk("object-type");
7251 Builder.AddTextChunk(" *");
7252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7253 Builder.AddTextChunk("object");
7254 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7255 CXCursor_ObjCInstanceMethodDecl));
7256 }
7257 }
7258
7259 // - (void)addKey:(NSSet *)objects
7260 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007261 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007262 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007263 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007264 if (ReturnType.isNull()) {
7265 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7266 Builder.AddTextChunk("void");
7267 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7268 }
7269
7270 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7271 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7272 Builder.AddTextChunk("NSSet *");
7273 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7274 Builder.AddTextChunk("objects");
7275 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7276 CXCursor_ObjCInstanceMethodDecl));
7277 }
7278 }
7279
7280 // - (void)removeKeyObject:(type *)object
7281 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007282 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007283 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007284 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007285 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007286 if (ReturnType.isNull()) {
7287 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7288 Builder.AddTextChunk("void");
7289 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7290 }
7291
7292 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7293 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7294 Builder.AddPlaceholderChunk("object-type");
7295 Builder.AddTextChunk(" *");
7296 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7297 Builder.AddTextChunk("object");
7298 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7299 CXCursor_ObjCInstanceMethodDecl));
7300 }
7301 }
7302
7303 // - (void)removeKey:(NSSet *)objects
7304 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007305 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007306 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007307 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007308 if (ReturnType.isNull()) {
7309 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7310 Builder.AddTextChunk("void");
7311 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7312 }
7313
7314 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7316 Builder.AddTextChunk("NSSet *");
7317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7318 Builder.AddTextChunk("objects");
7319 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7320 CXCursor_ObjCInstanceMethodDecl));
7321 }
7322 }
7323
7324 // - (void)intersectKey:(NSSet *)objects
7325 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007326 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007327 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007328 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007329 if (ReturnType.isNull()) {
7330 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7331 Builder.AddTextChunk("void");
7332 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7333 }
7334
7335 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7336 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7337 Builder.AddTextChunk("NSSet *");
7338 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7339 Builder.AddTextChunk("objects");
7340 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7341 CXCursor_ObjCInstanceMethodDecl));
7342 }
7343 }
7344
7345 // Key-Value Observing
7346 // + (NSSet *)keyPathsForValuesAffectingKey
7347 if (!IsInstanceMethod &&
7348 (ReturnType.isNull() ||
7349 (ReturnType->isObjCObjectPointerType() &&
7350 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7351 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7352 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007353 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007354 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00007355 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007356 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7357 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00007358 if (ReturnType.isNull()) {
7359 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Alex Lorenz71ecb072016-12-08 16:49:05 +00007360 Builder.AddTextChunk("NSSet<NSString *> *");
Douglas Gregor669a25a2011-02-17 00:22:45 +00007361 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7362 }
7363
7364 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7365 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00007366 CXCursor_ObjCClassMethodDecl));
7367 }
7368 }
7369
7370 // + (BOOL)automaticallyNotifiesObserversForKey
7371 if (!IsInstanceMethod &&
7372 (ReturnType.isNull() ||
7373 ReturnType->isIntegerType() ||
7374 ReturnType->isBooleanType())) {
7375 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007376 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007377 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007378 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7379 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007380 if (ReturnType.isNull()) {
7381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7382 Builder.AddTextChunk("BOOL");
7383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7384 }
7385
7386 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7387 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7388 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007389 }
7390 }
7391}
7392
Douglas Gregor636a61e2010-04-07 00:21:17 +00007393void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7394 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007395 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007396 // Determine the return type of the method we're declaring, if
7397 // provided.
7398 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007399 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007400 if (CurContext->isObjCContainer()) {
7401 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7402 IDecl = cast<Decl>(OCD);
7403 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007404 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007405 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007406 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007407 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007408 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7409 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007410 IsInImplementation = true;
7411 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007412 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007413 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007414 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007415 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007416 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007417 }
7418
7419 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007420 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007421 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007422 }
7423
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007424 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007425 HandleCodeCompleteResults(this, CodeCompleter,
7426 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007427 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007428 return;
7429 }
7430
7431 // Find all of the methods that we could declare/implement here.
7432 KnownMethodsMap KnownMethods;
7433 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007434 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007435
Douglas Gregor636a61e2010-04-07 00:21:17 +00007436 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007437 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007439 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007440 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007441 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007442 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007443 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7444 MEnd = KnownMethods.end();
7445 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007446 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007447 CodeCompletionBuilder Builder(Results.getAllocator(),
7448 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007449
7450 // If the result type was not already provided, add it to the
7451 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007452 if (ReturnType.isNull()) {
7453 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7454 AttributedType::stripOuterNullability(ResTy);
7455 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007456 Method->getObjCDeclQualifier(), Context, Policy,
7457 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007458 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007459
7460 Selector Sel = Method->getSelector();
7461
7462 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007463 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007464 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007465
7466 // Add parameters to the pattern.
7467 unsigned I = 0;
7468 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7469 PEnd = Method->param_end();
7470 P != PEnd; (void)++P, ++I) {
7471 // Add the part of the selector name.
7472 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007473 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007474 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007475 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7476 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007477 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007478 } else
7479 break;
7480
7481 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007482 QualType ParamType;
7483 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7484 ParamType = (*P)->getType();
7485 else
7486 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007487 ParamType = ParamType.substObjCTypeArgs(Context, {},
7488 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007489 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007490 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007491 (*P)->getObjCDeclQualifier(),
7492 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007493 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007494
7495 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007496 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007497 }
7498
7499 if (Method->isVariadic()) {
7500 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007501 Builder.AddChunk(CodeCompletionString::CK_Comma);
7502 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007503 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007504
Douglas Gregord37c59d2010-05-28 00:57:46 +00007505 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007506 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007507 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7508 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7509 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007510 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007511 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007512 Builder.AddTextChunk("return");
7513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7514 Builder.AddPlaceholderChunk("expression");
7515 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007516 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007517 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007518
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007519 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7520 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007521 }
7522
Douglas Gregor416b5752010-08-25 01:08:01 +00007523 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007524 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007525 Priority += CCD_InBaseClass;
7526
Douglas Gregor78254c82012-03-27 23:34:16 +00007527 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007528 }
7529
Douglas Gregor669a25a2011-02-17 00:22:45 +00007530 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7531 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007532 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007533 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007534 Containers.push_back(SearchDecl);
7535
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007536 VisitedSelectorSet KnownSelectors;
7537 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7538 MEnd = KnownMethods.end();
7539 M != MEnd; ++M)
7540 KnownSelectors.insert(M->first);
7541
7542
Douglas Gregor669a25a2011-02-17 00:22:45 +00007543 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7544 if (!IFace)
7545 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7546 IFace = Category->getClassInterface();
7547
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007548 if (IFace)
7549 for (auto *Cat : IFace->visible_categories())
7550 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007551
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007552 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007553 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007554 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007555 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007556 }
7557
Douglas Gregor636a61e2010-04-07 00:21:17 +00007558 Results.ExitScope();
7559
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007560 HandleCodeCompleteResults(this, CodeCompleter,
7561 CodeCompletionContext::CCC_Other,
7562 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007563}
Douglas Gregor95887f92010-07-08 23:20:03 +00007564
7565void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7566 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007567 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007568 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007569 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007570 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007571 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007572 if (ExternalSource) {
7573 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7574 I != N; ++I) {
7575 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007576 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007577 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007578
7579 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007580 }
7581 }
7582
7583 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007584 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007585 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007586 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007587 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007588
7589 if (ReturnTy)
7590 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007591
Douglas Gregor95887f92010-07-08 23:20:03 +00007592 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007593 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7594 MEnd = MethodPool.end();
7595 M != MEnd; ++M) {
7596 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7597 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007598 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007599 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007600 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007601 continue;
7602
Douglas Gregor45879692010-07-08 23:37:41 +00007603 if (AtParameterName) {
7604 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007605 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007606 if (NumSelIdents &&
7607 NumSelIdents <= MethList->getMethod()->param_size()) {
7608 ParmVarDecl *Param =
7609 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007610 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007611 CodeCompletionBuilder Builder(Results.getAllocator(),
7612 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007613 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007614 Param->getIdentifier()->getName()));
7615 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007616 }
7617 }
7618
7619 continue;
7620 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007621
Nico Weber2e0c8f72014-12-27 03:58:08 +00007622 Result R(MethList->getMethod(),
7623 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007624 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007625 R.AllParametersAreInformative = false;
7626 R.DeclaringEntity = true;
7627 Results.MaybeAddResult(R, CurContext);
7628 }
7629 }
7630
7631 Results.ExitScope();
Alex Lorenz847fda12017-01-03 11:56:40 +00007632
7633 if (!AtParameterName && !SelIdents.empty() &&
7634 SelIdents.front()->getName().startswith("init")) {
7635 for (const auto &M : PP.macros()) {
7636 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7637 continue;
7638 Results.EnterNewScope();
7639 CodeCompletionBuilder Builder(Results.getAllocator(),
7640 Results.getCodeCompletionTUInfo());
7641 Builder.AddTypedTextChunk(
7642 Builder.getAllocator().CopyString(M.first->getName()));
7643 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7644 CXCursor_MacroDefinition));
7645 Results.ExitScope();
7646 }
7647 }
7648
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007649 HandleCodeCompleteResults(this, CodeCompleter,
7650 CodeCompletionContext::CCC_Other,
7651 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007652}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007653
Douglas Gregorec00a262010-08-24 22:20:20 +00007654void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007655 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007656 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007657 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007658 Results.EnterNewScope();
7659
7660 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007661 CodeCompletionBuilder Builder(Results.getAllocator(),
7662 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007663 Builder.AddTypedTextChunk("if");
7664 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7665 Builder.AddPlaceholderChunk("condition");
7666 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007667
7668 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007669 Builder.AddTypedTextChunk("ifdef");
7670 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7671 Builder.AddPlaceholderChunk("macro");
7672 Results.AddResult(Builder.TakeString());
7673
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007674 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007675 Builder.AddTypedTextChunk("ifndef");
7676 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7677 Builder.AddPlaceholderChunk("macro");
7678 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007679
7680 if (InConditional) {
7681 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007682 Builder.AddTypedTextChunk("elif");
7683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7684 Builder.AddPlaceholderChunk("condition");
7685 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007686
7687 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007688 Builder.AddTypedTextChunk("else");
7689 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007690
7691 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007692 Builder.AddTypedTextChunk("endif");
7693 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007694 }
7695
7696 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007697 Builder.AddTypedTextChunk("include");
7698 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7699 Builder.AddTextChunk("\"");
7700 Builder.AddPlaceholderChunk("header");
7701 Builder.AddTextChunk("\"");
7702 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007703
7704 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007705 Builder.AddTypedTextChunk("include");
7706 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7707 Builder.AddTextChunk("<");
7708 Builder.AddPlaceholderChunk("header");
7709 Builder.AddTextChunk(">");
7710 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007711
7712 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007713 Builder.AddTypedTextChunk("define");
7714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7715 Builder.AddPlaceholderChunk("macro");
7716 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007717
7718 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007719 Builder.AddTypedTextChunk("define");
7720 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7721 Builder.AddPlaceholderChunk("macro");
7722 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7723 Builder.AddPlaceholderChunk("args");
7724 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7725 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007726
7727 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007728 Builder.AddTypedTextChunk("undef");
7729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7730 Builder.AddPlaceholderChunk("macro");
7731 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007732
7733 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007734 Builder.AddTypedTextChunk("line");
7735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7736 Builder.AddPlaceholderChunk("number");
7737 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007738
7739 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007740 Builder.AddTypedTextChunk("line");
7741 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7742 Builder.AddPlaceholderChunk("number");
7743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7744 Builder.AddTextChunk("\"");
7745 Builder.AddPlaceholderChunk("filename");
7746 Builder.AddTextChunk("\"");
7747 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007748
7749 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007750 Builder.AddTypedTextChunk("error");
7751 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7752 Builder.AddPlaceholderChunk("message");
7753 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007754
7755 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007756 Builder.AddTypedTextChunk("pragma");
7757 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7758 Builder.AddPlaceholderChunk("arguments");
7759 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007760
David Blaikiebbafb8a2012-03-11 07:00:24 +00007761 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007762 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007763 Builder.AddTypedTextChunk("import");
7764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7765 Builder.AddTextChunk("\"");
7766 Builder.AddPlaceholderChunk("header");
7767 Builder.AddTextChunk("\"");
7768 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007769
7770 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007771 Builder.AddTypedTextChunk("import");
7772 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7773 Builder.AddTextChunk("<");
7774 Builder.AddPlaceholderChunk("header");
7775 Builder.AddTextChunk(">");
7776 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007777 }
7778
7779 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007780 Builder.AddTypedTextChunk("include_next");
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 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007788 Builder.AddTypedTextChunk("include_next");
7789 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7790 Builder.AddTextChunk("<");
7791 Builder.AddPlaceholderChunk("header");
7792 Builder.AddTextChunk(">");
7793 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007794
7795 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007796 Builder.AddTypedTextChunk("warning");
7797 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7798 Builder.AddPlaceholderChunk("message");
7799 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007800
7801 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7802 // completions for them. And __include_macros is a Clang-internal extension
7803 // that we don't want to encourage anyone to use.
7804
7805 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7806 Results.ExitScope();
7807
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007808 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007809 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007810 Results.data(), Results.size());
7811}
7812
7813void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007814 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007815 S->getFnParent()? Sema::PCC_RecoveryInFunction
7816 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007817}
7818
Douglas Gregorec00a262010-08-24 22:20:20 +00007819void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007820 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007821 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007822 IsDefinition? CodeCompletionContext::CCC_MacroName
7823 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007824 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7825 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007826 CodeCompletionBuilder Builder(Results.getAllocator(),
7827 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007828 Results.EnterNewScope();
7829 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7830 MEnd = PP.macro_end();
7831 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007832 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007833 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007834 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7835 CCP_CodePattern,
7836 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007837 }
7838 Results.ExitScope();
7839 } else if (IsDefinition) {
7840 // FIXME: Can we detect when the user just wrote an include guard above?
7841 }
7842
Douglas Gregor0ac41382010-09-23 23:01:17 +00007843 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007844 Results.data(), Results.size());
7845}
7846
Douglas Gregorec00a262010-08-24 22:20:20 +00007847void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007848 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007849 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007850 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007851
7852 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007853 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007854
7855 // defined (<macro>)
7856 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007857 CodeCompletionBuilder Builder(Results.getAllocator(),
7858 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007859 Builder.AddTypedTextChunk("defined");
7860 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7861 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7862 Builder.AddPlaceholderChunk("macro");
7863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7864 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007865 Results.ExitScope();
7866
7867 HandleCodeCompleteResults(this, CodeCompleter,
7868 CodeCompletionContext::CCC_PreprocessorExpression,
7869 Results.data(), Results.size());
7870}
7871
7872void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7873 IdentifierInfo *Macro,
7874 MacroInfo *MacroInfo,
7875 unsigned Argument) {
7876 // FIXME: In the future, we could provide "overload" results, much like we
7877 // do for function calls.
7878
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007879 // Now just ignore this. There will be another code-completion callback
7880 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007881}
7882
Douglas Gregor11583702010-08-25 17:04:25 +00007883void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007884 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007885 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007886 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007887}
7888
Alex Lorenzf7f6f822017-05-09 16:05:04 +00007889void Sema::CodeCompleteAvailabilityPlatformName() {
7890 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7891 CodeCompleter->getCodeCompletionTUInfo(),
7892 CodeCompletionContext::CCC_Other);
7893 Results.EnterNewScope();
7894 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7895 for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7896 Results.AddResult(CodeCompletionResult(Platform));
7897 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7898 Twine(Platform) + "ApplicationExtension")));
7899 }
7900 Results.ExitScope();
7901 HandleCodeCompleteResults(this, CodeCompleter,
7902 CodeCompletionContext::CCC_Other, Results.data(),
7903 Results.size());
7904}
7905
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007906void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007907 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007908 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007909 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7910 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007911 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7912 CodeCompletionDeclConsumer Consumer(Builder,
7913 Context.getTranslationUnitDecl());
7914 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7915 Consumer);
7916 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007917
7918 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007919 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007920
7921 Results.clear();
7922 Results.insert(Results.end(),
7923 Builder.data(), Builder.data() + Builder.size());
7924}