blob: ab2e718c851ad68d759002e65f10c12baafb2496 [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/AST/DeclObjC.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Jordan Rose4938f272013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Douglas Gregor07f43572012-01-29 18:15:03 +000018#include "clang/Lex/HeaderSearch.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/CodeCompleteConsumer.h"
22#include "clang/Sema/ExternalSemaSource.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Sema/Overload.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.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]).
485static bool isReservedName(const IdentifierInfo *Id) {
486 if (Id->getLength() < 2)
487 return false;
488 const char *Name = Id->getNameStart();
489 return Name[0] == '_' &&
490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z'));
491}
492
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000493bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000494 bool &AsNestedNameSpecifier) const {
495 AsNestedNameSpecifier = false;
496
Richard Smithf2005d32015-12-29 23:34:32 +0000497 auto *Named = ND;
Douglas Gregor7c208612010-01-14 00:20:49 +0000498 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000499
500 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000501 if (!ND->getDeclName())
502 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000503
504 // Friend declarations and declarations introduced due to friends are never
505 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000506 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000507 return false;
508
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000509 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000510 if (isa<ClassTemplateSpecializationDecl>(ND) ||
511 isa<ClassTemplatePartialSpecializationDecl>(ND))
512 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000513
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000514 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000515 if (isa<UsingDecl>(ND))
516 return false;
517
518 // Some declarations have reserved names that we don't want to ever show.
Alp Toker034bbd52014-06-30 01:33:53 +0000519 // Filter out names reserved for the implementation if they come from a
520 // system header.
521 // TODO: Add a predicate for this.
522 if (const IdentifierInfo *Id = ND->getIdentifier())
523 if (isReservedName(Id) &&
524 (ND->getLocation().isInvalid() ||
525 SemaRef.SourceMgr.isInSystemHeader(
526 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregor7c208612010-01-14 00:20:49 +0000527 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000528
Douglas Gregor59cab552010-08-16 23:05:20 +0000529 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
Richard Smithf2005d32015-12-29 23:34:32 +0000530 (isa<NamespaceDecl>(ND) &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000531 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000532 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000533 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000534 AsNestedNameSpecifier = true;
535
Douglas Gregor3545ff42009-09-21 16:56:56 +0000536 // Filter out any unwanted results.
Richard Smithf2005d32015-12-29 23:34:32 +0000537 if (Filter && !(this->*Filter)(Named)) {
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000538 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000539 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000540 IsNestedNameSpecifier(ND) &&
541 (Filter != &ResultBuilder::IsMember ||
542 (isa<CXXRecordDecl>(ND) &&
543 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
544 AsNestedNameSpecifier = true;
545 return true;
546 }
547
Douglas Gregor7c208612010-01-14 00:20:49 +0000548 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000549 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000550 // ... then it must be interesting!
551 return true;
552}
553
Douglas Gregore0717ab2010-01-14 00:41:07 +0000554bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000555 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000556 // In C, there is no way to refer to a hidden name.
557 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
558 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000560 return true;
561
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000562 const DeclContext *HiddenCtx =
563 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000564
565 // There is no way to qualify a name declared in a function or method.
566 if (HiddenCtx->isFunctionOrMethod())
567 return true;
568
Sebastian Redl50c68252010-08-31 00:36:30 +0000569 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000570 return true;
571
572 // We can refer to the result with the appropriate qualification. Do it.
573 R.Hidden = true;
574 R.QualifierIsInformative = false;
575
576 if (!R.Qualifier)
577 R.Qualifier = getRequiredQualification(SemaRef.Context,
578 CurContext,
579 R.Declaration->getDeclContext());
580 return false;
581}
582
Douglas Gregor95887f92010-07-08 23:20:03 +0000583/// \brief A simplified classification of types used to determine whether two
584/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000585SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000586 switch (T->getTypeClass()) {
587 case Type::Builtin:
588 switch (cast<BuiltinType>(T)->getKind()) {
589 case BuiltinType::Void:
590 return STC_Void;
591
592 case BuiltinType::NullPtr:
593 return STC_Pointer;
594
595 case BuiltinType::Overload:
596 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000597 return STC_Other;
598
599 case BuiltinType::ObjCId:
600 case BuiltinType::ObjCClass:
601 case BuiltinType::ObjCSel:
602 return STC_ObjectiveC;
603
604 default:
605 return STC_Arithmetic;
606 }
David Blaikie8a40f702012-01-17 06:56:22 +0000607
Douglas Gregor95887f92010-07-08 23:20:03 +0000608 case Type::Complex:
609 return STC_Arithmetic;
610
611 case Type::Pointer:
612 return STC_Pointer;
613
614 case Type::BlockPointer:
615 return STC_Block;
616
617 case Type::LValueReference:
618 case Type::RValueReference:
619 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
620
621 case Type::ConstantArray:
622 case Type::IncompleteArray:
623 case Type::VariableArray:
624 case Type::DependentSizedArray:
625 return STC_Array;
626
627 case Type::DependentSizedExtVector:
628 case Type::Vector:
629 case Type::ExtVector:
630 return STC_Arithmetic;
631
632 case Type::FunctionProto:
633 case Type::FunctionNoProto:
634 return STC_Function;
635
636 case Type::Record:
637 return STC_Record;
638
639 case Type::Enum:
640 return STC_Arithmetic;
641
642 case Type::ObjCObject:
643 case Type::ObjCInterface:
644 case Type::ObjCObjectPointer:
645 return STC_ObjectiveC;
646
647 default:
648 return STC_Other;
649 }
650}
651
652/// \brief Get the type that a given expression will have if this declaration
653/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000654QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000655 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
656
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000657 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000658 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000659 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000660 return C.getObjCInterfaceType(Iface);
661
662 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000663 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000664 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000665 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000666 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000667 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000668 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000669 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000670 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000671 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000672 T = Value->getType();
673 else
674 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000675
676 // Dig through references, function pointers, and block pointers to
677 // get down to the likely type of an expression when the entity is
678 // used.
679 do {
680 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
681 T = Ref->getPointeeType();
682 continue;
683 }
684
685 if (const PointerType *Pointer = T->getAs<PointerType>()) {
686 if (Pointer->getPointeeType()->isFunctionType()) {
687 T = Pointer->getPointeeType();
688 continue;
689 }
690
691 break;
692 }
693
694 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
695 T = Block->getPointeeType();
696 continue;
697 }
698
699 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000700 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000701 continue;
702 }
703
704 break;
705 } while (true);
706
707 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000708}
709
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000710unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
711 if (!ND)
712 return CCP_Unlikely;
713
714 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000715 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
716 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000717 // _cmd is relatively rare
718 if (const ImplicitParamDecl *ImplicitParam =
719 dyn_cast<ImplicitParamDecl>(ND))
720 if (ImplicitParam->getIdentifier() &&
721 ImplicitParam->getIdentifier()->isStr("_cmd"))
722 return CCP_ObjC_cmd;
723
724 return CCP_LocalDeclaration;
725 }
Richard Smith541b38b2013-09-20 01:15:31 +0000726
727 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000728 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
729 return CCP_MemberDeclaration;
730
731 // Content-based decisions.
732 if (isa<EnumConstantDecl>(ND))
733 return CCP_Constant;
734
Douglas Gregor52e0de42013-01-31 05:03:46 +0000735 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
736 // message receiver, or parenthesized expression context. There, it's as
737 // likely that the user will want to write a type as other declarations.
738 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
739 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
740 CompletionContext.getKind()
741 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
742 CompletionContext.getKind()
743 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000744 return CCP_Type;
745
746 return CCP_Declaration;
747}
748
Douglas Gregor50832e02010-09-20 22:39:41 +0000749void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
750 // If this is an Objective-C method declaration whose selector matches our
751 // preferred selector, give it a priority boost.
752 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000753 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000754 if (PreferredSelector == Method->getSelector())
755 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000756
Douglas Gregor50832e02010-09-20 22:39:41 +0000757 // If we have a preferred type, adjust the priority for results with exactly-
758 // matching or nearly-matching types.
759 if (!PreferredType.isNull()) {
760 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
761 if (!T.isNull()) {
762 CanQualType TC = SemaRef.Context.getCanonicalType(T);
763 // Check for exactly-matching types (modulo qualifiers).
764 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
765 R.Priority /= CCF_ExactTypeMatch;
766 // Check for nearly-matching types, based on classification of each.
767 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000768 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000769 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
770 R.Priority /= CCF_SimilarTypeMatch;
771 }
772 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000773}
774
Douglas Gregor0212fd72010-09-21 16:06:22 +0000775void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000777 !CompletionContext.wantConstructorResults())
778 return;
779
780 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000781 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000782 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000783 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000784 Record = ClassTemplate->getTemplatedDecl();
785 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
786 // Skip specializations and partial specializations.
787 if (isa<ClassTemplateSpecializationDecl>(Record))
788 return;
789 } else {
790 // There are no constructors here.
791 return;
792 }
793
794 Record = Record->getDefinition();
795 if (!Record)
796 return;
797
798
799 QualType RecordTy = Context.getTypeDeclType(Record);
800 DeclarationName ConstructorName
801 = Context.DeclarationNames.getCXXConstructorName(
802 Context.getCanonicalType(RecordTy));
Richard Smithcf4bdde2015-02-21 02:45:19 +0000803 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
804 for (DeclContext::lookup_iterator I = Ctors.begin(),
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000805 E = Ctors.end();
806 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000807 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000808 R.CursorKind = getCursorKindForDecl(R.Declaration);
809 Results.push_back(R);
810 }
811}
812
Douglas Gregor7c208612010-01-14 00:20:49 +0000813void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
814 assert(!ShadowMaps.empty() && "Must enter into a results scope");
815
816 if (R.Kind != Result::RK_Declaration) {
817 // For non-declaration results, just add the result.
818 Results.push_back(R);
819 return;
820 }
821
822 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000823 if (const UsingShadowDecl *Using =
824 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000825 MaybeAddResult(Result(Using->getTargetDecl(),
826 getBasePriority(Using->getTargetDecl()),
827 R.Qualifier),
828 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000829 return;
830 }
831
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000832 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000833 unsigned IDNS = CanonDecl->getIdentifierNamespace();
834
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000835 bool AsNestedNameSpecifier = false;
836 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000837 return;
838
Douglas Gregor0212fd72010-09-21 16:06:22 +0000839 // C++ constructors are never found by name lookup.
840 if (isa<CXXConstructorDecl>(R.Declaration))
841 return;
842
Douglas Gregor3545ff42009-09-21 16:56:56 +0000843 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000844 ShadowMapEntry::iterator I, IEnd;
845 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
846 if (NamePos != SMap.end()) {
847 I = NamePos->second.begin();
848 IEnd = NamePos->second.end();
849 }
850
851 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000852 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000853 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000854 if (ND->getCanonicalDecl() == CanonDecl) {
855 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000856 Results[Index].Declaration = R.Declaration;
857
Douglas Gregor3545ff42009-09-21 16:56:56 +0000858 // We're done.
859 return;
860 }
861 }
862
863 // This is a new declaration in this scope. However, check whether this
864 // declaration name is hidden by a similarly-named declaration in an outer
865 // scope.
866 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
867 --SMEnd;
868 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000869 ShadowMapEntry::iterator I, IEnd;
870 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
871 if (NamePos != SM->end()) {
872 I = NamePos->second.begin();
873 IEnd = NamePos->second.end();
874 }
875 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000876 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000877 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000878 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
879 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000880 continue;
881
882 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000883 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000884 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000885 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000886 continue;
887
888 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000889 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000890 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000891
892 break;
893 }
894 }
895
896 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000897 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000898 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000899
Douglas Gregore412a5a2009-09-23 22:26:46 +0000900 // If the filter is for nested-name-specifiers, then this result starts a
901 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000902 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000903 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000904 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000905 } else
906 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000907
Douglas Gregor5bf52692009-09-22 23:15:58 +0000908 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000909 if (R.QualifierIsInformative && !R.Qualifier &&
910 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000911 const DeclContext *Ctx = R.Declaration->getDeclContext();
912 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000913 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
914 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000915 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000916 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
917 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000918 else
919 R.QualifierIsInformative = false;
920 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000921
Douglas Gregor3545ff42009-09-21 16:56:56 +0000922 // Insert this result into the set of results and into the current shadow
923 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000924 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000925 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000926
927 if (!AsNestedNameSpecifier)
928 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000929}
930
Douglas Gregorc580c522010-01-14 01:09:38 +0000931void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000932 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000933 if (R.Kind != Result::RK_Declaration) {
934 // For non-declaration results, just add the result.
935 Results.push_back(R);
936 return;
937 }
938
Douglas Gregorc580c522010-01-14 01:09:38 +0000939 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000940 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000941 AddResult(Result(Using->getTargetDecl(),
942 getBasePriority(Using->getTargetDecl()),
943 R.Qualifier),
944 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000945 return;
946 }
947
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000948 bool AsNestedNameSpecifier = false;
949 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000950 return;
951
Douglas Gregor0212fd72010-09-21 16:06:22 +0000952 // C++ constructors are never found by name lookup.
953 if (isa<CXXConstructorDecl>(R.Declaration))
954 return;
955
Douglas Gregorc580c522010-01-14 01:09:38 +0000956 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
957 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000958
Douglas Gregorc580c522010-01-14 01:09:38 +0000959 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000960 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000961 return;
962
963 // If the filter is for nested-name-specifiers, then this result starts a
964 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000965 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000966 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000967 R.Priority = CCP_NestedNameSpecifier;
968 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000969 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
970 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000971 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000972 R.QualifierIsInformative = true;
973
Douglas Gregorc580c522010-01-14 01:09:38 +0000974 // If this result is supposed to have an informative qualifier, add one.
975 if (R.QualifierIsInformative && !R.Qualifier &&
976 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000977 const DeclContext *Ctx = R.Declaration->getDeclContext();
978 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000979 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
980 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000981 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000982 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000983 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000984 else
985 R.QualifierIsInformative = false;
986 }
987
Douglas Gregora2db7932010-05-26 22:00:08 +0000988 // Adjust the priority if this result comes from a base class.
989 if (InBaseClass)
990 R.Priority += CCD_InBaseClass;
991
Douglas Gregor50832e02010-09-20 22:39:41 +0000992 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000993
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000994 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000995 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000996 if (Method->isInstance()) {
997 Qualifiers MethodQuals
998 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
999 if (ObjectTypeQualifiers == MethodQuals)
1000 R.Priority += CCD_ObjectQualifierMatch;
1001 else if (ObjectTypeQualifiers - MethodQuals) {
1002 // The method cannot be invoked, because doing so would drop
1003 // qualifiers.
1004 return;
1005 }
1006 }
1007
Douglas Gregorc580c522010-01-14 01:09:38 +00001008 // Insert this result into the set of results.
1009 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001010
1011 if (!AsNestedNameSpecifier)
1012 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001013}
1014
Douglas Gregor78a21012010-01-14 16:01:26 +00001015void ResultBuilder::AddResult(Result R) {
1016 assert(R.Kind != Result::RK_Declaration &&
1017 "Declaration results need more context");
1018 Results.push_back(R);
1019}
1020
Douglas Gregor3545ff42009-09-21 16:56:56 +00001021/// \brief Enter into a new scope.
Benjamin Kramer3204b152015-05-29 19:42:19 +00001022void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001023
1024/// \brief Exit from the current scope.
1025void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001026 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1027 EEnd = ShadowMaps.back().end();
1028 E != EEnd;
1029 ++E)
1030 E->second.Destroy();
1031
Douglas Gregor3545ff42009-09-21 16:56:56 +00001032 ShadowMaps.pop_back();
1033}
1034
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001035/// \brief Determines whether this given declaration will be found by
1036/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001037bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001038 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1039
Richard Smith541b38b2013-09-20 01:15:31 +00001040 // If name lookup finds a local extern declaration, then we are in a
1041 // context where it behaves like an ordinary name.
1042 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001043 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001044 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001045 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001046 if (isa<ObjCIvarDecl>(ND))
1047 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001048 }
1049
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001050 return ND->getIdentifierNamespace() & IDNS;
1051}
1052
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001053/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001054/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001055bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001056 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1057 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1058 return false;
1059
Richard Smith541b38b2013-09-20 01:15:31 +00001060 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001061 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001062 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001063 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001064 if (isa<ObjCIvarDecl>(ND))
1065 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001066 }
1067
Douglas Gregor70febae2010-05-28 00:49:12 +00001068 return ND->getIdentifierNamespace() & IDNS;
1069}
1070
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001071bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001072 if (!IsOrdinaryNonTypeName(ND))
1073 return 0;
1074
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001075 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001076 if (VD->getType()->isIntegralOrEnumerationType())
1077 return true;
1078
1079 return false;
1080}
1081
Douglas Gregor70febae2010-05-28 00:49:12 +00001082/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001083/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001084bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001085 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
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)
John McCalle87beb22010-04-23 18:46:30 +00001089 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001090
1091 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001092 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1093 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001094}
1095
Douglas Gregor3545ff42009-09-21 16:56:56 +00001096/// \brief Determines whether the given declaration is suitable as the
1097/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001098bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001099 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001100 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001101 ND = ClassTemplate->getTemplatedDecl();
1102
1103 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1104}
1105
1106/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001107bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001108 return isa<EnumDecl>(ND);
1109}
1110
1111/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001112bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001113 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001114 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001115 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001116
1117 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001118 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001119 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001120 RD->getTagKind() == TTK_Struct ||
1121 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001122
1123 return false;
1124}
1125
1126/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001127bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001128 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001129 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001130 ND = ClassTemplate->getTemplatedDecl();
1131
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001132 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001133 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001134
1135 return false;
1136}
1137
1138/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001139bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001140 return isa<NamespaceDecl>(ND);
1141}
1142
1143/// \brief Determines whether the given declaration is a namespace or
1144/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001145bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001146 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001147}
1148
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001149/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001150bool ResultBuilder::IsType(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001151 ND = ND->getUnderlyingDecl();
Douglas Gregor99fa2642010-08-24 01:06:58 +00001152 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001153}
1154
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001155/// \brief Determines which members of a class should be visible via
1156/// "." or "->". Only value declarations, nested name specifiers, and
1157/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001158bool ResultBuilder::IsMember(const NamedDecl *ND) const {
Richard Smithf2005d32015-12-29 23:34:32 +00001159 ND = ND->getUnderlyingDecl();
Douglas Gregor70788392009-12-11 18:14:22 +00001160 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
Richard Smithf2005d32015-12-29 23:34:32 +00001161 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001162}
1163
Douglas Gregora817a192010-05-27 23:06:34 +00001164static bool isObjCReceiverType(ASTContext &C, QualType T) {
1165 T = C.getCanonicalType(T);
1166 switch (T->getTypeClass()) {
1167 case Type::ObjCObject:
1168 case Type::ObjCInterface:
1169 case Type::ObjCObjectPointer:
1170 return true;
1171
1172 case Type::Builtin:
1173 switch (cast<BuiltinType>(T)->getKind()) {
1174 case BuiltinType::ObjCId:
1175 case BuiltinType::ObjCClass:
1176 case BuiltinType::ObjCSel:
1177 return true;
1178
1179 default:
1180 break;
1181 }
1182 return false;
1183
1184 default:
1185 break;
1186 }
1187
David Blaikiebbafb8a2012-03-11 07:00:24 +00001188 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001189 return false;
1190
1191 // FIXME: We could perform more analysis here to determine whether a
1192 // particular class type has any conversions to Objective-C types. For now,
1193 // just accept all class types.
1194 return T->isDependentType() || T->isRecordType();
1195}
1196
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001197bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001198 QualType T = getDeclUsageType(SemaRef.Context, ND);
1199 if (T.isNull())
1200 return false;
1201
1202 T = SemaRef.Context.getBaseElementType(T);
1203 return isObjCReceiverType(SemaRef.Context, T);
1204}
1205
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001206bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001207 if (IsObjCMessageReceiver(ND))
1208 return true;
1209
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001210 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001211 if (!Var)
1212 return false;
1213
1214 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1215}
1216
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001217bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001218 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1219 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001220 return false;
1221
1222 QualType T = getDeclUsageType(SemaRef.Context, ND);
1223 if (T.isNull())
1224 return false;
1225
1226 T = SemaRef.Context.getBaseElementType(T);
1227 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1228 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001229 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001230}
Douglas Gregora817a192010-05-27 23:06:34 +00001231
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001232bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001233 return false;
1234}
1235
James Dennettf1243872012-06-17 05:33:25 +00001236/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001237/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001238bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001239 return isa<ObjCIvarDecl>(ND);
1240}
1241
Douglas Gregorc580c522010-01-14 01:09:38 +00001242namespace {
1243 /// \brief Visible declaration consumer that adds a code-completion result
1244 /// for each visible declaration.
1245 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1246 ResultBuilder &Results;
1247 DeclContext *CurContext;
1248
1249 public:
1250 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1251 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001252
1253 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1254 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001255 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001256 if (Ctx)
1257 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001258
1259 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1260 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001261 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001262 }
1263 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001264}
Douglas Gregorc580c522010-01-14 01:09:38 +00001265
Douglas Gregor3545ff42009-09-21 16:56:56 +00001266/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001267static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001268 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001269 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001270 Results.AddResult(Result("short", CCP_Type));
1271 Results.AddResult(Result("long", CCP_Type));
1272 Results.AddResult(Result("signed", CCP_Type));
1273 Results.AddResult(Result("unsigned", CCP_Type));
1274 Results.AddResult(Result("void", CCP_Type));
1275 Results.AddResult(Result("char", CCP_Type));
1276 Results.AddResult(Result("int", CCP_Type));
1277 Results.AddResult(Result("float", CCP_Type));
1278 Results.AddResult(Result("double", CCP_Type));
1279 Results.AddResult(Result("enum", CCP_Type));
1280 Results.AddResult(Result("struct", CCP_Type));
1281 Results.AddResult(Result("union", CCP_Type));
1282 Results.AddResult(Result("const", CCP_Type));
1283 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001284
Douglas Gregor3545ff42009-09-21 16:56:56 +00001285 if (LangOpts.C99) {
1286 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001287 Results.AddResult(Result("_Complex", CCP_Type));
1288 Results.AddResult(Result("_Imaginary", CCP_Type));
1289 Results.AddResult(Result("_Bool", CCP_Type));
1290 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001291 }
1292
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001293 CodeCompletionBuilder Builder(Results.getAllocator(),
1294 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001295 if (LangOpts.CPlusPlus) {
1296 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001297 Results.AddResult(Result("bool", CCP_Type +
1298 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001299 Results.AddResult(Result("class", CCP_Type));
1300 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001301
Douglas Gregorf4c33342010-05-28 00:22:41 +00001302 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001303 Builder.AddTypedTextChunk("typename");
1304 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1305 Builder.AddPlaceholderChunk("qualifier");
1306 Builder.AddTextChunk("::");
1307 Builder.AddPlaceholderChunk("name");
1308 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001309
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001310 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001311 Results.AddResult(Result("auto", CCP_Type));
1312 Results.AddResult(Result("char16_t", CCP_Type));
1313 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001314
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001315 Builder.AddTypedTextChunk("decltype");
1316 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1317 Builder.AddPlaceholderChunk("expression");
1318 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1319 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001320 }
1321 }
1322
1323 // GNU extensions
1324 if (LangOpts.GNUMode) {
1325 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001326 // Results.AddResult(Result("_Decimal32"));
1327 // Results.AddResult(Result("_Decimal64"));
1328 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001329
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001330 Builder.AddTypedTextChunk("typeof");
1331 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1332 Builder.AddPlaceholderChunk("expression");
1333 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001334
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001335 Builder.AddTypedTextChunk("typeof");
1336 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1337 Builder.AddPlaceholderChunk("type");
1338 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1339 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001340 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001341
1342 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001343 Results.AddResult(Result("_Nonnull", CCP_Type));
1344 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1345 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001346}
1347
John McCallfaf5fb42010-08-26 23:41:50 +00001348static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001349 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001350 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001351 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001352 // Note: we don't suggest either "auto" or "register", because both
1353 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1354 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001355 Results.AddResult(Result("extern"));
1356 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001357}
1358
John McCallfaf5fb42010-08-26 23:41:50 +00001359static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001361 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001362 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001363 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001364 case Sema::PCC_Class:
1365 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001367 Results.AddResult(Result("explicit"));
1368 Results.AddResult(Result("friend"));
1369 Results.AddResult(Result("mutable"));
1370 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001371 }
1372 // Fall through
1373
John McCallfaf5fb42010-08-26 23:41:50 +00001374 case Sema::PCC_ObjCInterface:
1375 case Sema::PCC_ObjCImplementation:
1376 case Sema::PCC_Namespace:
1377 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001378 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001379 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001380 break;
1381
John McCallfaf5fb42010-08-26 23:41:50 +00001382 case Sema::PCC_ObjCInstanceVariableList:
1383 case Sema::PCC_Expression:
1384 case Sema::PCC_Statement:
1385 case Sema::PCC_ForInit:
1386 case Sema::PCC_Condition:
1387 case Sema::PCC_RecoveryInFunction:
1388 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001389 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001390 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001391 break;
1392 }
1393}
1394
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001395static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1396static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1397static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001398 ResultBuilder &Results,
1399 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001400static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001401 ResultBuilder &Results,
1402 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001403static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001404 ResultBuilder &Results,
1405 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001406static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001407
Douglas Gregorf4c33342010-05-28 00:22:41 +00001408static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001409 CodeCompletionBuilder Builder(Results.getAllocator(),
1410 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("typedef");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("type");
1414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1415 Builder.AddPlaceholderChunk("name");
1416 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001417}
1418
John McCallfaf5fb42010-08-26 23:41:50 +00001419static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001420 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001421 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001422 case Sema::PCC_Namespace:
1423 case Sema::PCC_Class:
1424 case Sema::PCC_ObjCInstanceVariableList:
1425 case Sema::PCC_Template:
1426 case Sema::PCC_MemberTemplate:
1427 case Sema::PCC_Statement:
1428 case Sema::PCC_RecoveryInFunction:
1429 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001430 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001431 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001432 return true;
1433
John McCallfaf5fb42010-08-26 23:41:50 +00001434 case Sema::PCC_Expression:
1435 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001436 return LangOpts.CPlusPlus;
1437
1438 case Sema::PCC_ObjCInterface:
1439 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001440 return false;
1441
John McCallfaf5fb42010-08-26 23:41:50 +00001442 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001443 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001444 }
David Blaikie8a40f702012-01-17 06:56:22 +00001445
1446 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001447}
1448
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001449static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1450 const Preprocessor &PP) {
1451 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001452 Policy.AnonymousTagLocations = false;
1453 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001454 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001455 return Policy;
1456}
1457
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001458/// \brief Retrieve a printing policy suitable for code completion.
1459static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1460 return getCompletionPrintingPolicy(S.Context, S.PP);
1461}
1462
Douglas Gregore5c79d52011-10-18 21:20:17 +00001463/// \brief Retrieve the string representation of the given type as a string
1464/// that has the appropriate lifetime for code completion.
1465///
1466/// This routine provides a fast path where we provide constant strings for
1467/// common type names.
1468static const char *GetCompletionTypeString(QualType T,
1469 ASTContext &Context,
1470 const PrintingPolicy &Policy,
1471 CodeCompletionAllocator &Allocator) {
1472 if (!T.getLocalQualifiers()) {
1473 // Built-in type names are constant strings.
1474 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001475 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001476
1477 // Anonymous tag types are constant strings.
1478 if (const TagType *TagT = dyn_cast<TagType>(T))
1479 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001480 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001481 switch (Tag->getTagKind()) {
1482 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001483 case TTK_Interface: return "__interface <anonymous>";
1484 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001485 case TTK_Union: return "union <anonymous>";
1486 case TTK_Enum: return "enum <anonymous>";
1487 }
1488 }
1489 }
1490
1491 // Slow path: format the type as a string.
1492 std::string Result;
1493 T.getAsStringInternal(Result, Policy);
1494 return Allocator.CopyString(Result);
1495}
1496
Douglas Gregord8c61782012-02-15 15:34:24 +00001497/// \brief Add a completion for "this", if we're in a member function.
1498static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1499 QualType ThisTy = S.getCurrentThisType();
1500 if (ThisTy.isNull())
1501 return;
1502
1503 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001504 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001505 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1506 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1507 S.Context,
1508 Policy,
1509 Allocator));
1510 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001511 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001512}
1513
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001514/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001515static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001516 Scope *S,
1517 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001518 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001519 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001520 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregore5c79d52011-10-18 21:20:17 +00001521 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001522
John McCall276321a2010-08-25 06:19:51 +00001523 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001524 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001525 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001527 if (Results.includeCodePatterns()) {
1528 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001529 Builder.AddTypedTextChunk("namespace");
1530 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1531 Builder.AddPlaceholderChunk("identifier");
1532 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1533 Builder.AddPlaceholderChunk("declarations");
1534 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1535 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1536 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001537 }
1538
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001539 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001540 Builder.AddTypedTextChunk("namespace");
1541 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1542 Builder.AddPlaceholderChunk("name");
1543 Builder.AddChunk(CodeCompletionString::CK_Equal);
1544 Builder.AddPlaceholderChunk("namespace");
1545 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001546
1547 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001548 Builder.AddTypedTextChunk("using");
1549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1550 Builder.AddTextChunk("namespace");
1551 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1552 Builder.AddPlaceholderChunk("identifier");
1553 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001554
1555 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001556 Builder.AddTypedTextChunk("asm");
1557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1558 Builder.AddPlaceholderChunk("string-literal");
1559 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1560 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001561
Douglas Gregorf4c33342010-05-28 00:22:41 +00001562 if (Results.includeCodePatterns()) {
1563 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001564 Builder.AddTypedTextChunk("template");
1565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566 Builder.AddPlaceholderChunk("declaration");
1567 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001568 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001569 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001570
David Blaikiebbafb8a2012-03-11 07:00:24 +00001571 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001572 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001573
Douglas Gregorf4c33342010-05-28 00:22:41 +00001574 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001575 // Fall through
1576
John McCallfaf5fb42010-08-26 23:41:50 +00001577 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001579 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001580 Builder.AddTypedTextChunk("using");
1581 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1582 Builder.AddPlaceholderChunk("qualifier");
1583 Builder.AddTextChunk("::");
1584 Builder.AddPlaceholderChunk("name");
1585 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001586
Douglas Gregorf4c33342010-05-28 00:22:41 +00001587 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001588 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001589 Builder.AddTypedTextChunk("using");
1590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1591 Builder.AddTextChunk("typename");
1592 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1593 Builder.AddPlaceholderChunk("qualifier");
1594 Builder.AddTextChunk("::");
1595 Builder.AddPlaceholderChunk("name");
1596 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001597 }
1598
John McCallfaf5fb42010-08-26 23:41:50 +00001599 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001600 AddTypedefResult(Results);
1601
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001602 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001603 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001604 if (Results.includeCodePatterns())
1605 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001607
1608 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001609 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001610 if (Results.includeCodePatterns())
1611 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001612 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001613
1614 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001615 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001616 if (Results.includeCodePatterns())
1617 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001618 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001619 }
1620 }
1621 // Fall through
1622
John McCallfaf5fb42010-08-26 23:41:50 +00001623 case Sema::PCC_Template:
1624 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001625 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001627 Builder.AddTypedTextChunk("template");
1628 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1629 Builder.AddPlaceholderChunk("parameters");
1630 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1631 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632 }
1633
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1635 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001636 break;
1637
John McCallfaf5fb42010-08-26 23:41:50 +00001638 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001639 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1640 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1641 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001642 break;
1643
John McCallfaf5fb42010-08-26 23:41:50 +00001644 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1646 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1647 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001648 break;
1649
John McCallfaf5fb42010-08-26 23:41:50 +00001650 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001651 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001652 break;
1653
John McCallfaf5fb42010-08-26 23:41:50 +00001654 case Sema::PCC_RecoveryInFunction:
1655 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001656 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001657
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1659 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001660 Builder.AddTypedTextChunk("try");
1661 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1662 Builder.AddPlaceholderChunk("statements");
1663 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1664 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1665 Builder.AddTextChunk("catch");
1666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1667 Builder.AddPlaceholderChunk("declaration");
1668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1669 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1670 Builder.AddPlaceholderChunk("statements");
1671 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1672 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001675 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001676 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001677
Douglas Gregorf64acca2010-05-25 21:41:55 +00001678 if (Results.includeCodePatterns()) {
1679 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001680 Builder.AddTypedTextChunk("if");
1681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001684 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001685 Builder.AddPlaceholderChunk("expression");
1686 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1687 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1688 Builder.AddPlaceholderChunk("statements");
1689 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1690 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1691 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001692
Douglas Gregorf64acca2010-05-25 21:41:55 +00001693 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("switch");
1695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001696 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001697 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001698 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001699 Builder.AddPlaceholderChunk("expression");
1700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1701 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1702 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1703 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001705 }
1706
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001707 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001708 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001709 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001710 Builder.AddTypedTextChunk("case");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddPlaceholderChunk("expression");
1713 Builder.AddChunk(CodeCompletionString::CK_Colon);
1714 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001715
1716 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001717 Builder.AddTypedTextChunk("default");
1718 Builder.AddChunk(CodeCompletionString::CK_Colon);
1719 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001720 }
1721
Douglas Gregorf64acca2010-05-25 21:41:55 +00001722 if (Results.includeCodePatterns()) {
1723 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001724 Builder.AddTypedTextChunk("while");
1725 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001727 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001728 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001729 Builder.AddPlaceholderChunk("expression");
1730 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1731 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1732 Builder.AddPlaceholderChunk("statements");
1733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1734 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1735 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001736
1737 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001738 Builder.AddTypedTextChunk("do");
1739 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1740 Builder.AddPlaceholderChunk("statements");
1741 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1742 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1743 Builder.AddTextChunk("while");
1744 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1745 Builder.AddPlaceholderChunk("expression");
1746 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1747 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001748
Douglas Gregorf64acca2010-05-25 21:41:55 +00001749 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001750 Builder.AddTypedTextChunk("for");
1751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001752 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001754 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001755 Builder.AddPlaceholderChunk("init-expression");
1756 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1757 Builder.AddPlaceholderChunk("condition");
1758 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1759 Builder.AddPlaceholderChunk("inc-expression");
1760 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1761 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1762 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1763 Builder.AddPlaceholderChunk("statements");
1764 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1765 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1766 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001767 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768
1769 if (S->getContinueParent()) {
1770 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001771 Builder.AddTypedTextChunk("continue");
1772 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001773 }
1774
1775 if (S->getBreakParent()) {
1776 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001777 Builder.AddTypedTextChunk("break");
1778 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001779 }
1780
1781 // "return expression ;" or "return ;", depending on whether we
1782 // know the function is void or not.
1783 bool isVoid = false;
1784 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001785 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001786 else if (ObjCMethodDecl *Method
1787 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001788 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001789 else if (SemaRef.getCurBlock() &&
1790 !SemaRef.getCurBlock()->ReturnType.isNull())
1791 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001792 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001793 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1795 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001796 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001797 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001798
Douglas Gregorf4c33342010-05-28 00:22:41 +00001799 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001800 Builder.AddTypedTextChunk("goto");
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("label");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001804
Douglas Gregorf4c33342010-05-28 00:22:41 +00001805 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001806 Builder.AddTypedTextChunk("using");
1807 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1808 Builder.AddTextChunk("namespace");
1809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1810 Builder.AddPlaceholderChunk("identifier");
1811 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001812 }
1813
1814 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001815 case Sema::PCC_ForInit:
1816 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001818 // Fall through: conditions and statements can have expressions.
1819
Douglas Gregor5e35d592010-09-14 23:59:36 +00001820 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001822 CCC == Sema::PCC_ParenthesizedExpression) {
1823 // (__bridge <type>)<expression>
1824 Builder.AddTypedTextChunk("__bridge");
1825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1826 Builder.AddPlaceholderChunk("type");
1827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1828 Builder.AddPlaceholderChunk("expression");
1829 Results.AddResult(Result(Builder.TakeString()));
1830
1831 // (__bridge_transfer <Objective-C type>)<expression>
1832 Builder.AddTypedTextChunk("__bridge_transfer");
1833 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1834 Builder.AddPlaceholderChunk("Objective-C type");
1835 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1836 Builder.AddPlaceholderChunk("expression");
1837 Results.AddResult(Result(Builder.TakeString()));
1838
1839 // (__bridge_retained <CF type>)<expression>
1840 Builder.AddTypedTextChunk("__bridge_retained");
1841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1842 Builder.AddPlaceholderChunk("CF type");
1843 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1844 Builder.AddPlaceholderChunk("expression");
1845 Results.AddResult(Result(Builder.TakeString()));
1846 }
1847 // Fall through
1848
John McCallfaf5fb42010-08-26 23:41:50 +00001849 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001850 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001851 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001852 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001853
Douglas Gregore5c79d52011-10-18 21:20:17 +00001854 // true
1855 Builder.AddResultTypeChunk("bool");
1856 Builder.AddTypedTextChunk("true");
1857 Results.AddResult(Result(Builder.TakeString()));
1858
1859 // false
1860 Builder.AddResultTypeChunk("bool");
1861 Builder.AddTypedTextChunk("false");
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001863
David Blaikiebbafb8a2012-03-11 07:00:24 +00001864 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001865 // dynamic_cast < type-id > ( expression )
1866 Builder.AddTypedTextChunk("dynamic_cast");
1867 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1868 Builder.AddPlaceholderChunk("type");
1869 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1870 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1871 Builder.AddPlaceholderChunk("expression");
1872 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1873 Results.AddResult(Result(Builder.TakeString()));
1874 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001875
1876 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001877 Builder.AddTypedTextChunk("static_cast");
1878 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1879 Builder.AddPlaceholderChunk("type");
1880 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1882 Builder.AddPlaceholderChunk("expression");
1883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1884 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001885
Douglas Gregorf4c33342010-05-28 00:22:41 +00001886 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001887 Builder.AddTypedTextChunk("reinterpret_cast");
1888 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1889 Builder.AddPlaceholderChunk("type");
1890 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1891 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1892 Builder.AddPlaceholderChunk("expression");
1893 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1894 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001895
Douglas Gregorf4c33342010-05-28 00:22:41 +00001896 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001897 Builder.AddTypedTextChunk("const_cast");
1898 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1899 Builder.AddPlaceholderChunk("type");
1900 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1902 Builder.AddPlaceholderChunk("expression");
1903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1904 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001905
David Blaikiebbafb8a2012-03-11 07:00:24 +00001906 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001907 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001908 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001909 Builder.AddTypedTextChunk("typeid");
1910 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1911 Builder.AddPlaceholderChunk("expression-or-type");
1912 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1913 Results.AddResult(Result(Builder.TakeString()));
1914 }
1915
Douglas Gregorf4c33342010-05-28 00:22:41 +00001916 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001917 Builder.AddTypedTextChunk("new");
1918 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1919 Builder.AddPlaceholderChunk("type");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1921 Builder.AddPlaceholderChunk("expressions");
1922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1923 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001924
Douglas Gregorf4c33342010-05-28 00:22:41 +00001925 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001926 Builder.AddTypedTextChunk("new");
1927 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1928 Builder.AddPlaceholderChunk("type");
1929 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1930 Builder.AddPlaceholderChunk("size");
1931 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1932 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1933 Builder.AddPlaceholderChunk("expressions");
1934 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1935 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001936
Douglas Gregorf4c33342010-05-28 00:22:41 +00001937 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001938 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001939 Builder.AddTypedTextChunk("delete");
1940 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1941 Builder.AddPlaceholderChunk("expression");
1942 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001943
Douglas Gregorf4c33342010-05-28 00:22:41 +00001944 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001945 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001946 Builder.AddTypedTextChunk("delete");
1947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1948 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1949 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1950 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1951 Builder.AddPlaceholderChunk("expression");
1952 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001953
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001955 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001956 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001957 Builder.AddTypedTextChunk("throw");
1958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1959 Builder.AddPlaceholderChunk("expression");
1960 Results.AddResult(Result(Builder.TakeString()));
1961 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001962
Douglas Gregora2db7932010-05-26 22:00:08 +00001963 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001964
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001965 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001966 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001967 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001968 Builder.AddTypedTextChunk("nullptr");
1969 Results.AddResult(Result(Builder.TakeString()));
1970
1971 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001972 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001973 Builder.AddTypedTextChunk("alignof");
1974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1975 Builder.AddPlaceholderChunk("type");
1976 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1977 Results.AddResult(Result(Builder.TakeString()));
1978
1979 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001980 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001981 Builder.AddTypedTextChunk("noexcept");
1982 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1983 Builder.AddPlaceholderChunk("expression");
1984 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1985 Results.AddResult(Result(Builder.TakeString()));
1986
1987 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001988 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001989 Builder.AddTypedTextChunk("sizeof...");
1990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1991 Builder.AddPlaceholderChunk("parameter-pack");
1992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1993 Results.AddResult(Result(Builder.TakeString()));
1994 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001995 }
1996
David Blaikiebbafb8a2012-03-11 07:00:24 +00001997 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001998 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001999 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2000 // The interface can be NULL.
2001 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002002 if (ID->getSuperClass()) {
2003 std::string SuperType;
2004 SuperType = ID->getSuperClass()->getNameAsString();
2005 if (Method->isInstanceMethod())
2006 SuperType += " *";
2007
2008 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2009 Builder.AddTypedTextChunk("super");
2010 Results.AddResult(Result(Builder.TakeString()));
2011 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002012 }
2013
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002014 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002015 }
2016
Jordan Rose58d54722012-06-30 21:33:57 +00002017 if (SemaRef.getLangOpts().C11) {
2018 // _Alignof
2019 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002020 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002021 Builder.AddTypedTextChunk("alignof");
2022 else
2023 Builder.AddTypedTextChunk("_Alignof");
2024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2025 Builder.AddPlaceholderChunk("type");
2026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2027 Results.AddResult(Result(Builder.TakeString()));
2028 }
2029
Douglas Gregorf4c33342010-05-28 00:22:41 +00002030 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002031 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002032 Builder.AddTypedTextChunk("sizeof");
2033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2034 Builder.AddPlaceholderChunk("expression-or-type");
2035 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002037 break;
2038 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002039
John McCallfaf5fb42010-08-26 23:41:50 +00002040 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002041 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002042 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002043 }
2044
David Blaikiebbafb8a2012-03-11 07:00:24 +00002045 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2046 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002047
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002049 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002050}
2051
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002052/// \brief If the given declaration has an associated type, add it as a result
2053/// type chunk.
2054static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002055 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002056 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002057 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002058 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002059 if (!ND)
2060 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002061
2062 // Skip constructors and conversion functions, which have their return types
2063 // built into their names.
2064 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2065 return;
2066
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002067 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002068 QualType T;
2069 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002070 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002071 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2072 if (!BaseType.isNull())
2073 T = Method->getSendResultType(BaseType);
2074 else
2075 T = Method->getReturnType();
2076 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002077 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2078 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2079 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002080 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2081 if (!BaseType.isNull())
2082 T = Ivar->getUsageType(BaseType);
2083 else
2084 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002085 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002086 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002087 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2088 if (!BaseType.isNull())
2089 T = Property->getUsageType(BaseType);
2090 else
2091 T = Property->getType();
2092 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002093
2094 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2095 return;
2096
Douglas Gregor75acd922011-09-27 23:30:47 +00002097 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002098 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002099}
2100
Richard Smith20e883e2015-04-29 23:20:19 +00002101static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002102 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002103 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002104 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2105 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002106 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002107 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002108 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002109 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002110 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002111 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002112 }
2113}
2114
Douglas Gregor86b42682015-06-19 18:27:52 +00002115static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2116 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002117 std::string Result;
2118 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002119 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002120 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002121 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002122 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002123 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002124 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002125 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002126 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002127 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002128 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002129 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002130 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2131 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2132 switch (*nullability) {
2133 case NullabilityKind::NonNull:
2134 Result += "nonnull ";
2135 break;
2136
2137 case NullabilityKind::Nullable:
2138 Result += "nullable ";
2139 break;
2140
2141 case NullabilityKind::Unspecified:
2142 Result += "null_unspecified ";
2143 break;
2144 }
2145 }
2146 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002147 return Result;
2148}
2149
Richard Smith20e883e2015-04-29 23:20:19 +00002150static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002151 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002152 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002153 bool SuppressBlock = false,
2154 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002155 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2156 if (Param->getType()->isDependentType() ||
2157 !Param->getType()->isBlockPointerType()) {
2158 // The argument for a dependent or non-block parameter is a placeholder
2159 // containing that parameter's type.
2160 std::string Result;
2161
Douglas Gregor981a0c42010-08-29 19:47:46 +00002162 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002163 Result = Param->getIdentifier()->getName();
2164
Douglas Gregor86b42682015-06-19 18:27:52 +00002165 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002166 if (ObjCSubsts)
2167 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2168 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002169 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002170 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2171 Type);
2172 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002173 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002174 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002175 } else {
2176 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002177 }
2178 return Result;
2179 }
2180
2181 // The argument for a block pointer parameter is a block literal with
2182 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002183 FunctionTypeLoc Block;
2184 FunctionProtoTypeLoc BlockProto;
Douglas Gregore90dd002010-08-24 16:15:59 +00002185 TypeLoc TL;
2186 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2187 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2188 while (true) {
2189 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002190 if (!SuppressBlock) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002191 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2192 if (TypeSourceInfo *InnerTSInfo =
2193 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002194 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2195 continue;
2196 }
2197 }
2198
2199 // Look through qualified types
David Blaikie6adc78e2013-02-18 22:06:02 +00002200 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2201 TL = QualifiedTL.getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002202 continue;
2203 }
Douglas Gregor4c850f32015-07-07 06:20:22 +00002204
2205 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2206 TL = AttrTL.getModifiedLoc();
2207 continue;
2208 }
Douglas Gregore90dd002010-08-24 16:15:59 +00002209 }
2210
Douglas Gregore90dd002010-08-24 16:15:59 +00002211 // Try to get the function prototype behind the block pointer type,
2212 // then we're done.
David Blaikie6adc78e2013-02-18 22:06:02 +00002213 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2214 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2215 Block = TL.getAs<FunctionTypeLoc>();
2216 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregore90dd002010-08-24 16:15:59 +00002217 }
2218 break;
2219 }
2220 }
2221
2222 if (!Block) {
2223 // We were unable to find a FunctionProtoTypeLoc with parameter names
2224 // for the block; just use the parameter type as a placeholder.
2225 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002226 if (!ObjCMethodParam && Param->getIdentifier())
2227 Result = Param->getIdentifier()->getName();
2228
Douglas Gregor86b42682015-06-19 18:27:52 +00002229 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002230
2231 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002232 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2233 Type);
2234 Result += Type.getAsString(Policy) + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002235 if (Param->getIdentifier())
2236 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002237 } else {
2238 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002239 }
2240
2241 return Result;
2242 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002243
Douglas Gregore90dd002010-08-24 16:15:59 +00002244 // We have the function prototype behind the block pointer type, as it was
2245 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002246 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002247 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002248 if (ObjCSubsts)
2249 ResultType = ResultType.substObjCTypeArgs(Param->getASTContext(),
2250 *ObjCSubsts,
2251 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002252 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002253 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002254
2255 // Format the parameter list.
2256 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002257 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002258 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002259 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002260 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002261 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002262 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002263 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002264 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002265 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002266 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002267 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002268 /*SuppressName=*/false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002269 /*SuppressBlock=*/true,
2270 ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002271
David Blaikie6adc78e2013-02-18 22:06:02 +00002272 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002273 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002274 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002275 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002276 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002277
Douglas Gregord793e7c2011-10-18 04:23:19 +00002278 if (SuppressBlock) {
2279 // Format as a parameter.
2280 Result = Result + " (^";
2281 if (Param->getIdentifier())
2282 Result += Param->getIdentifier()->getName();
2283 Result += ")";
2284 Result += Params;
2285 } else {
2286 // Format as a block literal argument.
2287 Result = '^' + Result;
2288 Result += Params;
2289
2290 if (Param->getIdentifier())
2291 Result += Param->getIdentifier()->getName();
2292 }
2293
Douglas Gregore90dd002010-08-24 16:15:59 +00002294 return Result;
2295}
2296
Douglas Gregor3545ff42009-09-21 16:56:56 +00002297/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002298static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002299 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002300 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002301 CodeCompletionBuilder &Result,
2302 unsigned Start = 0,
2303 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002304 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002305
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002306 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002307 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002308
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002309 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002310 // When we see an optional default argument, put that argument and
2311 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002312 CodeCompletionBuilder Opt(Result.getAllocator(),
2313 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002314 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002315 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002316 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002317 Result.AddOptionalChunk(Opt.TakeString());
2318 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002319 }
2320
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002321 if (FirstParameter)
2322 FirstParameter = false;
2323 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002324 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002325
2326 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002327
2328 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002329 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2330
Douglas Gregor400f5972010-08-31 05:13:43 +00002331 if (Function->isVariadic() && P == N - 1)
2332 PlaceholderStr += ", ...";
2333
Douglas Gregor3545ff42009-09-21 16:56:56 +00002334 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002335 Result.AddPlaceholderChunk(
2336 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002337 }
Douglas Gregorba449032009-09-22 21:42:17 +00002338
2339 if (const FunctionProtoType *Proto
2340 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002341 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002342 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002343 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002344
Richard Smith20e883e2015-04-29 23:20:19 +00002345 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002346 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002347}
2348
2349/// \brief Add template parameter chunks to the given code completion string.
2350static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002351 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002352 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002353 CodeCompletionBuilder &Result,
2354 unsigned MaxParameters = 0,
2355 unsigned Start = 0,
2356 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002357 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002358
2359 // Prefer to take the template parameter names from the first declaration of
2360 // the template.
2361 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2362
Douglas Gregor3545ff42009-09-21 16:56:56 +00002363 TemplateParameterList *Params = Template->getTemplateParameters();
2364 TemplateParameterList::iterator PEnd = Params->end();
2365 if (MaxParameters)
2366 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002367 for (TemplateParameterList::iterator P = Params->begin() + Start;
2368 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002369 bool HasDefaultArg = false;
2370 std::string PlaceholderStr;
2371 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2372 if (TTP->wasDeclaredWithTypename())
2373 PlaceholderStr = "typename";
2374 else
2375 PlaceholderStr = "class";
2376
2377 if (TTP->getIdentifier()) {
2378 PlaceholderStr += ' ';
2379 PlaceholderStr += TTP->getIdentifier()->getName();
2380 }
2381
2382 HasDefaultArg = TTP->hasDefaultArgument();
2383 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002384 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002385 if (NTTP->getIdentifier())
2386 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002387 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002388 HasDefaultArg = NTTP->hasDefaultArgument();
2389 } else {
2390 assert(isa<TemplateTemplateParmDecl>(*P));
2391 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2392
2393 // Since putting the template argument list into the placeholder would
2394 // be very, very long, we just use an abbreviation.
2395 PlaceholderStr = "template<...> class";
2396 if (TTP->getIdentifier()) {
2397 PlaceholderStr += ' ';
2398 PlaceholderStr += TTP->getIdentifier()->getName();
2399 }
2400
2401 HasDefaultArg = TTP->hasDefaultArgument();
2402 }
2403
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002404 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002405 // When we see an optional default argument, put that argument and
2406 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002407 CodeCompletionBuilder Opt(Result.getAllocator(),
2408 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002409 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002410 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002411 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002412 P - Params->begin(), true);
2413 Result.AddOptionalChunk(Opt.TakeString());
2414 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002415 }
2416
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002417 InDefaultArg = false;
2418
Douglas Gregor3545ff42009-09-21 16:56:56 +00002419 if (FirstParameter)
2420 FirstParameter = false;
2421 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002422 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002423
2424 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002425 Result.AddPlaceholderChunk(
2426 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002427 }
2428}
2429
Douglas Gregorf2510672009-09-21 19:57:38 +00002430/// \brief Add a qualifier to the given code-completion string, if the
2431/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002432static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002433AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002434 NestedNameSpecifier *Qualifier,
2435 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002436 ASTContext &Context,
2437 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002438 if (!Qualifier)
2439 return;
2440
2441 std::string PrintedNNS;
2442 {
2443 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002444 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002445 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002446 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002447 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002448 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002449 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002450}
2451
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002452static void
2453AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002454 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002455 const FunctionProtoType *Proto
2456 = Function->getType()->getAs<FunctionProtoType>();
2457 if (!Proto || !Proto->getTypeQuals())
2458 return;
2459
Douglas Gregor304f9b02011-02-01 21:15:40 +00002460 // FIXME: Add ref-qualifier!
2461
2462 // Handle single qualifiers without copying
2463 if (Proto->getTypeQuals() == Qualifiers::Const) {
2464 Result.AddInformativeChunk(" const");
2465 return;
2466 }
2467
2468 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2469 Result.AddInformativeChunk(" volatile");
2470 return;
2471 }
2472
2473 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2474 Result.AddInformativeChunk(" restrict");
2475 return;
2476 }
2477
2478 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002479 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002480 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002481 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002482 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002483 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002484 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002485 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002486 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002487}
2488
Douglas Gregor0212fd72010-09-21 16:06:22 +00002489/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002490static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002491 const NamedDecl *ND,
2492 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002493 DeclarationName Name = ND->getDeclName();
2494 if (!Name)
2495 return;
2496
2497 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002498 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002499 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002500 switch (Name.getCXXOverloadedOperator()) {
2501 case OO_None:
2502 case OO_Conditional:
2503 case NUM_OVERLOADED_OPERATORS:
2504 OperatorName = "operator";
2505 break;
2506
2507#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2508 case OO_##Name: OperatorName = "operator" Spelling; break;
2509#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2510#include "clang/Basic/OperatorKinds.def"
2511
2512 case OO_New: OperatorName = "operator new"; break;
2513 case OO_Delete: OperatorName = "operator delete"; break;
2514 case OO_Array_New: OperatorName = "operator new[]"; break;
2515 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2516 case OO_Call: OperatorName = "operator()"; break;
2517 case OO_Subscript: OperatorName = "operator[]"; break;
2518 }
2519 Result.AddTypedTextChunk(OperatorName);
2520 break;
2521 }
2522
Douglas Gregor0212fd72010-09-21 16:06:22 +00002523 case DeclarationName::Identifier:
2524 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002525 case DeclarationName::CXXDestructorName:
2526 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002527 Result.AddTypedTextChunk(
2528 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002529 break;
2530
2531 case DeclarationName::CXXUsingDirective:
2532 case DeclarationName::ObjCZeroArgSelector:
2533 case DeclarationName::ObjCOneArgSelector:
2534 case DeclarationName::ObjCMultiArgSelector:
2535 break;
2536
2537 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002538 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002539 QualType Ty = Name.getCXXNameType();
2540 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2541 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2542 else if (const InjectedClassNameType *InjectedTy
2543 = Ty->getAs<InjectedClassNameType>())
2544 Record = InjectedTy->getDecl();
2545 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002546 Result.AddTypedTextChunk(
2547 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002548 break;
2549 }
2550
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002551 Result.AddTypedTextChunk(
2552 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002553 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002554 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002555 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002556 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002557 }
2558 break;
2559 }
2560 }
2561}
2562
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002563CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002564 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002565 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002566 CodeCompletionTUInfo &CCTUInfo,
2567 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002568 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2569 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002570}
2571
Douglas Gregor3545ff42009-09-21 16:56:56 +00002572/// \brief If possible, create a new code completion string for the given
2573/// result.
2574///
2575/// \returns Either a new, heap-allocated code completion string describing
2576/// how to use this result, or NULL to indicate that the string or name of the
2577/// result is all that is needed.
2578CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002579CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2580 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002581 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002582 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002583 CodeCompletionTUInfo &CCTUInfo,
2584 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002585 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002586
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002587 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002588 if (Kind == RK_Pattern) {
2589 Pattern->Priority = Priority;
2590 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002591
2592 if (Declaration) {
2593 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002594 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002595 // Provide code completion comment for self.GetterName where
2596 // GetterName is the getter method for a property with name
2597 // different from the property name (declared via a property
2598 // getter attribute.
2599 const NamedDecl *ND = Declaration;
2600 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2601 if (M->isPropertyAccessor())
2602 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2603 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002604 PDecl->getIdentifier() != M->getIdentifier()) {
2605 if (const RawComment *RC =
2606 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002607 Result.addBriefComment(RC->getBriefText(Ctx));
2608 Pattern->BriefComment = Result.getBriefComment();
2609 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002610 else if (const RawComment *RC =
2611 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2612 Result.addBriefComment(RC->getBriefText(Ctx));
2613 Pattern->BriefComment = Result.getBriefComment();
2614 }
2615 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002616 }
2617
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002618 return Pattern;
2619 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002620
Douglas Gregorf09935f2009-12-01 05:55:20 +00002621 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002622 Result.AddTypedTextChunk(Keyword);
2623 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002624 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002625
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002626 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002627 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002628 Result.AddTypedTextChunk(
2629 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002630
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002631 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002632 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002633
2634 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002635 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002636 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002637
2638 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2639 if (MI->isC99Varargs()) {
2640 --AEnd;
2641
2642 if (A == AEnd) {
2643 Result.AddPlaceholderChunk("...");
2644 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002645 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002646
Douglas Gregor0c505312011-07-30 08:17:44 +00002647 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002648 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002649 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002650
2651 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002652 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002653 if (MI->isC99Varargs())
2654 Arg += ", ...";
2655 else
2656 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002657 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002658 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002659 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002660
2661 // Non-variadic macros are simple.
2662 Result.AddPlaceholderChunk(
2663 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002664 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002665 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002666 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002667 }
2668
Douglas Gregorf64acca2010-05-25 21:41:55 +00002669 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002670 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002671 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002672
2673 if (IncludeBriefComments) {
2674 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002675 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002676 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002677 }
2678 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2679 if (OMD->isPropertyAccessor())
2680 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2681 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2682 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002683 }
2684
Douglas Gregor9eb77012009-11-07 00:00:49 +00002685 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002686 Result.AddTypedTextChunk(
2687 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002688 Result.AddTextChunk("::");
2689 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002690 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002691
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002692 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2693 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002694
Douglas Gregorc3425b12015-07-07 06:20:19 +00002695 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002696
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002697 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002698 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002699 Ctx, Policy);
2700 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002701 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002702 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002703 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002704 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002705 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002706 }
2707
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002708 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002709 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002710 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002711 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002712 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002713
Douglas Gregor3545ff42009-09-21 16:56:56 +00002714 // Figure out which template parameters are deduced (or have default
2715 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002716 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002717 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002718 unsigned LastDeducibleArgument;
2719 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2720 --LastDeducibleArgument) {
2721 if (!Deduced[LastDeducibleArgument - 1]) {
2722 // C++0x: Figure out if the template argument has a default. If so,
2723 // the user doesn't need to type this argument.
2724 // FIXME: We need to abstract template parameters better!
2725 bool HasDefaultArg = false;
2726 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002727 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002728 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2729 HasDefaultArg = TTP->hasDefaultArgument();
2730 else if (NonTypeTemplateParmDecl *NTTP
2731 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2732 HasDefaultArg = NTTP->hasDefaultArgument();
2733 else {
2734 assert(isa<TemplateTemplateParmDecl>(Param));
2735 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002736 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002737 }
2738
2739 if (!HasDefaultArg)
2740 break;
2741 }
2742 }
2743
2744 if (LastDeducibleArgument) {
2745 // Some of the function template arguments cannot be deduced from a
2746 // function call, so we introduce an explicit template argument list
2747 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002748 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002749 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002750 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002751 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002752 }
2753
2754 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002755 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002756 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002757 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002758 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002759 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002760 }
2761
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002762 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002763 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002764 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002765 Result.AddTypedTextChunk(
2766 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002767 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002768 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002769 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002770 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002771 }
2772
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002773 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002774 Selector Sel = Method->getSelector();
2775 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002776 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002777 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002778 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002779 }
2780
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002781 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002782 SelName += ':';
2783 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002784 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002785 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002786 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002787
2788 // If there is only one parameter, and we're past it, add an empty
2789 // typed-text chunk since there is nothing to type.
2790 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002791 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002792 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002793 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002794 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2795 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002796 P != PEnd; (void)++P, ++Idx) {
2797 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002798 std::string Keyword;
2799 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002800 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002801 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002802 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002803 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002804 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002805 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002806 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002807 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002808 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002809
2810 // If we're before the starting parameter, skip the placeholder.
2811 if (Idx < StartParameter)
2812 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002813
2814 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002815 QualType ParamType = (*P)->getType();
2816 Optional<ArrayRef<QualType>> ObjCSubsts;
2817 if (!CCContext.getBaseType().isNull())
2818 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2819
2820 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2821 Arg = FormatFunctionParameter(Policy, *P, true,
2822 /*SuppressBlock=*/false,
2823 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002824 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002825 if (ObjCSubsts)
2826 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2827 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002828 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002829 ParamType);
2830 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002831 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002832 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002833 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002834 }
2835
Douglas Gregor400f5972010-08-31 05:13:43 +00002836 if (Method->isVariadic() && (P + 1) == PEnd)
2837 Arg += ", ...";
2838
Douglas Gregor95887f92010-07-08 23:20:03 +00002839 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002840 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002841 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002842 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002843 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002844 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002845 }
2846
Douglas Gregor04c5f972009-12-23 00:21:46 +00002847 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002848 if (Method->param_size() == 0) {
2849 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002850 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002851 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002852 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002853 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002854 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002855 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002856
Richard Smith20e883e2015-04-29 23:20:19 +00002857 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002858 }
2859
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002860 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002861 }
2862
Douglas Gregorf09935f2009-12-01 05:55:20 +00002863 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002864 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002865 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002866
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002867 Result.AddTypedTextChunk(
2868 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002869 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002870}
2871
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002872/// \brief Add function overload parameter chunks to the given code completion
2873/// string.
2874static void AddOverloadParameterChunks(ASTContext &Context,
2875 const PrintingPolicy &Policy,
2876 const FunctionDecl *Function,
2877 const FunctionProtoType *Prototype,
2878 CodeCompletionBuilder &Result,
2879 unsigned CurrentArg,
2880 unsigned Start = 0,
2881 bool InOptional = false) {
2882 bool FirstParameter = true;
2883 unsigned NumParams = Function ? Function->getNumParams()
2884 : Prototype->getNumParams();
2885
2886 for (unsigned P = Start; P != NumParams; ++P) {
2887 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2888 // When we see an optional default argument, put that argument and
2889 // the remaining default arguments into a new, optional string.
2890 CodeCompletionBuilder Opt(Result.getAllocator(),
2891 Result.getCodeCompletionTUInfo());
2892 if (!FirstParameter)
2893 Opt.AddChunk(CodeCompletionString::CK_Comma);
2894 // Optional sections are nested.
2895 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2896 CurrentArg, P, /*InOptional=*/true);
2897 Result.AddOptionalChunk(Opt.TakeString());
2898 return;
2899 }
2900
2901 if (FirstParameter)
2902 FirstParameter = false;
2903 else
2904 Result.AddChunk(CodeCompletionString::CK_Comma);
2905
2906 InOptional = false;
2907
2908 // Format the placeholder string.
2909 std::string Placeholder;
2910 if (Function)
Richard Smith20e883e2015-04-29 23:20:19 +00002911 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002912 else
2913 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2914
2915 if (P == CurrentArg)
2916 Result.AddCurrentParameterChunk(
2917 Result.getAllocator().CopyString(Placeholder));
2918 else
2919 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2920 }
2921
2922 if (Prototype && Prototype->isVariadic()) {
2923 CodeCompletionBuilder Opt(Result.getAllocator(),
2924 Result.getCodeCompletionTUInfo());
2925 if (!FirstParameter)
2926 Opt.AddChunk(CodeCompletionString::CK_Comma);
2927
2928 if (CurrentArg < NumParams)
2929 Opt.AddPlaceholderChunk("...");
2930 else
2931 Opt.AddCurrentParameterChunk("...");
2932
2933 Result.AddOptionalChunk(Opt.TakeString());
2934 }
2935}
2936
Douglas Gregorf0f51982009-09-23 00:34:09 +00002937CodeCompletionString *
2938CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002939 unsigned CurrentArg, Sema &S,
2940 CodeCompletionAllocator &Allocator,
2941 CodeCompletionTUInfo &CCTUInfo,
2942 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002943 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002944
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002945 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002946 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002947 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002948 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00002949 = dyn_cast<FunctionProtoType>(getFunctionType());
2950 if (!FDecl && !Proto) {
2951 // Function without a prototype. Just give the return type and a
2952 // highlighted ellipsis.
2953 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002954 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
2955 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002956 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2957 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2958 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002959 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002960 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002961
2962 if (FDecl) {
2963 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
2964 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
2965 FDecl->getParamDecl(CurrentArg)))
2966 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00002967 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002968 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002969 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2970 } else {
2971 Result.AddResultTypeChunk(
2972 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00002973 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002974 }
Alp Toker314cc812014-01-25 16:55:45 +00002975
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002976 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002977 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
2978 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002979 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002980
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002981 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002982}
2983
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002984unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002985 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002986 bool PreferredTypeIsPointer) {
2987 unsigned Priority = CCP_Macro;
2988
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002989 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2990 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2991 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002992 Priority = CCP_Constant;
2993 if (PreferredTypeIsPointer)
2994 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002995 }
2996 // Treat "YES", "NO", "true", and "false" as constants.
2997 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2998 MacroName.equals("true") || MacroName.equals("false"))
2999 Priority = CCP_Constant;
3000 // Treat "bool" as a type.
3001 else if (MacroName.equals("bool"))
3002 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3003
Douglas Gregor6e240332010-08-16 16:18:59 +00003004
3005 return Priority;
3006}
3007
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003008CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003009 if (!D)
3010 return CXCursor_UnexposedDecl;
3011
3012 switch (D->getKind()) {
3013 case Decl::Enum: return CXCursor_EnumDecl;
3014 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3015 case Decl::Field: return CXCursor_FieldDecl;
3016 case Decl::Function:
3017 return CXCursor_FunctionDecl;
3018 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3019 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003020 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003021
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003022 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003023 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3024 case Decl::ObjCMethod:
3025 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3026 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3027 case Decl::CXXMethod: return CXCursor_CXXMethod;
3028 case Decl::CXXConstructor: return CXCursor_Constructor;
3029 case Decl::CXXDestructor: return CXCursor_Destructor;
3030 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3031 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003032 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003033 case Decl::ParmVar: return CXCursor_ParmDecl;
3034 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003035 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00003036 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003037 case Decl::Var: return CXCursor_VarDecl;
3038 case Decl::Namespace: return CXCursor_Namespace;
3039 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3040 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3041 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3042 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3043 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3044 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003045 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003046 case Decl::ClassTemplatePartialSpecialization:
3047 return CXCursor_ClassTemplatePartialSpecialization;
3048 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003049 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003050
3051 case Decl::Using:
3052 case Decl::UnresolvedUsingValue:
3053 case Decl::UnresolvedUsingTypename:
3054 return CXCursor_UsingDeclaration;
3055
Douglas Gregor4cd65962011-06-03 23:08:58 +00003056 case Decl::ObjCPropertyImpl:
3057 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3058 case ObjCPropertyImplDecl::Dynamic:
3059 return CXCursor_ObjCDynamicDecl;
3060
3061 case ObjCPropertyImplDecl::Synthesize:
3062 return CXCursor_ObjCSynthesizeDecl;
3063 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003064
3065 case Decl::Import:
3066 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003067
3068 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3069
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003070 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003071 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003072 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003073 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003074 case TTK_Struct: return CXCursor_StructDecl;
3075 case TTK_Class: return CXCursor_ClassDecl;
3076 case TTK_Union: return CXCursor_UnionDecl;
3077 case TTK_Enum: return CXCursor_EnumDecl;
3078 }
3079 }
3080 }
3081
3082 return CXCursor_UnexposedDecl;
3083}
3084
Douglas Gregor55b037b2010-07-08 20:55:51 +00003085static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003086 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003087 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003088 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003089
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003090 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003091
Douglas Gregor9eb77012009-11-07 00:00:49 +00003092 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3093 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003094 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003095 auto MD = PP.getMacroDefinition(M->first);
3096 if (IncludeUndefined || MD) {
3097 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003098 if (MI->isUsedForHeaderGuard())
3099 continue;
3100
Douglas Gregor8cb17462012-10-09 16:01:50 +00003101 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003102 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003103 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003104 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003105 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003106 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003107
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003108 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003109
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003110}
3111
Douglas Gregorce0e8562010-08-23 21:54:33 +00003112static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3113 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003114 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003115
3116 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003117
Douglas Gregorce0e8562010-08-23 21:54:33 +00003118 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3119 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003120 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003121 Results.AddResult(Result("__func__", CCP_Constant));
3122 Results.ExitScope();
3123}
3124
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003125static void HandleCodeCompleteResults(Sema *S,
3126 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003127 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003128 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003129 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003130 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003131 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003132}
3133
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003134static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3135 Sema::ParserCompletionContext PCC) {
3136 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003137 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003138 return CodeCompletionContext::CCC_TopLevel;
3139
John McCallfaf5fb42010-08-26 23:41:50 +00003140 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003141 return CodeCompletionContext::CCC_ClassStructUnion;
3142
John McCallfaf5fb42010-08-26 23:41:50 +00003143 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003144 return CodeCompletionContext::CCC_ObjCInterface;
3145
John McCallfaf5fb42010-08-26 23:41:50 +00003146 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003147 return CodeCompletionContext::CCC_ObjCImplementation;
3148
John McCallfaf5fb42010-08-26 23:41:50 +00003149 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003150 return CodeCompletionContext::CCC_ObjCIvarList;
3151
John McCallfaf5fb42010-08-26 23:41:50 +00003152 case Sema::PCC_Template:
3153 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003154 if (S.CurContext->isFileContext())
3155 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003156 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003157 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003158 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003159
John McCallfaf5fb42010-08-26 23:41:50 +00003160 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003161 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003162
John McCallfaf5fb42010-08-26 23:41:50 +00003163 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003164 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3165 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003166 return CodeCompletionContext::CCC_ParenthesizedExpression;
3167 else
3168 return CodeCompletionContext::CCC_Expression;
3169
3170 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003171 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003172 return CodeCompletionContext::CCC_Expression;
3173
John McCallfaf5fb42010-08-26 23:41:50 +00003174 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003175 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003176
John McCallfaf5fb42010-08-26 23:41:50 +00003177 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003178 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003179
3180 case Sema::PCC_ParenthesizedExpression:
3181 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003182
3183 case Sema::PCC_LocalDeclarationSpecifiers:
3184 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003185 }
David Blaikie8a40f702012-01-17 06:56:22 +00003186
3187 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003188}
3189
Douglas Gregorac322ec2010-08-27 21:18:54 +00003190/// \brief If we're in a C++ virtual member function, add completion results
3191/// that invoke the functions we override, since it's common to invoke the
3192/// overridden function as well as adding new functionality.
3193///
3194/// \param S The semantic analysis object for which we are generating results.
3195///
3196/// \param InContext This context in which the nested-name-specifier preceding
3197/// the code-completion point
3198static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3199 ResultBuilder &Results) {
3200 // Look through blocks.
3201 DeclContext *CurContext = S.CurContext;
3202 while (isa<BlockDecl>(CurContext))
3203 CurContext = CurContext->getParent();
3204
3205
3206 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3207 if (!Method || !Method->isVirtual())
3208 return;
3209
3210 // We need to have names for all of the parameters, if we're going to
3211 // generate a forwarding call.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003212 for (auto P : Method->params())
3213 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003214 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003215
Douglas Gregor75acd922011-09-27 23:30:47 +00003216 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003217 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3218 MEnd = Method->end_overridden_methods();
3219 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003220 CodeCompletionBuilder Builder(Results.getAllocator(),
3221 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003222 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003223 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3224 continue;
3225
3226 // If we need a nested-name-specifier, add one now.
3227 if (!InContext) {
3228 NestedNameSpecifier *NNS
3229 = getRequiredQualification(S.Context, CurContext,
3230 Overridden->getDeclContext());
3231 if (NNS) {
3232 std::string Str;
3233 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003234 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003235 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003236 }
3237 } else if (!InContext->Equals(Overridden->getDeclContext()))
3238 continue;
3239
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003240 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003241 Overridden->getNameAsString()));
3242 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003243 bool FirstParam = true;
Aaron Ballman43b68be2014-03-07 17:50:17 +00003244 for (auto P : Method->params()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003245 if (FirstParam)
3246 FirstParam = false;
3247 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003248 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003249
Aaron Ballman43b68be2014-03-07 17:50:17 +00003250 Builder.AddPlaceholderChunk(
3251 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003252 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003253 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3254 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003255 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003256 CXCursor_CXXMethod,
3257 CXAvailability_Available,
3258 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003259 Results.Ignore(Overridden);
3260 }
3261}
3262
Douglas Gregor07f43572012-01-29 18:15:03 +00003263void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3264 ModuleIdPath Path) {
3265 typedef CodeCompletionResult Result;
3266 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003267 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003268 CodeCompletionContext::CCC_Other);
3269 Results.EnterNewScope();
3270
3271 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003272 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003273 typedef CodeCompletionResult Result;
3274 if (Path.empty()) {
3275 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003276 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003277 PP.getHeaderSearchInfo().collectAllModules(Modules);
3278 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3279 Builder.AddTypedTextChunk(
3280 Builder.getAllocator().CopyString(Modules[I]->Name));
3281 Results.AddResult(Result(Builder.TakeString(),
3282 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003283 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003284 Modules[I]->isAvailable()
3285 ? CXAvailability_Available
3286 : CXAvailability_NotAvailable));
3287 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003288 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003289 // Load the named module.
3290 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3291 Module::AllVisible,
3292 /*IsInclusionDirective=*/false);
3293 // Enumerate submodules.
3294 if (Mod) {
3295 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3296 SubEnd = Mod->submodule_end();
3297 Sub != SubEnd; ++Sub) {
3298
3299 Builder.AddTypedTextChunk(
3300 Builder.getAllocator().CopyString((*Sub)->Name));
3301 Results.AddResult(Result(Builder.TakeString(),
3302 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003303 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003304 (*Sub)->isAvailable()
3305 ? CXAvailability_Available
3306 : CXAvailability_NotAvailable));
3307 }
3308 }
3309 }
3310 Results.ExitScope();
3311 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3312 Results.data(),Results.size());
3313}
3314
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003315void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003316 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003317 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003318 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003319 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003320 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003321
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003322 // Determine how to filter results, e.g., so that the names of
3323 // values (functions, enumerators, function templates, etc.) are
3324 // only allowed where we can have an expression.
3325 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003326 case PCC_Namespace:
3327 case PCC_Class:
3328 case PCC_ObjCInterface:
3329 case PCC_ObjCImplementation:
3330 case PCC_ObjCInstanceVariableList:
3331 case PCC_Template:
3332 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003333 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003334 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003335 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3336 break;
3337
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003338 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003339 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003340 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003341 case PCC_ForInit:
3342 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003343 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003344 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3345 else
3346 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003347
David Blaikiebbafb8a2012-03-11 07:00:24 +00003348 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003349 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003350 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003351
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003352 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003353 // Unfiltered
3354 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003355 }
3356
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003357 // If we are in a C++ non-static member function, check the qualifiers on
3358 // the member function to filter/prioritize the results list.
3359 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3360 if (CurMethod->isInstance())
3361 Results.setObjectTypeQualifiers(
3362 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3363
Douglas Gregorc580c522010-01-14 01:09:38 +00003364 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003365 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3366 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003367
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003368 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003369 Results.ExitScope();
3370
Douglas Gregorce0e8562010-08-23 21:54:33 +00003371 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003372 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003373 case PCC_Expression:
3374 case PCC_Statement:
3375 case PCC_RecoveryInFunction:
3376 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00003377 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003378 break;
3379
3380 case PCC_Namespace:
3381 case PCC_Class:
3382 case PCC_ObjCInterface:
3383 case PCC_ObjCImplementation:
3384 case PCC_ObjCInstanceVariableList:
3385 case PCC_Template:
3386 case PCC_MemberTemplate:
3387 case PCC_ForInit:
3388 case PCC_Condition:
3389 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003390 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003391 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003392 }
3393
Douglas Gregor9eb77012009-11-07 00:00:49 +00003394 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003395 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003396
Douglas Gregor50832e02010-09-20 22:39:41 +00003397 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003398 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003399}
3400
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003401static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3402 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003403 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003404 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003405 bool IsSuper,
3406 ResultBuilder &Results);
3407
3408void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3409 bool AllowNonIdentifiers,
3410 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003411 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003412 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003413 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003414 AllowNestedNameSpecifiers
3415 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3416 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003417 Results.EnterNewScope();
3418
3419 // Type qualifiers can come after names.
3420 Results.AddResult(Result("const"));
3421 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003422 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003423 Results.AddResult(Result("restrict"));
3424
David Blaikiebbafb8a2012-03-11 07:00:24 +00003425 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003426 if (AllowNonIdentifiers) {
3427 Results.AddResult(Result("operator"));
3428 }
3429
3430 // Add nested-name-specifiers.
3431 if (AllowNestedNameSpecifiers) {
3432 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003433 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003434 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3435 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3436 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003437 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003438 }
3439 }
3440 Results.ExitScope();
3441
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003442 // If we're in a context where we might have an expression (rather than a
3443 // declaration), and what we've seen so far is an Objective-C type that could
3444 // be a receiver of a class message, this may be a class message send with
3445 // the initial opening bracket '[' missing. Add appropriate completions.
3446 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003447 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003448 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003449 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3450 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003451 !DS.isTypeAltiVecVector() &&
3452 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003453 (S->getFlags() & Scope::DeclScope) != 0 &&
3454 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3455 Scope::FunctionPrototypeScope |
3456 Scope::AtCatchScope)) == 0) {
3457 ParsedType T = DS.getRepAsType();
3458 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003459 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003460 }
3461
Douglas Gregor56ccce02010-08-24 04:59:56 +00003462 // Note that we intentionally suppress macro results here, since we do not
3463 // encourage using macros to produce the names of entities.
3464
Douglas Gregor0ac41382010-09-23 23:01:17 +00003465 HandleCodeCompleteResults(this, CodeCompleter,
3466 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003467 Results.data(), Results.size());
3468}
3469
Douglas Gregor68762e72010-08-23 21:17:50 +00003470struct Sema::CodeCompleteExpressionData {
3471 CodeCompleteExpressionData(QualType PreferredType = QualType())
3472 : PreferredType(PreferredType), IntegralConstantExpression(false),
3473 ObjCCollection(false) { }
3474
3475 QualType PreferredType;
3476 bool IntegralConstantExpression;
3477 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003478 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003479};
3480
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003481/// \brief Perform code-completion in an expression context when we know what
3482/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003483void Sema::CodeCompleteExpression(Scope *S,
3484 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003485 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003486 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003487 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003488 if (Data.ObjCCollection)
3489 Results.setFilter(&ResultBuilder::IsObjCCollection);
3490 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003491 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003492 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003493 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3494 else
3495 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003496
3497 if (!Data.PreferredType.isNull())
3498 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3499
3500 // Ignore any declarations that we were told that we don't care about.
3501 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3502 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003503
3504 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003505 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3506 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003507
3508 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003509 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003510 Results.ExitScope();
3511
Douglas Gregor55b037b2010-07-08 20:55:51 +00003512 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003513 if (!Data.PreferredType.isNull())
3514 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3515 || Data.PreferredType->isMemberPointerType()
3516 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003517
Douglas Gregorce0e8562010-08-23 21:54:33 +00003518 if (S->getFnParent() &&
3519 !Data.ObjCCollection &&
3520 !Data.IntegralConstantExpression)
Craig Topper12126262015-11-15 17:27:57 +00003521 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003522
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003523 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003524 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003525 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003526 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3527 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003528 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003529}
3530
Douglas Gregoreda7e542010-09-18 01:28:11 +00003531void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3532 if (E.isInvalid())
3533 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003534 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003535 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003536}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003537
Douglas Gregorb888acf2010-12-09 23:01:55 +00003538/// \brief The set of properties that have already been added, referenced by
3539/// property name.
3540typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3541
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003542/// \brief Retrieve the container definition, if any?
3543static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3544 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3545 if (Interface->hasDefinition())
3546 return Interface->getDefinition();
3547
3548 return Interface;
3549 }
3550
3551 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3552 if (Protocol->hasDefinition())
3553 return Protocol->getDefinition();
3554
3555 return Protocol;
3556 }
3557 return Container;
3558}
3559
Douglas Gregorc3425b12015-07-07 06:20:19 +00003560static void AddObjCProperties(const CodeCompletionContext &CCContext,
3561 ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003562 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003563 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003564 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003565 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003566 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003567 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003568
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003569 // Retrieve the definition.
3570 Container = getContainerDef(Container);
3571
Douglas Gregor9291bad2009-11-18 01:29:26 +00003572 // Add properties in this container.
Manman Rena7a8b1f2016-01-26 18:05:23 +00003573 for (const auto *P : Container->instance_properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003574 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003575 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003576 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003577
Douglas Gregor95147142011-05-05 15:50:42 +00003578 // Add nullary methods
3579 if (AllowNullaryMethods) {
3580 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003581 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003582 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003583 if (M->getSelector().isUnarySelector())
3584 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003585 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003586 CodeCompletionBuilder Builder(Results.getAllocator(),
3587 Results.getCodeCompletionTUInfo());
Douglas Gregorc3425b12015-07-07 06:20:19 +00003588 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3589 Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003590 Builder.AddTypedTextChunk(
3591 Results.getAllocator().CopyString(Name->getName()));
3592
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003593 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003594 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003595 CurContext);
3596 }
3597 }
3598 }
3599
3600
Douglas Gregor9291bad2009-11-18 01:29:26 +00003601 // Add properties in referenced protocols.
3602 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003603 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003604 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3605 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003606 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003607 if (AllowCategories) {
3608 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003609 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003610 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3611 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003612 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003613
Douglas Gregor9291bad2009-11-18 01:29:26 +00003614 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003615 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003616 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3617 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003618
3619 // Look in the superclass.
3620 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003621 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003622 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003623 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003624 } else if (const ObjCCategoryDecl *Category
3625 = dyn_cast<ObjCCategoryDecl>(Container)) {
3626 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003627 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003628 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3629 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003630 }
3631}
3632
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003633void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003634 SourceLocation OpLoc,
3635 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003636 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003637 return;
3638
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003639 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3640 if (ConvertedBase.isInvalid())
3641 return;
3642 Base = ConvertedBase.get();
3643
John McCall276321a2010-08-25 06:19:51 +00003644 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003645
Douglas Gregor2436e712009-09-17 21:32:03 +00003646 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003647
3648 if (IsArrow) {
3649 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3650 BaseType = Ptr->getPointeeType();
3651 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003652 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003653 else
3654 return;
3655 }
3656
Douglas Gregor21325842011-07-07 16:03:39 +00003657 enum CodeCompletionContext::Kind contextKind;
3658
3659 if (IsArrow) {
3660 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3661 }
3662 else {
3663 if (BaseType->isObjCObjectPointerType() ||
3664 BaseType->isObjCObjectOrInterfaceType()) {
3665 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3666 }
3667 else {
3668 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3669 }
3670 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003671
3672 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003673 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003674 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003675 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003676 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003677 Results.EnterNewScope();
3678 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003679 // Indicate that we are performing a member access, and the cv-qualifiers
3680 // for the base object type.
3681 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3682
Douglas Gregor9291bad2009-11-18 01:29:26 +00003683 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003684 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003685 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003686 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3687 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003688
David Blaikiebbafb8a2012-03-11 07:00:24 +00003689 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003690 if (!Results.empty()) {
3691 // The "template" keyword can follow "->" or "." in the grammar.
3692 // However, we only want to suggest the template keyword if something
3693 // is dependent.
3694 bool IsDependent = BaseType->isDependentType();
3695 if (!IsDependent) {
3696 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003697 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003698 IsDependent = Ctx->isDependentContext();
3699 break;
3700 }
3701 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003702
Douglas Gregor9291bad2009-11-18 01:29:26 +00003703 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003704 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003705 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003706 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003707 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3708 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003709 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003710
3711 // Add property results based on our interface.
3712 const ObjCObjectPointerType *ObjCPtr
3713 = BaseType->getAsObjCInterfacePointerType();
3714 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregorc3425b12015-07-07 06:20:19 +00003715 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
Douglas Gregor95147142011-05-05 15:50:42 +00003716 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003717 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003718
3719 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003720 for (auto *I : ObjCPtr->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003721 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3722 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003723 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003724 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003725 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003726 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003727 if (const ObjCObjectPointerType *ObjCPtr
3728 = BaseType->getAs<ObjCObjectPointerType>())
3729 Class = ObjCPtr->getInterfaceDecl();
3730 else
John McCall8b07ec22010-05-15 11:32:37 +00003731 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003732
3733 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003734 if (Class) {
3735 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3736 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003737 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3738 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003739 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003740 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003741
3742 // FIXME: How do we cope with isa?
3743
3744 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003745
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003746 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003747 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003748 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003749 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003750}
3751
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003752void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3753 if (!CodeCompleter)
3754 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003755
3756 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003757 enum CodeCompletionContext::Kind ContextKind
3758 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003759 switch ((DeclSpec::TST)TagSpec) {
3760 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003761 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003762 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003763 break;
3764
3765 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003766 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003767 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003768 break;
3769
3770 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003771 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003772 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003773 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003774 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003775 break;
3776
3777 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003778 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003779 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003780
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003781 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3782 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003783 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003784
3785 // First pass: look for tags.
3786 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003787 LookupVisibleDecls(S, LookupTagName, Consumer,
3788 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003789
Douglas Gregor39982192010-08-15 06:18:01 +00003790 if (CodeCompleter->includeGlobals()) {
3791 // Second pass: look for nested name specifiers.
3792 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3793 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3794 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003795
Douglas Gregor0ac41382010-09-23 23:01:17 +00003796 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003797 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003798}
3799
Douglas Gregor28c78432010-08-27 17:35:51 +00003800void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003801 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003802 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003803 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003804 Results.EnterNewScope();
3805 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3806 Results.AddResult("const");
3807 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3808 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003809 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003810 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3811 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003812 if (getLangOpts().C11 &&
3813 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3814 Results.AddResult("_Atomic");
Douglas Gregor28c78432010-08-27 17:35:51 +00003815 Results.ExitScope();
3816 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003817 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003818 Results.data(), Results.size());
3819}
3820
Benjamin Kramer72dae622016-02-18 15:30:24 +00003821void Sema::CodeCompleteBracketDeclarator(Scope *S) {
3822 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
3823}
3824
Douglas Gregord328d572009-09-21 18:10:23 +00003825void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003826 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003827 return;
John McCall5939b162011-08-06 07:30:58 +00003828
John McCallaab3e412010-08-25 08:40:02 +00003829 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003830 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3831 if (!type->isEnumeralType()) {
3832 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003833 Data.IntegralConstantExpression = true;
3834 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003835 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003836 }
Douglas Gregord328d572009-09-21 18:10:23 +00003837
3838 // Code-complete the cases of a switch statement over an enumeration type
3839 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003840 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003841 if (EnumDecl *Def = Enum->getDefinition())
3842 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003843
3844 // Determine which enumerators we have already seen in the switch statement.
3845 // FIXME: Ideally, we would also be able to look *past* the code-completion
3846 // token, in case we are code-completing in the middle of the switch and not
3847 // at the end. However, we aren't able to do so at the moment.
3848 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003849 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003850 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3851 SC = SC->getNextSwitchCase()) {
3852 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3853 if (!Case)
3854 continue;
3855
3856 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3857 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3858 if (EnumConstantDecl *Enumerator
3859 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3860 // We look into the AST of the case statement to determine which
3861 // enumerator was named. Alternatively, we could compute the value of
3862 // the integral constant expression, then compare it against the
3863 // values of each enumerator. However, value-based approach would not
3864 // work as well with C++ templates where enumerators declared within a
3865 // template are type- and value-dependent.
3866 EnumeratorsSeen.insert(Enumerator);
3867
Douglas Gregorf2510672009-09-21 19:57:38 +00003868 // If this is a qualified-id, keep track of the nested-name-specifier
3869 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003870 //
3871 // switch (TagD.getKind()) {
3872 // case TagDecl::TK_enum:
3873 // break;
3874 // case XXX
3875 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003876 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003877 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3878 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003879 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003880 }
3881 }
3882
David Blaikiebbafb8a2012-03-11 07:00:24 +00003883 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003884 // If there are no prior enumerators in C++, check whether we have to
3885 // qualify the names of the enumerators that we suggest, because they
3886 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003887 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003888 }
3889
Douglas Gregord328d572009-09-21 18:10:23 +00003890 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003891 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003892 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003893 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003894 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003895 for (auto *E : Enum->enumerators()) {
3896 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003897 continue;
3898
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003899 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003900 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003901 }
3902 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003903
Douglas Gregor21325842011-07-07 16:03:39 +00003904 //We need to make sure we're setting the right context,
3905 //so only say we include macros if the code completer says we do
3906 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3907 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003908 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003909 kind = CodeCompletionContext::CCC_OtherWithMacros;
3910 }
3911
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003912 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003913 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003914 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003915}
3916
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003917static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003918 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003919 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003920
3921 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003922 if (!Args[I])
3923 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003924
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003925 return false;
3926}
3927
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003928typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3929
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003930static void mergeCandidatesWithResults(Sema &SemaRef,
3931 SmallVectorImpl<ResultCandidate> &Results,
3932 OverloadCandidateSet &CandidateSet,
3933 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003934 if (!CandidateSet.empty()) {
3935 // Sort the overload candidate set by placing the best overloads first.
3936 std::stable_sort(
3937 CandidateSet.begin(), CandidateSet.end(),
3938 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3939 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3940 });
3941
3942 // Add the remaining viable overload candidates as code-completion results.
3943 for (auto &Candidate : CandidateSet)
3944 if (Candidate.Viable)
3945 Results.push_back(ResultCandidate(Candidate.Function));
3946 }
3947}
3948
3949/// \brief Get the type of the Nth parameter from a given set of overload
3950/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003951static QualType getParamType(Sema &SemaRef,
3952 ArrayRef<ResultCandidate> Candidates,
3953 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003954
3955 // Given the overloads 'Candidates' for a function call matching all arguments
3956 // up to N, return the type of the Nth parameter if it is the same for all
3957 // overload candidates.
3958 QualType ParamType;
3959 for (auto &Candidate : Candidates) {
3960 if (auto FType = Candidate.getFunctionType())
3961 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3962 if (N < Proto->getNumParams()) {
3963 if (ParamType.isNull())
3964 ParamType = Proto->getParamType(N);
3965 else if (!SemaRef.Context.hasSameUnqualifiedType(
3966 ParamType.getNonReferenceType(),
3967 Proto->getParamType(N).getNonReferenceType()))
3968 // Otherwise return a default-constructed QualType.
3969 return QualType();
3970 }
3971 }
3972
3973 return ParamType;
3974}
3975
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003976static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3977 MutableArrayRef<ResultCandidate> Candidates,
3978 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003979 bool CompleteExpressionWithCurrentArg = true) {
3980 QualType ParamType;
3981 if (CompleteExpressionWithCurrentArg)
3982 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3983
3984 if (ParamType.isNull())
3985 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3986 else
3987 SemaRef.CodeCompleteExpression(S, ParamType);
3988
3989 if (!Candidates.empty())
3990 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3991 Candidates.data(),
3992 Candidates.size());
3993}
3994
3995void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003996 if (!CodeCompleter)
3997 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003998
3999 // When we're code-completing for a call, we fall back to ordinary
4000 // name code-completion whenever we can't produce specific
4001 // results. We may want to revisit this strategy in the future,
4002 // e.g., by merging the two kinds of results.
4003
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004004 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004005
Douglas Gregorcabea402009-09-22 15:41:20 +00004006 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004007 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4008 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004009 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004010 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004011 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004012
John McCall57500772009-12-16 12:17:52 +00004013 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004014 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004015 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004016
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004017 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004018
John McCall57500772009-12-16 12:17:52 +00004019 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004020 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004021 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004022 /*PartialOverloading=*/true);
4023 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4024 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4025 if (UME->hasExplicitTemplateArgs()) {
4026 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4027 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004028 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004029 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4030 ArgExprs.append(Args.begin(), Args.end());
4031 UnresolvedSet<8> Decls;
4032 Decls.append(UME->decls_begin(), UME->decls_end());
4033 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4034 /*SuppressUsedConversions=*/false,
4035 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004036 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004037 FunctionDecl *FD = nullptr;
4038 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4039 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4040 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4041 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004042 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004043 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004044 !FD->getType()->getAs<FunctionProtoType>())
4045 Results.push_back(ResultCandidate(FD));
4046 else
4047 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4048 Args, CandidateSet,
4049 /*SuppressUsedConversions=*/false,
4050 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004051
4052 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4053 // If expression's type is CXXRecordDecl, it may overload the function
4054 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004055 // A complete type is needed to lookup for member function call operators.
Richard Smithdb0ac552015-12-18 22:40:25 +00004056 if (isCompleteType(Loc, NakedFn->getType())) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004057 DeclarationName OpName = Context.DeclarationNames
4058 .getCXXOperatorName(OO_Call);
4059 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4060 LookupQualifiedName(R, DC);
4061 R.suppressDiagnostics();
4062 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4063 ArgExprs.append(Args.begin(), Args.end());
4064 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4065 /*ExplicitArgs=*/nullptr,
4066 /*SuppressUsedConversions=*/false,
4067 /*PartialOverloading=*/true);
4068 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004069 } else {
4070 // Lastly we check whether expression's type is function pointer or
4071 // function.
4072 QualType T = NakedFn->getType();
4073 if (!T->getPointeeType().isNull())
4074 T = T->getPointeeType();
4075
4076 if (auto FP = T->getAs<FunctionProtoType>()) {
4077 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004078 /*PartialOverloading=*/true) ||
4079 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004080 Results.push_back(ResultCandidate(FP));
4081 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004082 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004083 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004084 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004085 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004086
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004087 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4088 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4089 !CandidateSet.empty());
4090}
4091
4092void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4093 ArrayRef<Expr *> Args) {
4094 if (!CodeCompleter)
4095 return;
4096
4097 // A complete type is needed to lookup for constructors.
Richard Smithdb0ac552015-12-18 22:40:25 +00004098 if (!isCompleteType(Loc, Type))
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004099 return;
4100
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004101 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4102 if (!RD) {
4103 CodeCompleteExpression(S, Type);
4104 return;
4105 }
4106
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004107 // FIXME: Provide support for member initializers.
4108 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004109
4110 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4111
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004112 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004113 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4114 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4115 Args, CandidateSet,
4116 /*SuppressUsedConversions=*/false,
4117 /*PartialOverloading=*/true);
4118 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4119 AddTemplateOverloadCandidate(FTD,
4120 DeclAccessPair::make(FTD, C->getAccess()),
4121 /*ExplicitTemplateArgs=*/nullptr,
4122 Args, CandidateSet,
4123 /*SuppressUsedConversions=*/false,
4124 /*PartialOverloading=*/true);
4125 }
4126 }
4127
4128 SmallVector<ResultCandidate, 8> Results;
4129 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4130 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004131}
4132
John McCall48871652010-08-21 09:40:31 +00004133void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4134 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004135 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004136 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004137 return;
4138 }
4139
4140 CodeCompleteExpression(S, VD->getType());
4141}
4142
4143void Sema::CodeCompleteReturn(Scope *S) {
4144 QualType ResultType;
4145 if (isa<BlockDecl>(CurContext)) {
4146 if (BlockScopeInfo *BSI = getCurBlock())
4147 ResultType = BSI->ReturnType;
4148 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004149 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004150 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004151 ResultType = Method->getReturnType();
4152
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004153 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004154 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004155 else
4156 CodeCompleteExpression(S, ResultType);
4157}
4158
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004159void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004161 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004162 mapCodeCompletionContext(*this, PCC_Statement));
4163 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4164 Results.EnterNewScope();
4165
4166 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4167 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4168 CodeCompleter->includeGlobals());
4169
4170 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4171
4172 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004173 CodeCompletionBuilder Builder(Results.getAllocator(),
4174 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004175 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004176 if (Results.includeCodePatterns()) {
4177 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4178 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4179 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4180 Builder.AddPlaceholderChunk("statements");
4181 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4182 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4183 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004184 Results.AddResult(Builder.TakeString());
4185
4186 // "else if" block
4187 Builder.AddTypedTextChunk("else");
4188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4189 Builder.AddTextChunk("if");
4190 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004192 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004193 Builder.AddPlaceholderChunk("condition");
4194 else
4195 Builder.AddPlaceholderChunk("expression");
4196 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004197 if (Results.includeCodePatterns()) {
4198 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4199 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4200 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4201 Builder.AddPlaceholderChunk("statements");
4202 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4203 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4204 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004205 Results.AddResult(Builder.TakeString());
4206
4207 Results.ExitScope();
4208
4209 if (S->getFnParent())
Craig Topper12126262015-11-15 17:27:57 +00004210 AddPrettyFunctionResults(getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004211
4212 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004213 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004214
4215 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4216 Results.data(),Results.size());
4217}
4218
Richard Trieu2bd04012011-09-09 02:00:50 +00004219void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004220 if (LHS)
4221 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4222 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004223 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004224}
4225
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004226void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004227 bool EnteringContext) {
4228 if (!SS.getScopeRep() || !CodeCompleter)
4229 return;
4230
Douglas Gregor3545ff42009-09-21 16:56:56 +00004231 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4232 if (!Ctx)
4233 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004234
4235 // Try to instantiate any non-dependent declaration contexts before
4236 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004237 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004238 return;
4239
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004240 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004241 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004242 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004243 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004244
Douglas Gregor3545ff42009-09-21 16:56:56 +00004245 // The "template" keyword can follow "::" in the grammar, but only
4246 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004247 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004248 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004249 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004250
4251 // Add calls to overridden virtual functions, if there are any.
4252 //
4253 // FIXME: This isn't wonderful, because we don't know whether we're actually
4254 // in a context that permits expressions. This is a general issue with
4255 // qualified-id completions.
4256 if (!EnteringContext)
4257 MaybeAddOverrideCalls(*this, Ctx, Results);
4258 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004259
Douglas Gregorac322ec2010-08-27 21:18:54 +00004260 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4261 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4262
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004263 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004264 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004265 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004266}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004267
4268void Sema::CodeCompleteUsing(Scope *S) {
4269 if (!CodeCompleter)
4270 return;
4271
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004272 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004273 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004274 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4275 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004276 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004277
4278 // If we aren't in class scope, we could see the "namespace" keyword.
4279 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004280 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004281
4282 // After "using", we can see anything that would start a
4283 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004284 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004285 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4286 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004287 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004288
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004289 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004290 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004291 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004292}
4293
4294void Sema::CodeCompleteUsingDirective(Scope *S) {
4295 if (!CodeCompleter)
4296 return;
4297
Douglas Gregor3545ff42009-09-21 16:56:56 +00004298 // After "using namespace", we expect to see a namespace name or namespace
4299 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004300 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004301 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004302 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004303 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004304 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004305 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004306 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4307 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004308 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004309 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004310 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004311 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004312}
4313
4314void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4315 if (!CodeCompleter)
4316 return;
4317
Ted Kremenekc37877d2013-10-08 17:08:03 +00004318 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004319 if (!S->getParent())
4320 Ctx = Context.getTranslationUnitDecl();
4321
Douglas Gregor0ac41382010-09-23 23:01:17 +00004322 bool SuppressedGlobalResults
4323 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4324
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004325 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004326 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004327 SuppressedGlobalResults
4328 ? CodeCompletionContext::CCC_Namespace
4329 : CodeCompletionContext::CCC_Other,
4330 &ResultBuilder::IsNamespace);
4331
4332 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004333 // We only want to see those namespaces that have already been defined
4334 // within this scope, because its likely that the user is creating an
4335 // extended namespace declaration. Keep track of the most recent
4336 // definition of each namespace.
4337 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4338 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4339 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4340 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004341 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004342
4343 // Add the most recent definition (or extended definition) of each
4344 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004345 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004346 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004347 NS = OrigToLatest.begin(),
4348 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004349 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004350 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004351 NS->second, Results.getBasePriority(NS->second),
4352 nullptr),
4353 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004354 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004355 }
4356
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004357 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004358 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004359 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004360}
4361
4362void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4363 if (!CodeCompleter)
4364 return;
4365
Douglas Gregor3545ff42009-09-21 16:56:56 +00004366 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004367 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004368 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004369 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004370 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004371 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004372 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4373 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004374 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004375 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004376 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004377}
4378
Douglas Gregorc811ede2009-09-18 20:05:18 +00004379void Sema::CodeCompleteOperatorName(Scope *S) {
4380 if (!CodeCompleter)
4381 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004382
John McCall276321a2010-08-25 06:19:51 +00004383 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004384 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004385 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004386 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004387 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004388 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004389
Douglas Gregor3545ff42009-09-21 16:56:56 +00004390 // Add the names of overloadable operators.
4391#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4392 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004393 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004394#include "clang/Basic/OperatorKinds.def"
4395
4396 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004397 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004398 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004399 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4400 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004401
4402 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004403 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004404 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004405
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004406 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004407 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004408 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004409}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004410
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004411void Sema::CodeCompleteConstructorInitializer(
4412 Decl *ConstructorD,
4413 ArrayRef <CXXCtorInitializer *> Initializers) {
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004414 if (!ConstructorD)
4415 return;
4416
4417 AdjustDeclIfTemplate(ConstructorD);
4418
4419 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004420 if (!Constructor)
4421 return;
4422
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004423 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004424 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004425 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004426 Results.EnterNewScope();
4427
4428 // Fill in any already-initialized fields or base classes.
4429 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4430 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004431 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004432 if (Initializers[I]->isBaseInitializer())
4433 InitializedBases.insert(
4434 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4435 else
Francois Pichetd583da02010-12-04 09:14:42 +00004436 InitializedFields.insert(cast<FieldDecl>(
4437 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004438 }
4439
4440 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004441 CodeCompletionBuilder Builder(Results.getAllocator(),
4442 Results.getCodeCompletionTUInfo());
Benjamin Kramera4f8df02015-07-09 15:31:10 +00004443 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004444 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004445 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004446 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004447 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4448 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004449 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004450 = !Initializers.empty() &&
4451 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004452 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004453 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004454 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004455 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004456
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004457 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004458 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004459 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004460 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4461 Builder.AddPlaceholderChunk("args");
4462 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4463 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004464 SawLastInitializer? CCP_NextInitializer
4465 : CCP_MemberDeclaration));
4466 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004467 }
4468
4469 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004470 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004471 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4472 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004473 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004474 = !Initializers.empty() &&
4475 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004476 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004477 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004478 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004479 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004480
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004481 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004482 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004483 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004484 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4485 Builder.AddPlaceholderChunk("args");
4486 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4487 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004488 SawLastInitializer? CCP_NextInitializer
4489 : CCP_MemberDeclaration));
4490 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004491 }
4492
4493 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004494 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004495 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4496 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004497 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004498 = !Initializers.empty() &&
4499 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004500 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004501 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004502 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004503
4504 if (!Field->getDeclName())
4505 continue;
4506
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004507 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004508 Field->getIdentifier()->getName()));
4509 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4510 Builder.AddPlaceholderChunk("args");
4511 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4512 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004513 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004514 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004515 CXCursor_MemberRef,
4516 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004517 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004518 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004519 }
4520 Results.ExitScope();
4521
Douglas Gregor0ac41382010-09-23 23:01:17 +00004522 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004523 Results.data(), Results.size());
4524}
4525
Douglas Gregord8c61782012-02-15 15:34:24 +00004526/// \brief Determine whether this scope denotes a namespace.
4527static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004528 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004529 if (!DC)
4530 return false;
4531
4532 return DC->isFileContext();
4533}
4534
4535void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4536 bool AfterAmpersand) {
4537 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004538 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004539 CodeCompletionContext::CCC_Other);
4540 Results.EnterNewScope();
4541
4542 // Note what has already been captured.
4543 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4544 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004545 for (const auto &C : Intro.Captures) {
4546 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004547 IncludedThis = true;
4548 continue;
4549 }
4550
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004551 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004552 }
4553
4554 // Look for other capturable variables.
4555 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004556 for (const auto *D : S->decls()) {
4557 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004558 if (!Var ||
4559 !Var->hasLocalStorage() ||
4560 Var->hasAttr<BlocksAttr>())
4561 continue;
4562
David Blaikie82e95a32014-11-19 07:49:47 +00004563 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004564 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004565 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004566 }
4567 }
4568
4569 // Add 'this', if it would be valid.
4570 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4571 addThisCompletion(*this, Results);
4572
4573 Results.ExitScope();
4574
4575 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4576 Results.data(), Results.size());
4577}
4578
James Dennett596e4752012-06-14 03:11:41 +00004579/// Macro that optionally prepends an "@" to the string literal passed in via
4580/// Keyword, depending on whether NeedAt is true or false.
4581#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4582
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004583static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004584 ResultBuilder &Results,
4585 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004586 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004587 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004588 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004589
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004590 CodeCompletionBuilder Builder(Results.getAllocator(),
4591 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004592 if (LangOpts.ObjC2) {
4593 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004594 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4596 Builder.AddPlaceholderChunk("property");
4597 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004598
4599 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004600 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004601 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4602 Builder.AddPlaceholderChunk("property");
4603 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004604 }
4605}
4606
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004607static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004608 ResultBuilder &Results,
4609 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004610 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004611
4612 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004613 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004614
4615 if (LangOpts.ObjC2) {
4616 // @property
James Dennett596e4752012-06-14 03:11:41 +00004617 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004618
4619 // @required
James Dennett596e4752012-06-14 03:11:41 +00004620 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004621
4622 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004623 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004624 }
4625}
4626
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004627static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004628 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004629 CodeCompletionBuilder Builder(Results.getAllocator(),
4630 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004631
4632 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004633 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004634 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4635 Builder.AddPlaceholderChunk("name");
4636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004637
Douglas Gregorf4c33342010-05-28 00:22:41 +00004638 if (Results.includeCodePatterns()) {
4639 // @interface name
4640 // FIXME: Could introduce the whole pattern, including superclasses and
4641 // such.
James Dennett596e4752012-06-14 03:11:41 +00004642 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004643 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4644 Builder.AddPlaceholderChunk("class");
4645 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004646
Douglas Gregorf4c33342010-05-28 00:22:41 +00004647 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004648 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4650 Builder.AddPlaceholderChunk("protocol");
4651 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004652
4653 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004654 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004655 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4656 Builder.AddPlaceholderChunk("class");
4657 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004658 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004659
4660 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004661 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4663 Builder.AddPlaceholderChunk("alias");
4664 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4665 Builder.AddPlaceholderChunk("class");
4666 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004667
4668 if (Results.getSema().getLangOpts().Modules) {
4669 // @import name
4670 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4671 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4672 Builder.AddPlaceholderChunk("module");
4673 Results.AddResult(Result(Builder.TakeString()));
4674 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004675}
4676
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004677void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004678 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004679 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004680 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004681 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004682 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004683 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004684 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004685 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004686 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004687 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004688 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004689 HandleCodeCompleteResults(this, CodeCompleter,
4690 CodeCompletionContext::CCC_Other,
4691 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004692}
4693
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004694static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004695 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004696 CodeCompletionBuilder Builder(Results.getAllocator(),
4697 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004698
4699 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004700 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004701 if (Results.getSema().getLangOpts().CPlusPlus ||
4702 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004703 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004704 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004705 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004706 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4707 Builder.AddPlaceholderChunk("type-name");
4708 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4709 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004710
4711 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004712 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004713 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004714 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4715 Builder.AddPlaceholderChunk("protocol-name");
4716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4717 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004718
4719 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004720 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004721 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004722 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4723 Builder.AddPlaceholderChunk("selector");
4724 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4725 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004726
4727 // @"string"
4728 Builder.AddResultTypeChunk("NSString *");
4729 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4730 Builder.AddPlaceholderChunk("string");
4731 Builder.AddTextChunk("\"");
4732 Results.AddResult(Result(Builder.TakeString()));
4733
Douglas Gregor951de302012-07-17 23:24:47 +00004734 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004735 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004736 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004737 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004738 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4739 Results.AddResult(Result(Builder.TakeString()));
4740
Douglas Gregor951de302012-07-17 23:24:47 +00004741 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004742 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004743 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004744 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004745 Builder.AddChunk(CodeCompletionString::CK_Colon);
4746 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4747 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004748 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4749 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004750
Douglas Gregor951de302012-07-17 23:24:47 +00004751 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004752 Builder.AddResultTypeChunk("id");
4753 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004754 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004755 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4756 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004757}
4758
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004759static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004760 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004761 CodeCompletionBuilder Builder(Results.getAllocator(),
4762 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004763
Douglas Gregorf4c33342010-05-28 00:22:41 +00004764 if (Results.includeCodePatterns()) {
4765 // @try { statements } @catch ( declaration ) { statements } @finally
4766 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004767 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004768 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4769 Builder.AddPlaceholderChunk("statements");
4770 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4771 Builder.AddTextChunk("@catch");
4772 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4773 Builder.AddPlaceholderChunk("parameter");
4774 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4775 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4776 Builder.AddPlaceholderChunk("statements");
4777 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4778 Builder.AddTextChunk("@finally");
4779 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4780 Builder.AddPlaceholderChunk("statements");
4781 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4782 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004783 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004784
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004785 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004786 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004787 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4788 Builder.AddPlaceholderChunk("expression");
4789 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004790
Douglas Gregorf4c33342010-05-28 00:22:41 +00004791 if (Results.includeCodePatterns()) {
4792 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004793 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4796 Builder.AddPlaceholderChunk("expression");
4797 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4798 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4799 Builder.AddPlaceholderChunk("statements");
4800 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4801 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004802 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004803}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004804
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004805static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004806 ResultBuilder &Results,
4807 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004808 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004809 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4810 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4811 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004812 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004813 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004814}
4815
4816void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004817 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004818 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004819 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004820 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004821 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004822 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004823 HandleCodeCompleteResults(this, CodeCompleter,
4824 CodeCompletionContext::CCC_Other,
4825 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004826}
4827
4828void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004829 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004830 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004831 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004832 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004833 AddObjCStatementResults(Results, false);
4834 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004835 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004836 HandleCodeCompleteResults(this, CodeCompleter,
4837 CodeCompletionContext::CCC_Other,
4838 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004839}
4840
4841void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004842 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004843 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004844 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004845 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004846 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004847 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004848 HandleCodeCompleteResults(this, CodeCompleter,
4849 CodeCompletionContext::CCC_Other,
4850 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004851}
4852
Douglas Gregore6078da2009-11-19 00:14:45 +00004853/// \brief Determine whether the addition of the given flag to an Objective-C
4854/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004855static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004856 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004857 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004858 return true;
4859
Bill Wendling44426052012-12-20 19:22:21 +00004860 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004861
4862 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004863 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4864 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004865 return true;
4866
Jordan Rose53cb2f32012-08-20 20:01:13 +00004867 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004868 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004869 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004870 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004871 ObjCDeclSpec::DQ_PR_retain |
4872 ObjCDeclSpec::DQ_PR_strong |
4873 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004874 if (AssignCopyRetMask &&
4875 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004876 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004877 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004878 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004879 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4880 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004881 return true;
4882
4883 return false;
4884}
4885
Douglas Gregor36029f42009-11-18 23:08:07 +00004886void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004887 if (!CodeCompleter)
4888 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004889
Bill Wendling44426052012-12-20 19:22:21 +00004890 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004891
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004892 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004893 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004894 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004895 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004896 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004897 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004898 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004899 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004900 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004901 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4902 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004903 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004904 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004905 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004906 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004907 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004908 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004909 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004910 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004911 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004912 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004913 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004914 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004915
4916 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall460ce582015-10-22 18:38:17 +00004917 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004918 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004919 Results.AddResult(CodeCompletionResult("weak"));
4920
Bill Wendling44426052012-12-20 19:22:21 +00004921 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004922 CodeCompletionBuilder Setter(Results.getAllocator(),
4923 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004924 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004925 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004926 Setter.AddPlaceholderChunk("method");
4927 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004928 }
Bill Wendling44426052012-12-20 19:22:21 +00004929 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004930 CodeCompletionBuilder Getter(Results.getAllocator(),
4931 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004932 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004933 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004934 Getter.AddPlaceholderChunk("method");
4935 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004936 }
Douglas Gregor86b42682015-06-19 18:27:52 +00004937 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4938 Results.AddResult(CodeCompletionResult("nonnull"));
4939 Results.AddResult(CodeCompletionResult("nullable"));
4940 Results.AddResult(CodeCompletionResult("null_unspecified"));
4941 Results.AddResult(CodeCompletionResult("null_resettable"));
4942 }
Steve Naroff936354c2009-10-08 21:55:05 +00004943 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004944 HandleCodeCompleteResults(this, CodeCompleter,
4945 CodeCompletionContext::CCC_Other,
4946 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004947}
Steve Naroffeae65032009-11-07 02:08:14 +00004948
James Dennettf1243872012-06-17 05:33:25 +00004949/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004950/// via code completion.
4951enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004952 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4953 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4954 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004955};
4956
Douglas Gregor67c692c2010-08-26 15:07:07 +00004957static bool isAcceptableObjCSelector(Selector Sel,
4958 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004959 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004960 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004961 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004962 if (NumSelIdents > Sel.getNumArgs())
4963 return false;
4964
4965 switch (WantKind) {
4966 case MK_Any: break;
4967 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4968 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4969 }
4970
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004971 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4972 return false;
4973
Douglas Gregor67c692c2010-08-26 15:07:07 +00004974 for (unsigned I = 0; I != NumSelIdents; ++I)
4975 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4976 return false;
4977
4978 return true;
4979}
4980
Douglas Gregorc8537c52009-11-19 07:41:15 +00004981static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4982 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004983 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004984 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004985 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004986 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004987}
Douglas Gregor1154e272010-09-16 16:06:31 +00004988
4989namespace {
4990 /// \brief A set of selectors, which is used to avoid introducing multiple
4991 /// completions with the same selector into the result set.
4992 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4993}
4994
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004995/// \brief Add all of the Objective-C methods in the given Objective-C
4996/// container to the set of results.
4997///
4998/// The container will be a class, protocol, category, or implementation of
4999/// any of the above. This mether will recurse to include methods from
5000/// the superclasses of classes along with their categories, protocols, and
5001/// implementations.
5002///
5003/// \param Container the container in which we'll look to find methods.
5004///
James Dennett596e4752012-06-14 03:11:41 +00005005/// \param WantInstanceMethods Whether to add instance methods (only); if
5006/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005007///
5008/// \param CurContext the context in which we're performing the lookup that
5009/// finds methods.
5010///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005011/// \param AllowSameLength Whether we allow a method to be added to the list
5012/// when it has the same number of parameters as we have selector identifiers.
5013///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005014/// \param Results the structure into which we'll add results.
5015static void AddObjCMethods(ObjCContainerDecl *Container,
5016 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00005017 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005018 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005019 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00005020 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005021 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00005022 ResultBuilder &Results,
5023 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00005024 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005025 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005026 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5027 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005028 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005029 // The instance methods on the root class can be messaged via the
5030 // metaclass.
5031 if (M->isInstanceMethod() == WantInstanceMethods ||
5032 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005033 // Check whether the selector identifiers we've been given are a
5034 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005035 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005036 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005037
David Blaikie82e95a32014-11-19 07:49:47 +00005038 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005039 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005040
5041 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005042 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005043 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005044 if (!InOriginalClass)
5045 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005046 Results.MaybeAddResult(R, CurContext);
5047 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005048 }
5049
Douglas Gregorf37c9492010-09-16 15:34:59 +00005050 // Visit the protocols of protocols.
5051 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005052 if (Protocol->hasDefinition()) {
5053 const ObjCList<ObjCProtocolDecl> &Protocols
5054 = Protocol->getReferencedProtocols();
5055 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5056 E = Protocols.end();
5057 I != E; ++I)
5058 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005059 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005060 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005061 }
5062
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005063 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005064 return;
5065
5066 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005067 for (auto *I : IFace->protocols())
5068 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005069 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005070
5071 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005072 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005073 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005074 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005075 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005076
5077 // Add a categories protocol methods.
5078 const ObjCList<ObjCProtocolDecl> &Protocols
5079 = CatDecl->getReferencedProtocols();
5080 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5081 E = Protocols.end();
5082 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005083 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005084 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005085 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005086
5087 // Add methods in category implementations.
5088 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005089 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005090 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005091 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005092 }
5093
5094 // Add methods in superclass.
5095 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005096 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005097 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005098 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005099
5100 // Add methods in our implementation, if any.
5101 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005102 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005103 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005104 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005105}
5106
5107
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005108void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005109 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005110 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005111 if (!Class) {
5112 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005113 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005114 Class = Category->getClassInterface();
5115
5116 if (!Class)
5117 return;
5118 }
5119
5120 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005121 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005122 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005123 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005124 Results.EnterNewScope();
5125
Douglas Gregor1154e272010-09-16 16:06:31 +00005126 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005127 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005128 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005129 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005130 HandleCodeCompleteResults(this, CodeCompleter,
5131 CodeCompletionContext::CCC_Other,
5132 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005133}
5134
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005135void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005136 // Try to find the interface where setters might live.
5137 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005138 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005139 if (!Class) {
5140 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005141 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005142 Class = Category->getClassInterface();
5143
5144 if (!Class)
5145 return;
5146 }
5147
5148 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005149 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005150 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005151 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005152 Results.EnterNewScope();
5153
Douglas Gregor1154e272010-09-16 16:06:31 +00005154 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005155 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005156 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005157
5158 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005159 HandleCodeCompleteResults(this, CodeCompleter,
5160 CodeCompletionContext::CCC_Other,
5161 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005162}
5163
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005164void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5165 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005167 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005168 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005169 Results.EnterNewScope();
5170
5171 // Add context-sensitive, Objective-C parameter-passing keywords.
5172 bool AddedInOut = false;
5173 if ((DS.getObjCDeclQualifier() &
5174 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5175 Results.AddResult("in");
5176 Results.AddResult("inout");
5177 AddedInOut = true;
5178 }
5179 if ((DS.getObjCDeclQualifier() &
5180 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5181 Results.AddResult("out");
5182 if (!AddedInOut)
5183 Results.AddResult("inout");
5184 }
5185 if ((DS.getObjCDeclQualifier() &
5186 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5187 ObjCDeclSpec::DQ_Oneway)) == 0) {
5188 Results.AddResult("bycopy");
5189 Results.AddResult("byref");
5190 Results.AddResult("oneway");
5191 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005192 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5193 Results.AddResult("nonnull");
5194 Results.AddResult("nullable");
5195 Results.AddResult("null_unspecified");
5196 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005197
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005198 // If we're completing the return type of an Objective-C method and the
5199 // identifier IBAction refers to a macro, provide a completion item for
5200 // an action, e.g.,
5201 // IBAction)<#selector#>:(id)sender
5202 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005203 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005204 CodeCompletionBuilder Builder(Results.getAllocator(),
5205 Results.getCodeCompletionTUInfo(),
5206 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005207 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005208 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005209 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005210 Builder.AddChunk(CodeCompletionString::CK_Colon);
5211 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005212 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005213 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005214 Builder.AddTextChunk("sender");
5215 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5216 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005217
5218 // If we're completing the return type, provide 'instancetype'.
5219 if (!IsParameter) {
5220 Results.AddResult(CodeCompletionResult("instancetype"));
5221 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005222
Douglas Gregor99fa2642010-08-24 01:06:58 +00005223 // Add various builtin type names and specifiers.
5224 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5225 Results.ExitScope();
5226
5227 // Add the various type names
5228 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5229 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5230 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5231 CodeCompleter->includeGlobals());
5232
5233 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005234 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005235
5236 HandleCodeCompleteResults(this, CodeCompleter,
5237 CodeCompletionContext::CCC_Type,
5238 Results.data(), Results.size());
5239}
5240
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005241/// \brief When we have an expression with type "id", we may assume
5242/// that it has some more-specific class type based on knowledge of
5243/// common uses of Objective-C. This routine returns that class type,
5244/// or NULL if no better result could be determined.
5245static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005246 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005247 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005248 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005249
5250 Selector Sel = Msg->getSelector();
5251 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005252 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005253
5254 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5255 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005256 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005257
5258 ObjCMethodDecl *Method = Msg->getMethodDecl();
5259 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005260 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005261
5262 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005263 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005264 switch (Msg->getReceiverKind()) {
5265 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005266 if (const ObjCObjectType *ObjType
5267 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5268 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005269 break;
5270
5271 case ObjCMessageExpr::Instance: {
5272 QualType T = Msg->getInstanceReceiver()->getType();
5273 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5274 IFace = Ptr->getInterfaceDecl();
5275 break;
5276 }
5277
5278 case ObjCMessageExpr::SuperInstance:
5279 case ObjCMessageExpr::SuperClass:
5280 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005281 }
5282
5283 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005284 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005285
5286 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5287 if (Method->isInstanceMethod())
5288 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5289 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005290 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005291 .Case("autorelease", IFace)
5292 .Case("copy", IFace)
5293 .Case("copyWithZone", IFace)
5294 .Case("mutableCopy", IFace)
5295 .Case("mutableCopyWithZone", IFace)
5296 .Case("awakeFromCoder", IFace)
5297 .Case("replacementObjectFromCoder", IFace)
5298 .Case("class", IFace)
5299 .Case("classForCoder", IFace)
5300 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005301 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005302
5303 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5304 .Case("new", IFace)
5305 .Case("alloc", IFace)
5306 .Case("allocWithZone", IFace)
5307 .Case("class", IFace)
5308 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005309 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005310}
5311
Douglas Gregor6fc04132010-08-27 15:10:57 +00005312// Add a special completion for a message send to "super", which fills in the
5313// most likely case of forwarding all of our arguments to the superclass
5314// function.
5315///
5316/// \param S The semantic analysis object.
5317///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005318/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005319/// the "super" keyword. Otherwise, we just need to provide the arguments.
5320///
5321/// \param SelIdents The identifiers in the selector that have already been
5322/// provided as arguments for a send to "super".
5323///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005324/// \param Results The set of results to augment.
5325///
5326/// \returns the Objective-C method declaration that would be invoked by
5327/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005328static ObjCMethodDecl *AddSuperSendCompletion(
5329 Sema &S, bool NeedSuperKeyword,
5330 ArrayRef<IdentifierInfo *> SelIdents,
5331 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005332 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5333 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005334 return nullptr;
5335
Douglas Gregor6fc04132010-08-27 15:10:57 +00005336 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5337 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005338 return nullptr;
5339
Douglas Gregor6fc04132010-08-27 15:10:57 +00005340 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005341 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005342 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5343 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005344 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5345 CurMethod->isInstanceMethod());
5346
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005347 // Check in categories or class extensions.
5348 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005349 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005350 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005351 CurMethod->isInstanceMethod())))
5352 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005353 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005354 }
5355 }
5356
Douglas Gregor6fc04132010-08-27 15:10:57 +00005357 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005358 return nullptr;
5359
Douglas Gregor6fc04132010-08-27 15:10:57 +00005360 // Check whether the superclass method has the same signature.
5361 if (CurMethod->param_size() != SuperMethod->param_size() ||
5362 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005363 return nullptr;
5364
Douglas Gregor6fc04132010-08-27 15:10:57 +00005365 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5366 CurPEnd = CurMethod->param_end(),
5367 SuperP = SuperMethod->param_begin();
5368 CurP != CurPEnd; ++CurP, ++SuperP) {
5369 // Make sure the parameter types are compatible.
5370 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5371 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005372 return nullptr;
5373
Douglas Gregor6fc04132010-08-27 15:10:57 +00005374 // Make sure we have a parameter name to forward!
5375 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005376 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005377 }
5378
5379 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005380 CodeCompletionBuilder Builder(Results.getAllocator(),
5381 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005382
5383 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005384 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5385 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005386 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005387
5388 // If we need the "super" keyword, add it (plus some spacing).
5389 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005390 Builder.AddTypedTextChunk("super");
5391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005392 }
5393
5394 Selector Sel = CurMethod->getSelector();
5395 if (Sel.isUnarySelector()) {
5396 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005397 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005398 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005399 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005400 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005401 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005402 } else {
5403 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5404 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005405 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005407
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005408 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005409 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005410 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005411 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005412 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005413 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005414 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005415 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005416 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005417 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005418 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005419 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005420 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005421 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005422 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005423 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005424 }
5425 }
5426 }
5427
Douglas Gregor78254c82012-03-27 23:34:16 +00005428 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5429 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005430 return SuperMethod;
5431}
5432
Douglas Gregora817a192010-05-27 23:06:34 +00005433void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005434 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005435 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005436 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005437 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005438 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005439 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5440 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005441
Douglas Gregora817a192010-05-27 23:06:34 +00005442 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5443 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005444 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5445 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005446
5447 // If we are in an Objective-C method inside a class that has a superclass,
5448 // add "super" as an option.
5449 if (ObjCMethodDecl *Method = getCurMethodDecl())
5450 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005451 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005452 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005453
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005454 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005455 }
Douglas Gregora817a192010-05-27 23:06:34 +00005456
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005457 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005458 addThisCompletion(*this, Results);
5459
Douglas Gregora817a192010-05-27 23:06:34 +00005460 Results.ExitScope();
5461
5462 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005463 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005464 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005465 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005466
5467}
5468
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005469void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005470 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005471 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005472 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005473 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5474 // Figure out which interface we're in.
5475 CDecl = CurMethod->getClassInterface();
5476 if (!CDecl)
5477 return;
5478
5479 // Find the superclass of this class.
5480 CDecl = CDecl->getSuperClass();
5481 if (!CDecl)
5482 return;
5483
5484 if (CurMethod->isInstanceMethod()) {
5485 // We are inside an instance method, which means that the message
5486 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005487 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005488 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005489 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005490 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005491 }
5492
5493 // Fall through to send to the superclass in CDecl.
5494 } else {
5495 // "super" may be the name of a type or variable. Figure out which
5496 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005497 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005498 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5499 LookupOrdinaryName);
5500 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5501 // "super" names an interface. Use it.
5502 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005503 if (const ObjCObjectType *Iface
5504 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5505 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005506 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5507 // "super" names an unresolved type; we can't be more specific.
5508 } else {
5509 // Assume that "super" names some kind of value and parse that way.
5510 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005511 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005512 UnqualifiedId id;
5513 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005514 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5515 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005516 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005517 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005518 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005519 }
5520
5521 // Fall through
5522 }
5523
John McCallba7bf592010-08-24 05:47:05 +00005524 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005525 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005526 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005527 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005528 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005529 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005530}
5531
Douglas Gregor74661272010-09-21 00:03:25 +00005532/// \brief Given a set of code-completion results for the argument of a message
5533/// send, determine the preferred type (if any) for that argument expression.
5534static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5535 unsigned NumSelIdents) {
5536 typedef CodeCompletionResult Result;
5537 ASTContext &Context = Results.getSema().Context;
5538
5539 QualType PreferredType;
5540 unsigned BestPriority = CCP_Unlikely * 2;
5541 Result *ResultsData = Results.data();
5542 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5543 Result &R = ResultsData[I];
5544 if (R.Kind == Result::RK_Declaration &&
5545 isa<ObjCMethodDecl>(R.Declaration)) {
5546 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005547 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005548 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005549 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005550 ->getType();
5551 if (R.Priority < BestPriority || PreferredType.isNull()) {
5552 BestPriority = R.Priority;
5553 PreferredType = MyPreferredType;
5554 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5555 MyPreferredType)) {
5556 PreferredType = QualType();
5557 }
5558 }
5559 }
5560 }
5561 }
5562
5563 return PreferredType;
5564}
5565
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005566static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5567 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005568 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005569 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005570 bool IsSuper,
5571 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005572 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005573 ObjCInterfaceDecl *CDecl = nullptr;
5574
Douglas Gregor8ce33212009-11-17 17:59:40 +00005575 // If the given name refers to an interface type, retrieve the
5576 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005577 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005578 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005579 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005580 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5581 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005582 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005583
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005584 // Add all of the factory methods in this Objective-C class, its protocols,
5585 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005586 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005587
Douglas Gregor6fc04132010-08-27 15:10:57 +00005588 // If this is a send-to-super, try to add the special "super" send
5589 // completion.
5590 if (IsSuper) {
5591 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005592 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005593 Results.Ignore(SuperMethod);
5594 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005595
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005596 // If we're inside an Objective-C method definition, prefer its selector to
5597 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005598 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005599 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005600
Douglas Gregor1154e272010-09-16 16:06:31 +00005601 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005602 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005603 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005604 SemaRef.CurContext, Selectors, AtArgumentExpression,
5605 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005606 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005607 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005608
Douglas Gregord720daf2010-04-06 17:30:22 +00005609 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005610 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005611 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005612 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005613 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005614 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005615 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005616 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005617 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005618
5619 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005620 }
5621 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005622
5623 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5624 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005625 M != MEnd; ++M) {
5626 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005627 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005628 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005629 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005630 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005631
Nico Weber2e0c8f72014-12-27 03:58:08 +00005632 Result R(MethList->getMethod(),
5633 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005634 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005635 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005636 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005637 }
5638 }
5639 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005640
5641 Results.ExitScope();
5642}
Douglas Gregor6285f752010-04-06 16:40:00 +00005643
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005644void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005645 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005646 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005647 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005648
5649 QualType T = this->GetTypeFromParser(Receiver);
5650
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005651 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005652 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005653 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005654 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005655
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005656 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005657 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005658
5659 // If we're actually at the argument expression (rather than prior to the
5660 // selector), we're actually performing code completion for an expression.
5661 // Determine whether we have a single, best method. If so, we can
5662 // code-complete the expression using the corresponding parameter type as
5663 // our preferred type, improving completion results.
5664 if (AtArgumentExpression) {
5665 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005666 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005667 if (PreferredType.isNull())
5668 CodeCompleteOrdinaryName(S, PCC_Expression);
5669 else
5670 CodeCompleteExpression(S, PreferredType);
5671 return;
5672 }
5673
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005674 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005675 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005676 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005677}
5678
Richard Trieu2bd04012011-09-09 02:00:50 +00005679void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005680 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005681 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005682 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005683 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005684
5685 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005686
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005687 // If necessary, apply function/array conversion to the receiver.
5688 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005689 if (RecExpr) {
5690 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5691 if (Conv.isInvalid()) // conversion failed. bail.
5692 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005693 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005694 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005695 QualType ReceiverType = RecExpr? RecExpr->getType()
5696 : Super? Context.getObjCObjectPointerType(
5697 Context.getObjCInterfaceType(Super))
5698 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005699
Douglas Gregordc520b02010-11-08 21:12:30 +00005700 // If we're messaging an expression with type "id" or "Class", check
5701 // whether we know something special about the receiver that allows
5702 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005703 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005704 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5705 if (ReceiverType->isObjCClassType())
5706 return CodeCompleteObjCClassMessage(S,
5707 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005708 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005709 AtArgumentExpression, Super);
5710
5711 ReceiverType = Context.getObjCObjectPointerType(
5712 Context.getObjCInterfaceType(IFace));
5713 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005714 } else if (RecExpr && getLangOpts().CPlusPlus) {
5715 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5716 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005717 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005718 ReceiverType = RecExpr->getType();
5719 }
5720 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005721
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005722 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005723 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005724 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005725 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005726 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005727
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005728 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005729
Douglas Gregor6fc04132010-08-27 15:10:57 +00005730 // If this is a send-to-super, try to add the special "super" send
5731 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005732 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005733 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005734 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005735 Results.Ignore(SuperMethod);
5736 }
5737
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005738 // If we're inside an Objective-C method definition, prefer its selector to
5739 // others.
5740 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5741 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005742
Douglas Gregor1154e272010-09-16 16:06:31 +00005743 // Keep track of the selectors we've already added.
5744 VisitedSelectorSet Selectors;
5745
Douglas Gregora3329fa2009-11-18 00:06:18 +00005746 // Handle messages to Class. This really isn't a message to an instance
5747 // method, so we treat it the same way we would treat a message send to a
5748 // class method.
5749 if (ReceiverType->isObjCClassType() ||
5750 ReceiverType->isObjCQualifiedClassType()) {
5751 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5752 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005753 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005754 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005755 }
5756 }
5757 // Handle messages to a qualified ID ("id<foo>").
5758 else if (const ObjCObjectPointerType *QualID
5759 = ReceiverType->getAsObjCQualifiedIdType()) {
5760 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005761 for (auto *I : QualID->quals())
5762 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005763 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005764 }
5765 // Handle messages to a pointer to interface type.
5766 else if (const ObjCObjectPointerType *IFacePtr
5767 = ReceiverType->getAsObjCInterfacePointerType()) {
5768 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005769 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005770 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005771 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005772
5773 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005774 for (auto *I : IFacePtr->quals())
5775 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005776 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005777 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005778 // Handle messages to "id".
5779 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005780 // We're messaging "id", so provide all instance methods we know
5781 // about as code-completion results.
5782
5783 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005784 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005785 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005786 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5787 I != N; ++I) {
5788 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005789 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005790 continue;
5791
Sebastian Redl75d8a322010-08-02 23:18:59 +00005792 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005793 }
5794 }
5795
Sebastian Redl75d8a322010-08-02 23:18:59 +00005796 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5797 MEnd = MethodPool.end();
5798 M != MEnd; ++M) {
5799 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005800 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005801 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005802 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005803 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005804
Nico Weber2e0c8f72014-12-27 03:58:08 +00005805 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005806 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005807
Nico Weber2e0c8f72014-12-27 03:58:08 +00005808 Result R(MethList->getMethod(),
5809 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005810 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005811 R.AllParametersAreInformative = false;
5812 Results.MaybeAddResult(R, CurContext);
5813 }
5814 }
5815 }
Steve Naroffeae65032009-11-07 02:08:14 +00005816 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005817
5818
5819 // If we're actually at the argument expression (rather than prior to the
5820 // selector), we're actually performing code completion for an expression.
5821 // Determine whether we have a single, best method. If so, we can
5822 // code-complete the expression using the corresponding parameter type as
5823 // our preferred type, improving completion results.
5824 if (AtArgumentExpression) {
5825 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005826 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005827 if (PreferredType.isNull())
5828 CodeCompleteOrdinaryName(S, PCC_Expression);
5829 else
5830 CodeCompleteExpression(S, PreferredType);
5831 return;
5832 }
5833
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005834 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005835 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005836 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005837}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005838
Douglas Gregor68762e72010-08-23 21:17:50 +00005839void Sema::CodeCompleteObjCForCollection(Scope *S,
5840 DeclGroupPtrTy IterationVar) {
5841 CodeCompleteExpressionData Data;
5842 Data.ObjCCollection = true;
5843
5844 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005845 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005846 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5847 if (*I)
5848 Data.IgnoreDecls.push_back(*I);
5849 }
5850 }
5851
5852 CodeCompleteExpression(S, Data);
5853}
5854
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005855void Sema::CodeCompleteObjCSelector(Scope *S,
5856 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005857 // If we have an external source, load the entire class method
5858 // pool from the AST file.
5859 if (ExternalSource) {
5860 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5861 I != N; ++I) {
5862 Selector Sel = ExternalSource->GetExternalSelector(I);
5863 if (Sel.isNull() || MethodPool.count(Sel))
5864 continue;
5865
5866 ReadMethodPool(Sel);
5867 }
5868 }
5869
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005870 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005871 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005872 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005873 Results.EnterNewScope();
5874 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5875 MEnd = MethodPool.end();
5876 M != MEnd; ++M) {
5877
5878 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005879 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005880 continue;
5881
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005882 CodeCompletionBuilder Builder(Results.getAllocator(),
5883 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005884 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005885 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005886 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005887 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005888 continue;
5889 }
5890
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005891 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005892 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005893 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005894 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005895 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005896 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005897 Accumulator.clear();
5898 }
5899 }
5900
Benjamin Kramer632500c2011-07-26 16:59:25 +00005901 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005902 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005903 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005904 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005905 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005906 }
5907 Results.ExitScope();
5908
5909 HandleCodeCompleteResults(this, CodeCompleter,
5910 CodeCompletionContext::CCC_SelectorName,
5911 Results.data(), Results.size());
5912}
5913
Douglas Gregorbaf69612009-11-18 04:19:12 +00005914/// \brief Add all of the protocol declarations that we find in the given
5915/// (translation unit) context.
5916static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005917 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005918 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005919 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005920
Aaron Ballman629afae2014-03-07 19:56:05 +00005921 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005922 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005923 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005924 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005925 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5926 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005927 }
5928}
5929
Craig Topper883dd332015-12-24 23:58:11 +00005930void Sema::CodeCompleteObjCProtocolReferences(
5931 ArrayRef<IdentifierLocPair> Protocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005932 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005933 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005934 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005935
Douglas Gregora3b23b02010-12-09 21:44:02 +00005936 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5937 Results.EnterNewScope();
5938
5939 // Tell the result set to ignore all of the protocols we have
5940 // already seen.
5941 // FIXME: This doesn't work when caching code-completion results.
Craig Topper883dd332015-12-24 23:58:11 +00005942 for (const IdentifierLocPair &Pair : Protocols)
5943 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
5944 Pair.second))
Douglas Gregora3b23b02010-12-09 21:44:02 +00005945 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005946
Douglas Gregora3b23b02010-12-09 21:44:02 +00005947 // Add all protocols.
5948 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5949 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005950
Douglas Gregora3b23b02010-12-09 21:44:02 +00005951 Results.ExitScope();
5952 }
5953
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005954 HandleCodeCompleteResults(this, CodeCompleter,
5955 CodeCompletionContext::CCC_ObjCProtocolName,
5956 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005957}
5958
5959void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005960 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005961 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005962 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005963
Douglas Gregora3b23b02010-12-09 21:44:02 +00005964 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5965 Results.EnterNewScope();
5966
5967 // Add all protocols.
5968 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5969 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005970
Douglas Gregora3b23b02010-12-09 21:44:02 +00005971 Results.ExitScope();
5972 }
5973
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005974 HandleCodeCompleteResults(this, CodeCompleter,
5975 CodeCompletionContext::CCC_ObjCProtocolName,
5976 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005977}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005978
5979/// \brief Add all of the Objective-C interface declarations that we find in
5980/// the given (translation unit) context.
5981static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5982 bool OnlyForwardDeclarations,
5983 bool OnlyUnimplemented,
5984 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005985 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005986
Aaron Ballman629afae2014-03-07 19:56:05 +00005987 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005988 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005989 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005990 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005991 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005992 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5993 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005994 }
5995}
5996
5997void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005998 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005999 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006000 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006001 Results.EnterNewScope();
6002
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006003 if (CodeCompleter->includeGlobals()) {
6004 // Add all classes.
6005 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6006 false, Results);
6007 }
6008
Douglas Gregor49c22a72009-11-18 16:26:39 +00006009 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006010
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006011 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006012 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006013 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006014}
6015
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006016void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6017 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006018 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006019 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006020 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006021 Results.EnterNewScope();
6022
6023 // Make sure that we ignore the class we're currently defining.
6024 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006025 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006026 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006027 Results.Ignore(CurClass);
6028
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006029 if (CodeCompleter->includeGlobals()) {
6030 // Add all classes.
6031 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6032 false, Results);
6033 }
6034
Douglas Gregor49c22a72009-11-18 16:26:39 +00006035 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006036
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006037 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006038 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006039 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006040}
6041
6042void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006043 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006044 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006045 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006046 Results.EnterNewScope();
6047
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006048 if (CodeCompleter->includeGlobals()) {
6049 // Add all unimplemented classes.
6050 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6051 true, Results);
6052 }
6053
Douglas Gregor49c22a72009-11-18 16:26:39 +00006054 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006055
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006056 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006057 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006058 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006059}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006060
6061void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006062 IdentifierInfo *ClassName,
6063 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006064 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006065
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006066 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006067 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006068 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006069
6070 // Ignore any categories we find that have already been implemented by this
6071 // interface.
6072 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6073 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006074 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006075 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006076 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006077 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006078 }
6079
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006080 // Add all of the categories we know about.
6081 Results.EnterNewScope();
6082 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006083 for (const auto *D : TU->decls())
6084 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006085 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006086 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6087 nullptr),
6088 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006089 Results.ExitScope();
6090
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006091 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006092 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006093 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006094}
6095
6096void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006097 IdentifierInfo *ClassName,
6098 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006099 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006100
6101 // Find the corresponding interface. If we couldn't find the interface, the
6102 // program itself is ill-formed. However, we'll try to be helpful still by
6103 // providing the list of all of the categories we know about.
6104 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006105 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006106 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6107 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006108 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006109
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006110 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006111 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006112 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006113
6114 // Add all of the categories that have have corresponding interface
6115 // declarations in this class and any of its superclasses, except for
6116 // already-implemented categories in the class itself.
6117 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6118 Results.EnterNewScope();
6119 bool IgnoreImplemented = true;
6120 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006121 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006122 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006123 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006124 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6125 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006126 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006127
6128 Class = Class->getSuperClass();
6129 IgnoreImplemented = false;
6130 }
6131 Results.ExitScope();
6132
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006133 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006134 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006135 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006136}
Douglas Gregor5d649882009-11-18 22:32:06 +00006137
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006138void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006139 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006140 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006141 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006142 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006143
6144 // Figure out where this @synthesize lives.
6145 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006146 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006147 if (!Container ||
6148 (!isa<ObjCImplementationDecl>(Container) &&
6149 !isa<ObjCCategoryImplDecl>(Container)))
6150 return;
6151
6152 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006153 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006154 for (const auto *D : Container->decls())
6155 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006156 Results.Ignore(PropertyImpl->getPropertyDecl());
6157
6158 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006159 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006160 Results.EnterNewScope();
6161 if (ObjCImplementationDecl *ClassImpl
6162 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006163 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006164 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006165 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006166 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006167 AddObjCProperties(CCContext,
6168 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006169 false, /*AllowNullaryMethods=*/false, CurContext,
6170 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006171 Results.ExitScope();
6172
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006173 HandleCodeCompleteResults(this, CodeCompleter,
6174 CodeCompletionContext::CCC_Other,
6175 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006176}
6177
6178void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006179 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006180 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006181 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006182 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006183 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006184
6185 // Figure out where this @synthesize lives.
6186 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006187 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006188 if (!Container ||
6189 (!isa<ObjCImplementationDecl>(Container) &&
6190 !isa<ObjCCategoryImplDecl>(Container)))
6191 return;
6192
6193 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006194 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006195 if (ObjCImplementationDecl *ClassImpl
Manman Ren5b786402016-01-28 18:49:28 +00006196 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor5d649882009-11-18 22:32:06 +00006197 Class = ClassImpl->getClassInterface();
6198 else
6199 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6200 ->getClassInterface();
6201
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006202 // Determine the type of the property we're synthesizing.
6203 QualType PropertyType = Context.getObjCIdType();
6204 if (Class) {
Manman Ren5b786402016-01-28 18:49:28 +00006205 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6206 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006207 PropertyType
6208 = Property->getType().getNonReferenceType().getUnqualifiedType();
6209
6210 // Give preference to ivars
6211 Results.setPreferredType(PropertyType);
6212 }
6213 }
6214
Douglas Gregor5d649882009-11-18 22:32:06 +00006215 // Add all of the instance variables in this class and its superclasses.
6216 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006217 bool SawSimilarlyNamedIvar = false;
6218 std::string NameWithPrefix;
6219 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006220 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006221 std::string NameWithSuffix = PropertyName->getName().str();
6222 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006223 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006224 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6225 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006226 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6227 CurContext, nullptr, false);
6228
Douglas Gregor331faa02011-04-18 14:13:53 +00006229 // Determine whether we've seen an ivar with a name similar to the
6230 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006231 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006232 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006233 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006234 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006235
6236 // Reduce the priority of this result by one, to give it a slight
6237 // advantage over other results whose names don't match so closely.
6238 if (Results.size() &&
6239 Results.data()[Results.size() - 1].Kind
6240 == CodeCompletionResult::RK_Declaration &&
6241 Results.data()[Results.size() - 1].Declaration == Ivar)
6242 Results.data()[Results.size() - 1].Priority--;
6243 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006244 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006245 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006246
6247 if (!SawSimilarlyNamedIvar) {
6248 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006249 // an ivar of the appropriate type.
6250 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006251 typedef CodeCompletionResult Result;
6252 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006253 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6254 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006255
Douglas Gregor75acd922011-09-27 23:30:47 +00006256 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006257 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006258 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006259 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6260 Results.AddResult(Result(Builder.TakeString(), Priority,
6261 CXCursor_ObjCIvarDecl));
6262 }
6263
Douglas Gregor5d649882009-11-18 22:32:06 +00006264 Results.ExitScope();
6265
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006266 HandleCodeCompleteResults(this, CodeCompleter,
6267 CodeCompletionContext::CCC_Other,
6268 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006269}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006270
Douglas Gregor416b5752010-08-25 01:08:01 +00006271// Mapping from selectors to the methods that implement that selector, along
6272// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006273typedef llvm::DenseMap<
6274 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006275
6276/// \brief Find all of the methods that reside in the given container
6277/// (and its superclasses, protocols, etc.) that meet the given
6278/// criteria. Insert those methods into the map of known methods,
6279/// indexed by selector so they can be easily found.
6280static void FindImplementableMethods(ASTContext &Context,
6281 ObjCContainerDecl *Container,
6282 bool WantInstanceMethods,
6283 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006284 KnownMethodsMap &KnownMethods,
6285 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006286 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006287 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006288 if (!IFace->hasDefinition())
6289 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006290
6291 IFace = IFace->getDefinition();
6292 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006293
Douglas Gregor636a61e2010-04-07 00:21:17 +00006294 const ObjCList<ObjCProtocolDecl> &Protocols
6295 = IFace->getReferencedProtocols();
6296 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006297 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006298 I != E; ++I)
6299 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006300 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006301
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006302 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006303 for (auto *Cat : IFace->visible_categories()) {
6304 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006305 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006306 }
6307
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006308 // Visit the superclass.
6309 if (IFace->getSuperClass())
6310 FindImplementableMethods(Context, IFace->getSuperClass(),
6311 WantInstanceMethods, ReturnType,
6312 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006313 }
6314
6315 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6316 // Recurse into protocols.
6317 const ObjCList<ObjCProtocolDecl> &Protocols
6318 = Category->getReferencedProtocols();
6319 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006320 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006321 I != E; ++I)
6322 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006323 KnownMethods, InOriginalClass);
6324
6325 // If this category is the original class, jump to the interface.
6326 if (InOriginalClass && Category->getClassInterface())
6327 FindImplementableMethods(Context, Category->getClassInterface(),
6328 WantInstanceMethods, ReturnType, KnownMethods,
6329 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006330 }
6331
6332 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006333 // Make sure we have a definition; that's what we'll walk.
6334 if (!Protocol->hasDefinition())
6335 return;
6336 Protocol = Protocol->getDefinition();
6337 Container = Protocol;
6338
6339 // Recurse into protocols.
6340 const ObjCList<ObjCProtocolDecl> &Protocols
6341 = Protocol->getReferencedProtocols();
6342 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6343 E = Protocols.end();
6344 I != E; ++I)
6345 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6346 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006347 }
6348
6349 // Add methods in this container. This operation occurs last because
6350 // we want the methods from this container to override any methods
6351 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006352 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006353 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006354 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006355 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006356 continue;
6357
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006358 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006359 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006360 }
6361 }
6362}
6363
Douglas Gregor669a25a2011-02-17 00:22:45 +00006364/// \brief Add the parenthesized return or parameter type chunk to a code
6365/// completion string.
6366static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006367 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006368 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006369 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006370 CodeCompletionBuilder &Builder) {
6371 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006372 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006373 if (!Quals.empty())
6374 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006375 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006376 Builder.getAllocator()));
6377 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6378}
6379
6380/// \brief Determine whether the given class is or inherits from a class by
6381/// the given name.
6382static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006383 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006384 if (!Class)
6385 return false;
6386
6387 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6388 return true;
6389
6390 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6391}
6392
6393/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6394/// Key-Value Observing (KVO).
6395static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6396 bool IsInstanceMethod,
6397 QualType ReturnType,
6398 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006399 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006400 ResultBuilder &Results) {
6401 IdentifierInfo *PropName = Property->getIdentifier();
6402 if (!PropName || PropName->getLength() == 0)
6403 return;
6404
Douglas Gregor75acd922011-09-27 23:30:47 +00006405 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6406
Douglas Gregor669a25a2011-02-17 00:22:45 +00006407 // Builder that will create each code completion.
6408 typedef CodeCompletionResult Result;
6409 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006410 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006411
6412 // The selector table.
6413 SelectorTable &Selectors = Context.Selectors;
6414
6415 // The property name, copied into the code completion allocation region
6416 // on demand.
6417 struct KeyHolder {
6418 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006419 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006420 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006421
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006422 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006423 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6424
Douglas Gregor669a25a2011-02-17 00:22:45 +00006425 operator const char *() {
6426 if (CopiedKey)
6427 return CopiedKey;
6428
6429 return CopiedKey = Allocator.CopyString(Key);
6430 }
6431 } Key(Allocator, PropName->getName());
6432
6433 // The uppercased name of the property name.
6434 std::string UpperKey = PropName->getName();
6435 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006436 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006437
6438 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6439 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6440 Property->getType());
6441 bool ReturnTypeMatchesVoid
6442 = ReturnType.isNull() || ReturnType->isVoidType();
6443
6444 // Add the normal accessor -(type)key.
6445 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006446 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006447 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6448 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006449 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6450 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006451
6452 Builder.AddTypedTextChunk(Key);
6453 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6454 CXCursor_ObjCInstanceMethodDecl));
6455 }
6456
6457 // If we have an integral or boolean property (or the user has provided
6458 // an integral or boolean return type), add the accessor -(type)isKey.
6459 if (IsInstanceMethod &&
6460 ((!ReturnType.isNull() &&
6461 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6462 (ReturnType.isNull() &&
6463 (Property->getType()->isIntegerType() ||
6464 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006465 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006466 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006467 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6468 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006469 if (ReturnType.isNull()) {
6470 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6471 Builder.AddTextChunk("BOOL");
6472 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6473 }
6474
6475 Builder.AddTypedTextChunk(
6476 Allocator.CopyString(SelectorId->getName()));
6477 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6478 CXCursor_ObjCInstanceMethodDecl));
6479 }
6480 }
6481
6482 // Add the normal mutator.
6483 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6484 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006485 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006486 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006487 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006488 if (ReturnType.isNull()) {
6489 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6490 Builder.AddTextChunk("void");
6491 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6492 }
6493
6494 Builder.AddTypedTextChunk(
6495 Allocator.CopyString(SelectorId->getName()));
6496 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006497 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6498 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006499 Builder.AddTextChunk(Key);
6500 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6501 CXCursor_ObjCInstanceMethodDecl));
6502 }
6503 }
6504
6505 // Indexed and unordered accessors
6506 unsigned IndexedGetterPriority = CCP_CodePattern;
6507 unsigned IndexedSetterPriority = CCP_CodePattern;
6508 unsigned UnorderedGetterPriority = CCP_CodePattern;
6509 unsigned UnorderedSetterPriority = CCP_CodePattern;
6510 if (const ObjCObjectPointerType *ObjCPointer
6511 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6512 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6513 // If this interface type is not provably derived from a known
6514 // collection, penalize the corresponding completions.
6515 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6516 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6517 if (!InheritsFromClassNamed(IFace, "NSArray"))
6518 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6519 }
6520
6521 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6522 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6523 if (!InheritsFromClassNamed(IFace, "NSSet"))
6524 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6525 }
6526 }
6527 } else {
6528 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6529 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6530 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6531 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6532 }
6533
6534 // Add -(NSUInteger)countOf<key>
6535 if (IsInstanceMethod &&
6536 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006537 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006538 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006539 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6540 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006541 if (ReturnType.isNull()) {
6542 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6543 Builder.AddTextChunk("NSUInteger");
6544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6545 }
6546
6547 Builder.AddTypedTextChunk(
6548 Allocator.CopyString(SelectorId->getName()));
6549 Results.AddResult(Result(Builder.TakeString(),
6550 std::min(IndexedGetterPriority,
6551 UnorderedGetterPriority),
6552 CXCursor_ObjCInstanceMethodDecl));
6553 }
6554 }
6555
6556 // Indexed getters
6557 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6558 if (IsInstanceMethod &&
6559 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006560 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006561 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006562 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006563 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006564 if (ReturnType.isNull()) {
6565 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6566 Builder.AddTextChunk("id");
6567 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6568 }
6569
6570 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6571 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6572 Builder.AddTextChunk("NSUInteger");
6573 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6574 Builder.AddTextChunk("index");
6575 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6576 CXCursor_ObjCInstanceMethodDecl));
6577 }
6578 }
6579
6580 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6581 if (IsInstanceMethod &&
6582 (ReturnType.isNull() ||
6583 (ReturnType->isObjCObjectPointerType() &&
6584 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6585 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6586 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006587 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006588 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006589 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006590 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006591 if (ReturnType.isNull()) {
6592 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6593 Builder.AddTextChunk("NSArray *");
6594 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6595 }
6596
6597 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6598 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6599 Builder.AddTextChunk("NSIndexSet *");
6600 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6601 Builder.AddTextChunk("indexes");
6602 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6603 CXCursor_ObjCInstanceMethodDecl));
6604 }
6605 }
6606
6607 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6608 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006609 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006610 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006611 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006612 &Context.Idents.get("range")
6613 };
6614
David Blaikie82e95a32014-11-19 07:49:47 +00006615 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006616 if (ReturnType.isNull()) {
6617 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6618 Builder.AddTextChunk("void");
6619 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6620 }
6621
6622 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6623 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6624 Builder.AddPlaceholderChunk("object-type");
6625 Builder.AddTextChunk(" **");
6626 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6627 Builder.AddTextChunk("buffer");
6628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6629 Builder.AddTypedTextChunk("range:");
6630 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6631 Builder.AddTextChunk("NSRange");
6632 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6633 Builder.AddTextChunk("inRange");
6634 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6635 CXCursor_ObjCInstanceMethodDecl));
6636 }
6637 }
6638
6639 // Mutable indexed accessors
6640
6641 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6642 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006643 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006644 IdentifierInfo *SelectorIds[2] = {
6645 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006646 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006647 };
6648
David Blaikie82e95a32014-11-19 07:49:47 +00006649 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006650 if (ReturnType.isNull()) {
6651 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6652 Builder.AddTextChunk("void");
6653 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6654 }
6655
6656 Builder.AddTypedTextChunk("insertObject:");
6657 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6658 Builder.AddPlaceholderChunk("object-type");
6659 Builder.AddTextChunk(" *");
6660 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6661 Builder.AddTextChunk("object");
6662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6663 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6664 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6665 Builder.AddPlaceholderChunk("NSUInteger");
6666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6667 Builder.AddTextChunk("index");
6668 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6669 CXCursor_ObjCInstanceMethodDecl));
6670 }
6671 }
6672
6673 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6674 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006675 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006676 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006677 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006678 &Context.Idents.get("atIndexes")
6679 };
6680
David Blaikie82e95a32014-11-19 07:49:47 +00006681 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006682 if (ReturnType.isNull()) {
6683 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6684 Builder.AddTextChunk("void");
6685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6686 }
6687
6688 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6689 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6690 Builder.AddTextChunk("NSArray *");
6691 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6692 Builder.AddTextChunk("array");
6693 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6694 Builder.AddTypedTextChunk("atIndexes:");
6695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6696 Builder.AddPlaceholderChunk("NSIndexSet *");
6697 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6698 Builder.AddTextChunk("indexes");
6699 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6700 CXCursor_ObjCInstanceMethodDecl));
6701 }
6702 }
6703
6704 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6705 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006706 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006707 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006708 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006709 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006710 if (ReturnType.isNull()) {
6711 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6712 Builder.AddTextChunk("void");
6713 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6714 }
6715
6716 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6717 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6718 Builder.AddTextChunk("NSUInteger");
6719 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6720 Builder.AddTextChunk("index");
6721 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6722 CXCursor_ObjCInstanceMethodDecl));
6723 }
6724 }
6725
6726 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6727 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006728 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006729 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006730 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006731 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006732 if (ReturnType.isNull()) {
6733 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6734 Builder.AddTextChunk("void");
6735 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6736 }
6737
6738 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6740 Builder.AddTextChunk("NSIndexSet *");
6741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6742 Builder.AddTextChunk("indexes");
6743 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6744 CXCursor_ObjCInstanceMethodDecl));
6745 }
6746 }
6747
6748 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6749 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006750 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006751 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006752 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006753 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006754 &Context.Idents.get("withObject")
6755 };
6756
David Blaikie82e95a32014-11-19 07:49:47 +00006757 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006758 if (ReturnType.isNull()) {
6759 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6760 Builder.AddTextChunk("void");
6761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6762 }
6763
6764 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6766 Builder.AddPlaceholderChunk("NSUInteger");
6767 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6768 Builder.AddTextChunk("index");
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddTypedTextChunk("withObject:");
6771 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6772 Builder.AddTextChunk("id");
6773 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6774 Builder.AddTextChunk("object");
6775 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6776 CXCursor_ObjCInstanceMethodDecl));
6777 }
6778 }
6779
6780 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6781 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006782 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006783 = (Twine("replace") + UpperKey + "AtIndexes").str();
6784 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006785 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006786 &Context.Idents.get(SelectorName1),
6787 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006788 };
6789
David Blaikie82e95a32014-11-19 07:49:47 +00006790 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006791 if (ReturnType.isNull()) {
6792 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6793 Builder.AddTextChunk("void");
6794 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6795 }
6796
6797 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6798 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6799 Builder.AddPlaceholderChunk("NSIndexSet *");
6800 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6801 Builder.AddTextChunk("indexes");
6802 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6803 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6804 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6805 Builder.AddTextChunk("NSArray *");
6806 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6807 Builder.AddTextChunk("array");
6808 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6809 CXCursor_ObjCInstanceMethodDecl));
6810 }
6811 }
6812
6813 // Unordered getters
6814 // - (NSEnumerator *)enumeratorOfKey
6815 if (IsInstanceMethod &&
6816 (ReturnType.isNull() ||
6817 (ReturnType->isObjCObjectPointerType() &&
6818 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6819 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6820 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006821 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006822 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006823 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6824 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006825 if (ReturnType.isNull()) {
6826 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6827 Builder.AddTextChunk("NSEnumerator *");
6828 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6829 }
6830
6831 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6832 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6833 CXCursor_ObjCInstanceMethodDecl));
6834 }
6835 }
6836
6837 // - (type *)memberOfKey:(type *)object
6838 if (IsInstanceMethod &&
6839 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006840 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006841 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006842 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006843 if (ReturnType.isNull()) {
6844 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6845 Builder.AddPlaceholderChunk("object-type");
6846 Builder.AddTextChunk(" *");
6847 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6848 }
6849
6850 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6851 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6852 if (ReturnType.isNull()) {
6853 Builder.AddPlaceholderChunk("object-type");
6854 Builder.AddTextChunk(" *");
6855 } else {
6856 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006857 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006858 Builder.getAllocator()));
6859 }
6860 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6861 Builder.AddTextChunk("object");
6862 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6863 CXCursor_ObjCInstanceMethodDecl));
6864 }
6865 }
6866
6867 // Mutable unordered accessors
6868 // - (void)addKeyObject:(type *)object
6869 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006870 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006871 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006872 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006873 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006874 if (ReturnType.isNull()) {
6875 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6876 Builder.AddTextChunk("void");
6877 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6878 }
6879
6880 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6882 Builder.AddPlaceholderChunk("object-type");
6883 Builder.AddTextChunk(" *");
6884 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6885 Builder.AddTextChunk("object");
6886 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6887 CXCursor_ObjCInstanceMethodDecl));
6888 }
6889 }
6890
6891 // - (void)addKey:(NSSet *)objects
6892 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006893 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006894 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006895 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006896 if (ReturnType.isNull()) {
6897 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6898 Builder.AddTextChunk("void");
6899 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6900 }
6901
6902 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6903 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6904 Builder.AddTextChunk("NSSet *");
6905 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6906 Builder.AddTextChunk("objects");
6907 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6908 CXCursor_ObjCInstanceMethodDecl));
6909 }
6910 }
6911
6912 // - (void)removeKeyObject:(type *)object
6913 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006914 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006915 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006916 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006917 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006918 if (ReturnType.isNull()) {
6919 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6920 Builder.AddTextChunk("void");
6921 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6922 }
6923
6924 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6926 Builder.AddPlaceholderChunk("object-type");
6927 Builder.AddTextChunk(" *");
6928 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6929 Builder.AddTextChunk("object");
6930 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6931 CXCursor_ObjCInstanceMethodDecl));
6932 }
6933 }
6934
6935 // - (void)removeKey:(NSSet *)objects
6936 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006937 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006938 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006939 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006940 if (ReturnType.isNull()) {
6941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942 Builder.AddTextChunk("void");
6943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 }
6945
6946 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6948 Builder.AddTextChunk("NSSet *");
6949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6950 Builder.AddTextChunk("objects");
6951 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6952 CXCursor_ObjCInstanceMethodDecl));
6953 }
6954 }
6955
6956 // - (void)intersectKey:(NSSet *)objects
6957 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006958 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006959 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006960 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006961 if (ReturnType.isNull()) {
6962 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6963 Builder.AddTextChunk("void");
6964 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6965 }
6966
6967 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6968 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6969 Builder.AddTextChunk("NSSet *");
6970 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6971 Builder.AddTextChunk("objects");
6972 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6973 CXCursor_ObjCInstanceMethodDecl));
6974 }
6975 }
6976
6977 // Key-Value Observing
6978 // + (NSSet *)keyPathsForValuesAffectingKey
6979 if (!IsInstanceMethod &&
6980 (ReturnType.isNull() ||
6981 (ReturnType->isObjCObjectPointerType() &&
6982 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6983 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6984 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006985 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006986 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006987 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006988 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6989 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006990 if (ReturnType.isNull()) {
6991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6992 Builder.AddTextChunk("NSSet *");
6993 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6994 }
6995
6996 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6997 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006998 CXCursor_ObjCClassMethodDecl));
6999 }
7000 }
7001
7002 // + (BOOL)automaticallyNotifiesObserversForKey
7003 if (!IsInstanceMethod &&
7004 (ReturnType.isNull() ||
7005 ReturnType->isIntegerType() ||
7006 ReturnType->isBooleanType())) {
7007 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007008 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007009 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007010 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7011 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007012 if (ReturnType.isNull()) {
7013 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7014 Builder.AddTextChunk("BOOL");
7015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7016 }
7017
7018 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7019 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7020 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007021 }
7022 }
7023}
7024
Douglas Gregor636a61e2010-04-07 00:21:17 +00007025void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7026 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007027 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007028 // Determine the return type of the method we're declaring, if
7029 // provided.
7030 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007031 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007032 if (CurContext->isObjCContainer()) {
7033 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7034 IDecl = cast<Decl>(OCD);
7035 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007036 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007037 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007038 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007039 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007040 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7041 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007042 IsInImplementation = true;
7043 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007044 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007045 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007046 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007047 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007048 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007049 }
7050
7051 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007052 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007053 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007054 }
7055
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007056 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007057 HandleCodeCompleteResults(this, CodeCompleter,
7058 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007059 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007060 return;
7061 }
7062
7063 // Find all of the methods that we could declare/implement here.
7064 KnownMethodsMap KnownMethods;
7065 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007066 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007067
Douglas Gregor636a61e2010-04-07 00:21:17 +00007068 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007069 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007070 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007071 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007072 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007073 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007074 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007075 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7076 MEnd = KnownMethods.end();
7077 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007078 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007079 CodeCompletionBuilder Builder(Results.getAllocator(),
7080 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007081
7082 // If the result type was not already provided, add it to the
7083 // pattern as (type).
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007084 if (ReturnType.isNull()) {
7085 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7086 AttributedType::stripOuterNullability(ResTy);
7087 AddObjCPassingTypeChunk(ResTy,
Alp Toker314cc812014-01-25 16:55:45 +00007088 Method->getObjCDeclQualifier(), Context, Policy,
7089 Builder);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007090 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007091
7092 Selector Sel = Method->getSelector();
7093
7094 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007095 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007096 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007097
7098 // Add parameters to the pattern.
7099 unsigned I = 0;
7100 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7101 PEnd = Method->param_end();
7102 P != PEnd; (void)++P, ++I) {
7103 // Add the part of the selector name.
7104 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007105 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007106 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007107 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7108 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007109 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007110 } else
7111 break;
7112
7113 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007114 QualType ParamType;
7115 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7116 ParamType = (*P)->getType();
7117 else
7118 ParamType = (*P)->getOriginalType();
Douglas Gregor9b7b3e92015-07-07 06:20:27 +00007119 ParamType = ParamType.substObjCTypeArgs(Context, {},
7120 ObjCSubstitutionContext::Parameter);
Argyrios Kyrtzidisf0917ab2015-07-24 17:00:19 +00007121 AttributedType::stripOuterNullability(ParamType);
Douglas Gregor86b42682015-06-19 18:27:52 +00007122 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007123 (*P)->getObjCDeclQualifier(),
7124 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007125 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007126
7127 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007128 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007129 }
7130
7131 if (Method->isVariadic()) {
7132 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007133 Builder.AddChunk(CodeCompletionString::CK_Comma);
7134 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007135 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007136
Douglas Gregord37c59d2010-05-28 00:57:46 +00007137 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007138 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007139 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7140 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7141 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007142 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007143 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007144 Builder.AddTextChunk("return");
7145 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7146 Builder.AddPlaceholderChunk("expression");
7147 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007148 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007149 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007150
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007151 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7152 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007153 }
7154
Douglas Gregor416b5752010-08-25 01:08:01 +00007155 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007156 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007157 Priority += CCD_InBaseClass;
7158
Douglas Gregor78254c82012-03-27 23:34:16 +00007159 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007160 }
7161
Douglas Gregor669a25a2011-02-17 00:22:45 +00007162 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7163 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007164 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007165 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007166 Containers.push_back(SearchDecl);
7167
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007168 VisitedSelectorSet KnownSelectors;
7169 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7170 MEnd = KnownMethods.end();
7171 M != MEnd; ++M)
7172 KnownSelectors.insert(M->first);
7173
7174
Douglas Gregor669a25a2011-02-17 00:22:45 +00007175 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7176 if (!IFace)
7177 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7178 IFace = Category->getClassInterface();
7179
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007180 if (IFace)
7181 for (auto *Cat : IFace->visible_categories())
7182 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007183
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007184 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Manman Rena7a8b1f2016-01-26 18:05:23 +00007185 for (auto *P : Containers[I]->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007186 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007187 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007188 }
7189
Douglas Gregor636a61e2010-04-07 00:21:17 +00007190 Results.ExitScope();
7191
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007192 HandleCodeCompleteResults(this, CodeCompleter,
7193 CodeCompletionContext::CCC_Other,
7194 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007195}
Douglas Gregor95887f92010-07-08 23:20:03 +00007196
7197void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7198 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007199 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007200 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007201 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007202 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007203 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007204 if (ExternalSource) {
7205 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7206 I != N; ++I) {
7207 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007208 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007209 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007210
7211 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007212 }
7213 }
7214
7215 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007216 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007217 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007218 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007219 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007220
7221 if (ReturnTy)
7222 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007223
Douglas Gregor95887f92010-07-08 23:20:03 +00007224 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007225 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7226 MEnd = MethodPool.end();
7227 M != MEnd; ++M) {
7228 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7229 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007230 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007231 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007232 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007233 continue;
7234
Douglas Gregor45879692010-07-08 23:37:41 +00007235 if (AtParameterName) {
7236 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007237 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007238 if (NumSelIdents &&
7239 NumSelIdents <= MethList->getMethod()->param_size()) {
7240 ParmVarDecl *Param =
7241 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007242 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007243 CodeCompletionBuilder Builder(Results.getAllocator(),
7244 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007245 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007246 Param->getIdentifier()->getName()));
7247 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007248 }
7249 }
7250
7251 continue;
7252 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007253
Nico Weber2e0c8f72014-12-27 03:58:08 +00007254 Result R(MethList->getMethod(),
7255 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007256 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007257 R.AllParametersAreInformative = false;
7258 R.DeclaringEntity = true;
7259 Results.MaybeAddResult(R, CurContext);
7260 }
7261 }
7262
7263 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007264 HandleCodeCompleteResults(this, CodeCompleter,
7265 CodeCompletionContext::CCC_Other,
7266 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007267}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007268
Douglas Gregorec00a262010-08-24 22:20:20 +00007269void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007270 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007271 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007272 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007273 Results.EnterNewScope();
7274
7275 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007276 CodeCompletionBuilder Builder(Results.getAllocator(),
7277 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007278 Builder.AddTypedTextChunk("if");
7279 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7280 Builder.AddPlaceholderChunk("condition");
7281 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007282
7283 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007284 Builder.AddTypedTextChunk("ifdef");
7285 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7286 Builder.AddPlaceholderChunk("macro");
7287 Results.AddResult(Builder.TakeString());
7288
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007289 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007290 Builder.AddTypedTextChunk("ifndef");
7291 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7292 Builder.AddPlaceholderChunk("macro");
7293 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007294
7295 if (InConditional) {
7296 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007297 Builder.AddTypedTextChunk("elif");
7298 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7299 Builder.AddPlaceholderChunk("condition");
7300 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007301
7302 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007303 Builder.AddTypedTextChunk("else");
7304 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007305
7306 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007307 Builder.AddTypedTextChunk("endif");
7308 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007309 }
7310
7311 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007312 Builder.AddTypedTextChunk("include");
7313 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7314 Builder.AddTextChunk("\"");
7315 Builder.AddPlaceholderChunk("header");
7316 Builder.AddTextChunk("\"");
7317 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007318
7319 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007320 Builder.AddTypedTextChunk("include");
7321 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7322 Builder.AddTextChunk("<");
7323 Builder.AddPlaceholderChunk("header");
7324 Builder.AddTextChunk(">");
7325 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007326
7327 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007328 Builder.AddTypedTextChunk("define");
7329 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7330 Builder.AddPlaceholderChunk("macro");
7331 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007332
7333 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007334 Builder.AddTypedTextChunk("define");
7335 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7336 Builder.AddPlaceholderChunk("macro");
7337 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7338 Builder.AddPlaceholderChunk("args");
7339 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7340 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007341
7342 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007343 Builder.AddTypedTextChunk("undef");
7344 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7345 Builder.AddPlaceholderChunk("macro");
7346 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007347
7348 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007349 Builder.AddTypedTextChunk("line");
7350 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7351 Builder.AddPlaceholderChunk("number");
7352 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007353
7354 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007355 Builder.AddTypedTextChunk("line");
7356 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7357 Builder.AddPlaceholderChunk("number");
7358 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7359 Builder.AddTextChunk("\"");
7360 Builder.AddPlaceholderChunk("filename");
7361 Builder.AddTextChunk("\"");
7362 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007363
7364 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007365 Builder.AddTypedTextChunk("error");
7366 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7367 Builder.AddPlaceholderChunk("message");
7368 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007369
7370 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007371 Builder.AddTypedTextChunk("pragma");
7372 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7373 Builder.AddPlaceholderChunk("arguments");
7374 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007375
David Blaikiebbafb8a2012-03-11 07:00:24 +00007376 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007377 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007378 Builder.AddTypedTextChunk("import");
7379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7380 Builder.AddTextChunk("\"");
7381 Builder.AddPlaceholderChunk("header");
7382 Builder.AddTextChunk("\"");
7383 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007384
7385 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007386 Builder.AddTypedTextChunk("import");
7387 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7388 Builder.AddTextChunk("<");
7389 Builder.AddPlaceholderChunk("header");
7390 Builder.AddTextChunk(">");
7391 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007392 }
7393
7394 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007395 Builder.AddTypedTextChunk("include_next");
7396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7397 Builder.AddTextChunk("\"");
7398 Builder.AddPlaceholderChunk("header");
7399 Builder.AddTextChunk("\"");
7400 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007401
7402 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007403 Builder.AddTypedTextChunk("include_next");
7404 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7405 Builder.AddTextChunk("<");
7406 Builder.AddPlaceholderChunk("header");
7407 Builder.AddTextChunk(">");
7408 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007409
7410 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007411 Builder.AddTypedTextChunk("warning");
7412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7413 Builder.AddPlaceholderChunk("message");
7414 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007415
7416 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7417 // completions for them. And __include_macros is a Clang-internal extension
7418 // that we don't want to encourage anyone to use.
7419
7420 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7421 Results.ExitScope();
7422
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007423 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007424 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007425 Results.data(), Results.size());
7426}
7427
7428void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007429 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007430 S->getFnParent()? Sema::PCC_RecoveryInFunction
7431 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007432}
7433
Douglas Gregorec00a262010-08-24 22:20:20 +00007434void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007435 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007436 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007437 IsDefinition? CodeCompletionContext::CCC_MacroName
7438 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007439 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7440 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007441 CodeCompletionBuilder Builder(Results.getAllocator(),
7442 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007443 Results.EnterNewScope();
7444 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7445 MEnd = PP.macro_end();
7446 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007447 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007448 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007449 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7450 CCP_CodePattern,
7451 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007452 }
7453 Results.ExitScope();
7454 } else if (IsDefinition) {
7455 // FIXME: Can we detect when the user just wrote an include guard above?
7456 }
7457
Douglas Gregor0ac41382010-09-23 23:01:17 +00007458 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007459 Results.data(), Results.size());
7460}
7461
Douglas Gregorec00a262010-08-24 22:20:20 +00007462void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007463 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007464 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007465 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007466
7467 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007468 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007469
7470 // defined (<macro>)
7471 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007472 CodeCompletionBuilder Builder(Results.getAllocator(),
7473 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007474 Builder.AddTypedTextChunk("defined");
7475 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7476 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7477 Builder.AddPlaceholderChunk("macro");
7478 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7479 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007480 Results.ExitScope();
7481
7482 HandleCodeCompleteResults(this, CodeCompleter,
7483 CodeCompletionContext::CCC_PreprocessorExpression,
7484 Results.data(), Results.size());
7485}
7486
7487void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7488 IdentifierInfo *Macro,
7489 MacroInfo *MacroInfo,
7490 unsigned Argument) {
7491 // FIXME: In the future, we could provide "overload" results, much like we
7492 // do for function calls.
7493
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007494 // Now just ignore this. There will be another code-completion callback
7495 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007496}
7497
Douglas Gregor11583702010-08-25 17:04:25 +00007498void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007499 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007500 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007501 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007502}
7503
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007504void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007505 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007506 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007507 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7508 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007509 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7510 CodeCompletionDeclConsumer Consumer(Builder,
7511 Context.getTranslationUnitDecl());
7512 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7513 Consumer);
7514 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007515
7516 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007517 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007518
7519 Results.clear();
7520 Results.insert(Results.end(),
7521 Builder.data(), Builder.data() + Builder.size());
7522}