blob: 7d898d8ac1a20938d2a99f0c1ee8f0c753fcdc77 [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
Douglas Gregor7c208612010-01-14 00:20:49 +0000497 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000498
499 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000500 if (!ND->getDeclName())
501 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000502
503 // Friend declarations and declarations introduced due to friends are never
504 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000505 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000506 return false;
507
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000508 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000509 if (isa<ClassTemplateSpecializationDecl>(ND) ||
510 isa<ClassTemplatePartialSpecializationDecl>(ND))
511 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000512
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000513 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000514 if (isa<UsingDecl>(ND))
515 return false;
516
517 // Some declarations have reserved names that we don't want to ever show.
Alp Toker034bbd52014-06-30 01:33:53 +0000518 // Filter out names reserved for the implementation if they come from a
519 // system header.
520 // TODO: Add a predicate for this.
521 if (const IdentifierInfo *Id = ND->getIdentifier())
522 if (isReservedName(Id) &&
523 (ND->getLocation().isInvalid() ||
524 SemaRef.SourceMgr.isInSystemHeader(
525 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregor7c208612010-01-14 00:20:49 +0000526 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000527
Douglas Gregor59cab552010-08-16 23:05:20 +0000528 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
529 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
530 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000531 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000532 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000533 AsNestedNameSpecifier = true;
534
Douglas Gregor3545ff42009-09-21 16:56:56 +0000535 // Filter out any unwanted results.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000536 if (Filter && !(this->*Filter)(ND)) {
537 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000538 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000539 IsNestedNameSpecifier(ND) &&
540 (Filter != &ResultBuilder::IsMember ||
541 (isa<CXXRecordDecl>(ND) &&
542 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
543 AsNestedNameSpecifier = true;
544 return true;
545 }
546
Douglas Gregor7c208612010-01-14 00:20:49 +0000547 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000548 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000549 // ... then it must be interesting!
550 return true;
551}
552
Douglas Gregore0717ab2010-01-14 00:41:07 +0000553bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000554 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000555 // In C, there is no way to refer to a hidden name.
556 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
557 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000558 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000559 return true;
560
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000561 const DeclContext *HiddenCtx =
562 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000563
564 // There is no way to qualify a name declared in a function or method.
565 if (HiddenCtx->isFunctionOrMethod())
566 return true;
567
Sebastian Redl50c68252010-08-31 00:36:30 +0000568 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000569 return true;
570
571 // We can refer to the result with the appropriate qualification. Do it.
572 R.Hidden = true;
573 R.QualifierIsInformative = false;
574
575 if (!R.Qualifier)
576 R.Qualifier = getRequiredQualification(SemaRef.Context,
577 CurContext,
578 R.Declaration->getDeclContext());
579 return false;
580}
581
Douglas Gregor95887f92010-07-08 23:20:03 +0000582/// \brief A simplified classification of types used to determine whether two
583/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000584SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000585 switch (T->getTypeClass()) {
586 case Type::Builtin:
587 switch (cast<BuiltinType>(T)->getKind()) {
588 case BuiltinType::Void:
589 return STC_Void;
590
591 case BuiltinType::NullPtr:
592 return STC_Pointer;
593
594 case BuiltinType::Overload:
595 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000596 return STC_Other;
597
598 case BuiltinType::ObjCId:
599 case BuiltinType::ObjCClass:
600 case BuiltinType::ObjCSel:
601 return STC_ObjectiveC;
602
603 default:
604 return STC_Arithmetic;
605 }
David Blaikie8a40f702012-01-17 06:56:22 +0000606
Douglas Gregor95887f92010-07-08 23:20:03 +0000607 case Type::Complex:
608 return STC_Arithmetic;
609
610 case Type::Pointer:
611 return STC_Pointer;
612
613 case Type::BlockPointer:
614 return STC_Block;
615
616 case Type::LValueReference:
617 case Type::RValueReference:
618 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return STC_Array;
625
626 case Type::DependentSizedExtVector:
627 case Type::Vector:
628 case Type::ExtVector:
629 return STC_Arithmetic;
630
631 case Type::FunctionProto:
632 case Type::FunctionNoProto:
633 return STC_Function;
634
635 case Type::Record:
636 return STC_Record;
637
638 case Type::Enum:
639 return STC_Arithmetic;
640
641 case Type::ObjCObject:
642 case Type::ObjCInterface:
643 case Type::ObjCObjectPointer:
644 return STC_ObjectiveC;
645
646 default:
647 return STC_Other;
648 }
649}
650
651/// \brief Get the type that a given expression will have if this declaration
652/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000653QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000654 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
655
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000656 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000657 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000658 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000659 return C.getObjCInterfaceType(Iface);
660
661 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000662 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000663 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000664 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000665 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000666 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000667 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000668 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000669 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000670 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000671 T = Value->getType();
672 else
673 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000674
675 // Dig through references, function pointers, and block pointers to
676 // get down to the likely type of an expression when the entity is
677 // used.
678 do {
679 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
680 T = Ref->getPointeeType();
681 continue;
682 }
683
684 if (const PointerType *Pointer = T->getAs<PointerType>()) {
685 if (Pointer->getPointeeType()->isFunctionType()) {
686 T = Pointer->getPointeeType();
687 continue;
688 }
689
690 break;
691 }
692
693 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
694 T = Block->getPointeeType();
695 continue;
696 }
697
698 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000699 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000700 continue;
701 }
702
703 break;
704 } while (true);
705
706 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000707}
708
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000709unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
710 if (!ND)
711 return CCP_Unlikely;
712
713 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000714 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
715 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000716 // _cmd is relatively rare
717 if (const ImplicitParamDecl *ImplicitParam =
718 dyn_cast<ImplicitParamDecl>(ND))
719 if (ImplicitParam->getIdentifier() &&
720 ImplicitParam->getIdentifier()->isStr("_cmd"))
721 return CCP_ObjC_cmd;
722
723 return CCP_LocalDeclaration;
724 }
Richard Smith541b38b2013-09-20 01:15:31 +0000725
726 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000727 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
728 return CCP_MemberDeclaration;
729
730 // Content-based decisions.
731 if (isa<EnumConstantDecl>(ND))
732 return CCP_Constant;
733
Douglas Gregor52e0de42013-01-31 05:03:46 +0000734 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
735 // message receiver, or parenthesized expression context. There, it's as
736 // likely that the user will want to write a type as other declarations.
737 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
738 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
739 CompletionContext.getKind()
740 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
741 CompletionContext.getKind()
742 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000743 return CCP_Type;
744
745 return CCP_Declaration;
746}
747
Douglas Gregor50832e02010-09-20 22:39:41 +0000748void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
749 // If this is an Objective-C method declaration whose selector matches our
750 // preferred selector, give it a priority boost.
751 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000752 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000753 if (PreferredSelector == Method->getSelector())
754 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000755
Douglas Gregor50832e02010-09-20 22:39:41 +0000756 // If we have a preferred type, adjust the priority for results with exactly-
757 // matching or nearly-matching types.
758 if (!PreferredType.isNull()) {
759 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
760 if (!T.isNull()) {
761 CanQualType TC = SemaRef.Context.getCanonicalType(T);
762 // Check for exactly-matching types (modulo qualifiers).
763 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
764 R.Priority /= CCF_ExactTypeMatch;
765 // Check for nearly-matching types, based on classification of each.
766 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000767 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000768 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
769 R.Priority /= CCF_SimilarTypeMatch;
770 }
771 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000772}
773
Douglas Gregor0212fd72010-09-21 16:06:22 +0000774void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000776 !CompletionContext.wantConstructorResults())
777 return;
778
779 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000780 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000782 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000783 Record = ClassTemplate->getTemplatedDecl();
784 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
785 // Skip specializations and partial specializations.
786 if (isa<ClassTemplateSpecializationDecl>(Record))
787 return;
788 } else {
789 // There are no constructors here.
790 return;
791 }
792
793 Record = Record->getDefinition();
794 if (!Record)
795 return;
796
797
798 QualType RecordTy = Context.getTypeDeclType(Record);
799 DeclarationName ConstructorName
800 = Context.DeclarationNames.getCXXConstructorName(
801 Context.getCanonicalType(RecordTy));
Richard Smithcf4bdde2015-02-21 02:45:19 +0000802 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
803 for (DeclContext::lookup_iterator I = Ctors.begin(),
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000804 E = Ctors.end();
805 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000806 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000807 R.CursorKind = getCursorKindForDecl(R.Declaration);
808 Results.push_back(R);
809 }
810}
811
Douglas Gregor7c208612010-01-14 00:20:49 +0000812void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
813 assert(!ShadowMaps.empty() && "Must enter into a results scope");
814
815 if (R.Kind != Result::RK_Declaration) {
816 // For non-declaration results, just add the result.
817 Results.push_back(R);
818 return;
819 }
820
821 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000822 if (const UsingShadowDecl *Using =
823 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000824 MaybeAddResult(Result(Using->getTargetDecl(),
825 getBasePriority(Using->getTargetDecl()),
826 R.Qualifier),
827 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000828 return;
829 }
830
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000831 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000832 unsigned IDNS = CanonDecl->getIdentifierNamespace();
833
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000834 bool AsNestedNameSpecifier = false;
835 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000836 return;
837
Douglas Gregor0212fd72010-09-21 16:06:22 +0000838 // C++ constructors are never found by name lookup.
839 if (isa<CXXConstructorDecl>(R.Declaration))
840 return;
841
Douglas Gregor3545ff42009-09-21 16:56:56 +0000842 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000843 ShadowMapEntry::iterator I, IEnd;
844 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
845 if (NamePos != SMap.end()) {
846 I = NamePos->second.begin();
847 IEnd = NamePos->second.end();
848 }
849
850 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000851 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000852 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000853 if (ND->getCanonicalDecl() == CanonDecl) {
854 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000855 Results[Index].Declaration = R.Declaration;
856
Douglas Gregor3545ff42009-09-21 16:56:56 +0000857 // We're done.
858 return;
859 }
860 }
861
862 // This is a new declaration in this scope. However, check whether this
863 // declaration name is hidden by a similarly-named declaration in an outer
864 // scope.
865 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
866 --SMEnd;
867 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000868 ShadowMapEntry::iterator I, IEnd;
869 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
870 if (NamePos != SM->end()) {
871 I = NamePos->second.begin();
872 IEnd = NamePos->second.end();
873 }
874 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000875 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000876 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000877 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
878 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000879 continue;
880
881 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000882 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000883 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000884 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000885 continue;
886
887 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000888 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000889 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000890
891 break;
892 }
893 }
894
895 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000896 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000897 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000898
Douglas Gregore412a5a2009-09-23 22:26:46 +0000899 // If the filter is for nested-name-specifiers, then this result starts a
900 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000901 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000902 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000903 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000904 } else
905 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000906
Douglas Gregor5bf52692009-09-22 23:15:58 +0000907 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000908 if (R.QualifierIsInformative && !R.Qualifier &&
909 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000910 const DeclContext *Ctx = R.Declaration->getDeclContext();
911 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
913 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000914 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000915 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
916 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000917 else
918 R.QualifierIsInformative = false;
919 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000920
Douglas Gregor3545ff42009-09-21 16:56:56 +0000921 // Insert this result into the set of results and into the current shadow
922 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000923 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000924 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000925
926 if (!AsNestedNameSpecifier)
927 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000928}
929
Douglas Gregorc580c522010-01-14 01:09:38 +0000930void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000931 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000932 if (R.Kind != Result::RK_Declaration) {
933 // For non-declaration results, just add the result.
934 Results.push_back(R);
935 return;
936 }
937
Douglas Gregorc580c522010-01-14 01:09:38 +0000938 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000939 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000940 AddResult(Result(Using->getTargetDecl(),
941 getBasePriority(Using->getTargetDecl()),
942 R.Qualifier),
943 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000944 return;
945 }
946
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000947 bool AsNestedNameSpecifier = false;
948 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000949 return;
950
Douglas Gregor0212fd72010-09-21 16:06:22 +0000951 // C++ constructors are never found by name lookup.
952 if (isa<CXXConstructorDecl>(R.Declaration))
953 return;
954
Douglas Gregorc580c522010-01-14 01:09:38 +0000955 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
956 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000957
Douglas Gregorc580c522010-01-14 01:09:38 +0000958 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000959 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000960 return;
961
962 // If the filter is for nested-name-specifiers, then this result starts a
963 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000964 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000965 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000966 R.Priority = CCP_NestedNameSpecifier;
967 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000968 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
969 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000970 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000971 R.QualifierIsInformative = true;
972
Douglas Gregorc580c522010-01-14 01:09:38 +0000973 // If this result is supposed to have an informative qualifier, add one.
974 if (R.QualifierIsInformative && !R.Qualifier &&
975 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000976 const DeclContext *Ctx = R.Declaration->getDeclContext();
977 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000978 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
979 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000980 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000981 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000982 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000983 else
984 R.QualifierIsInformative = false;
985 }
986
Douglas Gregora2db7932010-05-26 22:00:08 +0000987 // Adjust the priority if this result comes from a base class.
988 if (InBaseClass)
989 R.Priority += CCD_InBaseClass;
990
Douglas Gregor50832e02010-09-20 22:39:41 +0000991 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000992
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000993 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000994 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000995 if (Method->isInstance()) {
996 Qualifiers MethodQuals
997 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
998 if (ObjectTypeQualifiers == MethodQuals)
999 R.Priority += CCD_ObjectQualifierMatch;
1000 else if (ObjectTypeQualifiers - MethodQuals) {
1001 // The method cannot be invoked, because doing so would drop
1002 // qualifiers.
1003 return;
1004 }
1005 }
1006
Douglas Gregorc580c522010-01-14 01:09:38 +00001007 // Insert this result into the set of results.
1008 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001009
1010 if (!AsNestedNameSpecifier)
1011 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001012}
1013
Douglas Gregor78a21012010-01-14 16:01:26 +00001014void ResultBuilder::AddResult(Result R) {
1015 assert(R.Kind != Result::RK_Declaration &&
1016 "Declaration results need more context");
1017 Results.push_back(R);
1018}
1019
Douglas Gregor3545ff42009-09-21 16:56:56 +00001020/// \brief Enter into a new scope.
Benjamin Kramer3204b152015-05-29 19:42:19 +00001021void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001022
1023/// \brief Exit from the current scope.
1024void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001025 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1026 EEnd = ShadowMaps.back().end();
1027 E != EEnd;
1028 ++E)
1029 E->second.Destroy();
1030
Douglas Gregor3545ff42009-09-21 16:56:56 +00001031 ShadowMaps.pop_back();
1032}
1033
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001034/// \brief Determines whether this given declaration will be found by
1035/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001036bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001037 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1038
Richard Smith541b38b2013-09-20 01:15:31 +00001039 // If name lookup finds a local extern declaration, then we are in a
1040 // context where it behaves like an ordinary name.
1041 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001042 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001043 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001044 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001045 if (isa<ObjCIvarDecl>(ND))
1046 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001047 }
1048
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001049 return ND->getIdentifierNamespace() & IDNS;
1050}
1051
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001052/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001053/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001054bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001055 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1056 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1057 return false;
1058
Richard Smith541b38b2013-09-20 01:15:31 +00001059 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001061 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001062 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001063 if (isa<ObjCIvarDecl>(ND))
1064 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001065 }
1066
Douglas Gregor70febae2010-05-28 00:49:12 +00001067 return ND->getIdentifierNamespace() & IDNS;
1068}
1069
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001070bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001071 if (!IsOrdinaryNonTypeName(ND))
1072 return 0;
1073
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001074 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001075 if (VD->getType()->isIntegralOrEnumerationType())
1076 return true;
1077
1078 return false;
1079}
1080
Douglas Gregor70febae2010-05-28 00:49:12 +00001081/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001082/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001083bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001084 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1085
Richard Smith541b38b2013-09-20 01:15:31 +00001086 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001087 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001088 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001089
1090 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001091 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1092 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001093}
1094
Douglas Gregor3545ff42009-09-21 16:56:56 +00001095/// \brief Determines whether the given declaration is suitable as the
1096/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001097bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001098 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001099 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100 ND = ClassTemplate->getTemplatedDecl();
1101
1102 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1103}
1104
1105/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001106bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001107 return isa<EnumDecl>(ND);
1108}
1109
1110/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001111bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001112 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001113 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001114 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001115
1116 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001117 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001118 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001119 RD->getTagKind() == TTK_Struct ||
1120 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001121
1122 return false;
1123}
1124
1125/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001126bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001127 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001128 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001129 ND = ClassTemplate->getTemplatedDecl();
1130
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001131 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001132 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001133
1134 return false;
1135}
1136
1137/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001138bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001139 return isa<NamespaceDecl>(ND);
1140}
1141
1142/// \brief Determines whether the given declaration is a namespace or
1143/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001144bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001145 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1146}
1147
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001148/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001149bool ResultBuilder::IsType(const NamedDecl *ND) const {
1150 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fa2642010-08-24 01:06:58 +00001151 ND = Using->getTargetDecl();
1152
1153 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001154}
1155
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001156/// \brief Determines which members of a class should be visible via
1157/// "." or "->". Only value declarations, nested name specifiers, and
1158/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001159bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1160 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001161 ND = Using->getTargetDecl();
1162
Douglas Gregor70788392009-12-11 18:14:22 +00001163 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1164 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001165}
1166
Douglas Gregora817a192010-05-27 23:06:34 +00001167static bool isObjCReceiverType(ASTContext &C, QualType T) {
1168 T = C.getCanonicalType(T);
1169 switch (T->getTypeClass()) {
1170 case Type::ObjCObject:
1171 case Type::ObjCInterface:
1172 case Type::ObjCObjectPointer:
1173 return true;
1174
1175 case Type::Builtin:
1176 switch (cast<BuiltinType>(T)->getKind()) {
1177 case BuiltinType::ObjCId:
1178 case BuiltinType::ObjCClass:
1179 case BuiltinType::ObjCSel:
1180 return true;
1181
1182 default:
1183 break;
1184 }
1185 return false;
1186
1187 default:
1188 break;
1189 }
1190
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001192 return false;
1193
1194 // FIXME: We could perform more analysis here to determine whether a
1195 // particular class type has any conversions to Objective-C types. For now,
1196 // just accept all class types.
1197 return T->isDependentType() || T->isRecordType();
1198}
1199
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001200bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001201 QualType T = getDeclUsageType(SemaRef.Context, ND);
1202 if (T.isNull())
1203 return false;
1204
1205 T = SemaRef.Context.getBaseElementType(T);
1206 return isObjCReceiverType(SemaRef.Context, T);
1207}
1208
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001209bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001210 if (IsObjCMessageReceiver(ND))
1211 return true;
1212
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001213 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001214 if (!Var)
1215 return false;
1216
1217 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1218}
1219
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001220bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001221 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1222 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001223 return false;
1224
1225 QualType T = getDeclUsageType(SemaRef.Context, ND);
1226 if (T.isNull())
1227 return false;
1228
1229 T = SemaRef.Context.getBaseElementType(T);
1230 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1231 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001232 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001233}
Douglas Gregora817a192010-05-27 23:06:34 +00001234
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001235bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001236 return false;
1237}
1238
James Dennettf1243872012-06-17 05:33:25 +00001239/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001240/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001241bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001242 return isa<ObjCIvarDecl>(ND);
1243}
1244
Douglas Gregorc580c522010-01-14 01:09:38 +00001245namespace {
1246 /// \brief Visible declaration consumer that adds a code-completion result
1247 /// for each visible declaration.
1248 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1249 ResultBuilder &Results;
1250 DeclContext *CurContext;
1251
1252 public:
1253 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1254 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001255
1256 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1257 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001258 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001259 if (Ctx)
1260 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001261
1262 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1263 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001264 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001265 }
1266 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001267}
Douglas Gregorc580c522010-01-14 01:09:38 +00001268
Douglas Gregor3545ff42009-09-21 16:56:56 +00001269/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001270static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001271 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001272 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001273 Results.AddResult(Result("short", CCP_Type));
1274 Results.AddResult(Result("long", CCP_Type));
1275 Results.AddResult(Result("signed", CCP_Type));
1276 Results.AddResult(Result("unsigned", CCP_Type));
1277 Results.AddResult(Result("void", CCP_Type));
1278 Results.AddResult(Result("char", CCP_Type));
1279 Results.AddResult(Result("int", CCP_Type));
1280 Results.AddResult(Result("float", CCP_Type));
1281 Results.AddResult(Result("double", CCP_Type));
1282 Results.AddResult(Result("enum", CCP_Type));
1283 Results.AddResult(Result("struct", CCP_Type));
1284 Results.AddResult(Result("union", CCP_Type));
1285 Results.AddResult(Result("const", CCP_Type));
1286 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001287
Douglas Gregor3545ff42009-09-21 16:56:56 +00001288 if (LangOpts.C99) {
1289 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001290 Results.AddResult(Result("_Complex", CCP_Type));
1291 Results.AddResult(Result("_Imaginary", CCP_Type));
1292 Results.AddResult(Result("_Bool", CCP_Type));
1293 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001294 }
1295
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001296 CodeCompletionBuilder Builder(Results.getAllocator(),
1297 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001298 if (LangOpts.CPlusPlus) {
1299 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001300 Results.AddResult(Result("bool", CCP_Type +
1301 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001302 Results.AddResult(Result("class", CCP_Type));
1303 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001304
Douglas Gregorf4c33342010-05-28 00:22:41 +00001305 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001306 Builder.AddTypedTextChunk("typename");
1307 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1308 Builder.AddPlaceholderChunk("qualifier");
1309 Builder.AddTextChunk("::");
1310 Builder.AddPlaceholderChunk("name");
1311 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001312
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001313 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001314 Results.AddResult(Result("auto", CCP_Type));
1315 Results.AddResult(Result("char16_t", CCP_Type));
1316 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001317
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001318 Builder.AddTypedTextChunk("decltype");
1319 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1320 Builder.AddPlaceholderChunk("expression");
1321 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1322 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001323 }
1324 }
1325
1326 // GNU extensions
1327 if (LangOpts.GNUMode) {
1328 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001329 // Results.AddResult(Result("_Decimal32"));
1330 // Results.AddResult(Result("_Decimal64"));
1331 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001332
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001333 Builder.AddTypedTextChunk("typeof");
1334 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1335 Builder.AddPlaceholderChunk("expression");
1336 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001337
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001338 Builder.AddTypedTextChunk("typeof");
1339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1340 Builder.AddPlaceholderChunk("type");
1341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1342 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001343 }
Douglas Gregor86b42682015-06-19 18:27:52 +00001344
1345 // Nullability
Douglas Gregoraea7afd2015-06-24 22:02:08 +00001346 Results.AddResult(Result("_Nonnull", CCP_Type));
1347 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1348 Results.AddResult(Result("_Nullable", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001349}
1350
John McCallfaf5fb42010-08-26 23:41:50 +00001351static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001352 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001353 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001354 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001355 // Note: we don't suggest either "auto" or "register", because both
1356 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1357 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001358 Results.AddResult(Result("extern"));
1359 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360}
1361
John McCallfaf5fb42010-08-26 23:41:50 +00001362static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001363 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001364 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001365 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001367 case Sema::PCC_Class:
1368 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001369 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001370 Results.AddResult(Result("explicit"));
1371 Results.AddResult(Result("friend"));
1372 Results.AddResult(Result("mutable"));
1373 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001374 }
1375 // Fall through
1376
John McCallfaf5fb42010-08-26 23:41:50 +00001377 case Sema::PCC_ObjCInterface:
1378 case Sema::PCC_ObjCImplementation:
1379 case Sema::PCC_Namespace:
1380 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001381 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001382 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001383 break;
1384
John McCallfaf5fb42010-08-26 23:41:50 +00001385 case Sema::PCC_ObjCInstanceVariableList:
1386 case Sema::PCC_Expression:
1387 case Sema::PCC_Statement:
1388 case Sema::PCC_ForInit:
1389 case Sema::PCC_Condition:
1390 case Sema::PCC_RecoveryInFunction:
1391 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001392 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001393 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001394 break;
1395 }
1396}
1397
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001398static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1399static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1400static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001401 ResultBuilder &Results,
1402 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001403static void AddObjCImplementationResults(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 AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001407 ResultBuilder &Results,
1408 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001409static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001410
Douglas Gregorf4c33342010-05-28 00:22:41 +00001411static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001412 CodeCompletionBuilder Builder(Results.getAllocator(),
1413 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001414 Builder.AddTypedTextChunk("typedef");
1415 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1416 Builder.AddPlaceholderChunk("type");
1417 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1418 Builder.AddPlaceholderChunk("name");
1419 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001420}
1421
John McCallfaf5fb42010-08-26 23:41:50 +00001422static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001423 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001424 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001425 case Sema::PCC_Namespace:
1426 case Sema::PCC_Class:
1427 case Sema::PCC_ObjCInstanceVariableList:
1428 case Sema::PCC_Template:
1429 case Sema::PCC_MemberTemplate:
1430 case Sema::PCC_Statement:
1431 case Sema::PCC_RecoveryInFunction:
1432 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001433 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001434 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001435 return true;
1436
John McCallfaf5fb42010-08-26 23:41:50 +00001437 case Sema::PCC_Expression:
1438 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001439 return LangOpts.CPlusPlus;
1440
1441 case Sema::PCC_ObjCInterface:
1442 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001443 return false;
1444
John McCallfaf5fb42010-08-26 23:41:50 +00001445 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001446 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001447 }
David Blaikie8a40f702012-01-17 06:56:22 +00001448
1449 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001450}
1451
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001452static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1453 const Preprocessor &PP) {
1454 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001455 Policy.AnonymousTagLocations = false;
1456 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001457 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001458 return Policy;
1459}
1460
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001461/// \brief Retrieve a printing policy suitable for code completion.
1462static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1463 return getCompletionPrintingPolicy(S.Context, S.PP);
1464}
1465
Douglas Gregore5c79d52011-10-18 21:20:17 +00001466/// \brief Retrieve the string representation of the given type as a string
1467/// that has the appropriate lifetime for code completion.
1468///
1469/// This routine provides a fast path where we provide constant strings for
1470/// common type names.
1471static const char *GetCompletionTypeString(QualType T,
1472 ASTContext &Context,
1473 const PrintingPolicy &Policy,
1474 CodeCompletionAllocator &Allocator) {
1475 if (!T.getLocalQualifiers()) {
1476 // Built-in type names are constant strings.
1477 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001478 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001479
1480 // Anonymous tag types are constant strings.
1481 if (const TagType *TagT = dyn_cast<TagType>(T))
1482 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001483 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001484 switch (Tag->getTagKind()) {
1485 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001486 case TTK_Interface: return "__interface <anonymous>";
1487 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001488 case TTK_Union: return "union <anonymous>";
1489 case TTK_Enum: return "enum <anonymous>";
1490 }
1491 }
1492 }
1493
1494 // Slow path: format the type as a string.
1495 std::string Result;
1496 T.getAsStringInternal(Result, Policy);
1497 return Allocator.CopyString(Result);
1498}
1499
Douglas Gregord8c61782012-02-15 15:34:24 +00001500/// \brief Add a completion for "this", if we're in a member function.
1501static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1502 QualType ThisTy = S.getCurrentThisType();
1503 if (ThisTy.isNull())
1504 return;
1505
1506 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001507 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001508 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1509 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1510 S.Context,
1511 Policy,
1512 Allocator));
1513 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001514 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001515}
1516
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001517/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001518static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001519 Scope *S,
1520 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001521 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001522 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001523 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregore5c79d52011-10-18 21:20:17 +00001524 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001525
John McCall276321a2010-08-25 06:19:51 +00001526 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001527 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001528 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001529 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001530 if (Results.includeCodePatterns()) {
1531 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001532 Builder.AddTypedTextChunk("namespace");
1533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1534 Builder.AddPlaceholderChunk("identifier");
1535 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1536 Builder.AddPlaceholderChunk("declarations");
1537 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1538 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1539 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001540 }
1541
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001542 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001543 Builder.AddTypedTextChunk("namespace");
1544 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1545 Builder.AddPlaceholderChunk("name");
1546 Builder.AddChunk(CodeCompletionString::CK_Equal);
1547 Builder.AddPlaceholderChunk("namespace");
1548 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001549
1550 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001551 Builder.AddTypedTextChunk("using");
1552 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1553 Builder.AddTextChunk("namespace");
1554 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1555 Builder.AddPlaceholderChunk("identifier");
1556 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001557
1558 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001559 Builder.AddTypedTextChunk("asm");
1560 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1561 Builder.AddPlaceholderChunk("string-literal");
1562 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1563 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001564
Douglas Gregorf4c33342010-05-28 00:22:41 +00001565 if (Results.includeCodePatterns()) {
1566 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001567 Builder.AddTypedTextChunk("template");
1568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1569 Builder.AddPlaceholderChunk("declaration");
1570 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001571 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001572 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001573
David Blaikiebbafb8a2012-03-11 07:00:24 +00001574 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001575 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001576
Douglas Gregorf4c33342010-05-28 00:22:41 +00001577 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001578 // Fall through
1579
John McCallfaf5fb42010-08-26 23:41:50 +00001580 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001581 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001582 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001583 Builder.AddTypedTextChunk("using");
1584 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1585 Builder.AddPlaceholderChunk("qualifier");
1586 Builder.AddTextChunk("::");
1587 Builder.AddPlaceholderChunk("name");
1588 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001589
Douglas Gregorf4c33342010-05-28 00:22:41 +00001590 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001591 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001592 Builder.AddTypedTextChunk("using");
1593 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1594 Builder.AddTextChunk("typename");
1595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1596 Builder.AddPlaceholderChunk("qualifier");
1597 Builder.AddTextChunk("::");
1598 Builder.AddPlaceholderChunk("name");
1599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001600 }
1601
John McCallfaf5fb42010-08-26 23:41:50 +00001602 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001603 AddTypedefResult(Results);
1604
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001605 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001606 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001607 if (Results.includeCodePatterns())
1608 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001609 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001610
1611 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001612 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001613 if (Results.includeCodePatterns())
1614 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001615 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001616
1617 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001618 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001619 if (Results.includeCodePatterns())
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001621 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001622 }
1623 }
1624 // Fall through
1625
John McCallfaf5fb42010-08-26 23:41:50 +00001626 case Sema::PCC_Template:
1627 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001628 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001629 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001630 Builder.AddTypedTextChunk("template");
1631 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1632 Builder.AddPlaceholderChunk("parameters");
1633 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1634 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001635 }
1636
David Blaikiebbafb8a2012-03-11 07:00:24 +00001637 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1638 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001639 break;
1640
John McCallfaf5fb42010-08-26 23:41:50 +00001641 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001642 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1643 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1644 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001645 break;
1646
John McCallfaf5fb42010-08-26 23:41:50 +00001647 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1649 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1650 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001651 break;
1652
John McCallfaf5fb42010-08-26 23:41:50 +00001653 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001654 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001655 break;
1656
John McCallfaf5fb42010-08-26 23:41:50 +00001657 case Sema::PCC_RecoveryInFunction:
1658 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001659 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001660
David Blaikiebbafb8a2012-03-11 07:00:24 +00001661 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1662 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001663 Builder.AddTypedTextChunk("try");
1664 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1665 Builder.AddPlaceholderChunk("statements");
1666 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1667 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1668 Builder.AddTextChunk("catch");
1669 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1670 Builder.AddPlaceholderChunk("declaration");
1671 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1672 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1673 Builder.AddPlaceholderChunk("statements");
1674 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1675 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1676 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001677 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001678 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001679 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001680
Douglas Gregorf64acca2010-05-25 21:41:55 +00001681 if (Results.includeCodePatterns()) {
1682 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddTypedTextChunk("if");
1684 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001685 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001686 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001687 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001688 Builder.AddPlaceholderChunk("expression");
1689 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1690 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1691 Builder.AddPlaceholderChunk("statements");
1692 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1693 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1694 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001695
Douglas Gregorf64acca2010-05-25 21:41:55 +00001696 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001697 Builder.AddTypedTextChunk("switch");
1698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001699 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001700 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001701 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001702 Builder.AddPlaceholderChunk("expression");
1703 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1704 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1705 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1706 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1707 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001708 }
1709
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001710 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001711 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001712 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001713 Builder.AddTypedTextChunk("case");
1714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1715 Builder.AddPlaceholderChunk("expression");
1716 Builder.AddChunk(CodeCompletionString::CK_Colon);
1717 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001718
1719 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001720 Builder.AddTypedTextChunk("default");
1721 Builder.AddChunk(CodeCompletionString::CK_Colon);
1722 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001723 }
1724
Douglas Gregorf64acca2010-05-25 21:41:55 +00001725 if (Results.includeCodePatterns()) {
1726 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001727 Builder.AddTypedTextChunk("while");
1728 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001729 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001730 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001731 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001732 Builder.AddPlaceholderChunk("expression");
1733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1734 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1735 Builder.AddPlaceholderChunk("statements");
1736 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1737 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1738 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001739
1740 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("do");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1743 Builder.AddPlaceholderChunk("statements");
1744 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1745 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1746 Builder.AddTextChunk("while");
1747 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1748 Builder.AddPlaceholderChunk("expression");
1749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1750 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001751
Douglas Gregorf64acca2010-05-25 21:41:55 +00001752 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddTypedTextChunk("for");
1754 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001755 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001756 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001757 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001758 Builder.AddPlaceholderChunk("init-expression");
1759 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1760 Builder.AddPlaceholderChunk("condition");
1761 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1762 Builder.AddPlaceholderChunk("inc-expression");
1763 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1764 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1765 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1766 Builder.AddPlaceholderChunk("statements");
1767 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1768 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1769 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001770 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001771
1772 if (S->getContinueParent()) {
1773 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001774 Builder.AddTypedTextChunk("continue");
1775 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001776 }
1777
1778 if (S->getBreakParent()) {
1779 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001780 Builder.AddTypedTextChunk("break");
1781 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001782 }
1783
1784 // "return expression ;" or "return ;", depending on whether we
1785 // know the function is void or not.
1786 bool isVoid = false;
1787 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001788 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001789 else if (ObjCMethodDecl *Method
1790 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001791 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001792 else if (SemaRef.getCurBlock() &&
1793 !SemaRef.getCurBlock()->ReturnType.isNull())
1794 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001795 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001796 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001797 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1798 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001799 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001800 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001801
Douglas Gregorf4c33342010-05-28 00:22:41 +00001802 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001803 Builder.AddTypedTextChunk("goto");
1804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1805 Builder.AddPlaceholderChunk("label");
1806 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001807
Douglas Gregorf4c33342010-05-28 00:22:41 +00001808 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001809 Builder.AddTypedTextChunk("using");
1810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1811 Builder.AddTextChunk("namespace");
1812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1813 Builder.AddPlaceholderChunk("identifier");
1814 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001815 }
1816
1817 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001818 case Sema::PCC_ForInit:
1819 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001820 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001821 // Fall through: conditions and statements can have expressions.
1822
Douglas Gregor5e35d592010-09-14 23:59:36 +00001823 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001824 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001825 CCC == Sema::PCC_ParenthesizedExpression) {
1826 // (__bridge <type>)<expression>
1827 Builder.AddTypedTextChunk("__bridge");
1828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1829 Builder.AddPlaceholderChunk("type");
1830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1831 Builder.AddPlaceholderChunk("expression");
1832 Results.AddResult(Result(Builder.TakeString()));
1833
1834 // (__bridge_transfer <Objective-C type>)<expression>
1835 Builder.AddTypedTextChunk("__bridge_transfer");
1836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1837 Builder.AddPlaceholderChunk("Objective-C type");
1838 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1839 Builder.AddPlaceholderChunk("expression");
1840 Results.AddResult(Result(Builder.TakeString()));
1841
1842 // (__bridge_retained <CF type>)<expression>
1843 Builder.AddTypedTextChunk("__bridge_retained");
1844 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1845 Builder.AddPlaceholderChunk("CF type");
1846 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1847 Builder.AddPlaceholderChunk("expression");
1848 Results.AddResult(Result(Builder.TakeString()));
1849 }
1850 // Fall through
1851
John McCallfaf5fb42010-08-26 23:41:50 +00001852 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001853 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001854 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001855 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001856
Douglas Gregore5c79d52011-10-18 21:20:17 +00001857 // true
1858 Builder.AddResultTypeChunk("bool");
1859 Builder.AddTypedTextChunk("true");
1860 Results.AddResult(Result(Builder.TakeString()));
1861
1862 // false
1863 Builder.AddResultTypeChunk("bool");
1864 Builder.AddTypedTextChunk("false");
1865 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001866
David Blaikiebbafb8a2012-03-11 07:00:24 +00001867 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001868 // dynamic_cast < type-id > ( expression )
1869 Builder.AddTypedTextChunk("dynamic_cast");
1870 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1871 Builder.AddPlaceholderChunk("type");
1872 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1874 Builder.AddPlaceholderChunk("expression");
1875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1876 Results.AddResult(Result(Builder.TakeString()));
1877 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001878
1879 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001880 Builder.AddTypedTextChunk("static_cast");
1881 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1882 Builder.AddPlaceholderChunk("type");
1883 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1885 Builder.AddPlaceholderChunk("expression");
1886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1887 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001888
Douglas Gregorf4c33342010-05-28 00:22:41 +00001889 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001890 Builder.AddTypedTextChunk("reinterpret_cast");
1891 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1892 Builder.AddPlaceholderChunk("type");
1893 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1894 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1895 Builder.AddPlaceholderChunk("expression");
1896 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1897 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001898
Douglas Gregorf4c33342010-05-28 00:22:41 +00001899 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001900 Builder.AddTypedTextChunk("const_cast");
1901 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1902 Builder.AddPlaceholderChunk("type");
1903 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1904 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1905 Builder.AddPlaceholderChunk("expression");
1906 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1907 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001908
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001910 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001911 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001912 Builder.AddTypedTextChunk("typeid");
1913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1914 Builder.AddPlaceholderChunk("expression-or-type");
1915 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1916 Results.AddResult(Result(Builder.TakeString()));
1917 }
1918
Douglas Gregorf4c33342010-05-28 00:22:41 +00001919 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001920 Builder.AddTypedTextChunk("new");
1921 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1922 Builder.AddPlaceholderChunk("type");
1923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1924 Builder.AddPlaceholderChunk("expressions");
1925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1926 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001927
Douglas Gregorf4c33342010-05-28 00:22:41 +00001928 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001929 Builder.AddTypedTextChunk("new");
1930 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1931 Builder.AddPlaceholderChunk("type");
1932 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1933 Builder.AddPlaceholderChunk("size");
1934 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1936 Builder.AddPlaceholderChunk("expressions");
1937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1938 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001939
Douglas Gregorf4c33342010-05-28 00:22:41 +00001940 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001941 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001942 Builder.AddTypedTextChunk("delete");
1943 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1944 Builder.AddPlaceholderChunk("expression");
1945 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001946
Douglas Gregorf4c33342010-05-28 00:22:41 +00001947 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001948 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001949 Builder.AddTypedTextChunk("delete");
1950 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1951 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1952 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1953 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1954 Builder.AddPlaceholderChunk("expression");
1955 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001956
David Blaikiebbafb8a2012-03-11 07:00:24 +00001957 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001958 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001959 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001960 Builder.AddTypedTextChunk("throw");
1961 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1962 Builder.AddPlaceholderChunk("expression");
1963 Results.AddResult(Result(Builder.TakeString()));
1964 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001965
Douglas Gregora2db7932010-05-26 22:00:08 +00001966 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001967
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001968 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001969 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001970 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001971 Builder.AddTypedTextChunk("nullptr");
1972 Results.AddResult(Result(Builder.TakeString()));
1973
1974 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001975 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001976 Builder.AddTypedTextChunk("alignof");
1977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1978 Builder.AddPlaceholderChunk("type");
1979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1980 Results.AddResult(Result(Builder.TakeString()));
1981
1982 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001983 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001984 Builder.AddTypedTextChunk("noexcept");
1985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986 Builder.AddPlaceholderChunk("expression");
1987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988 Results.AddResult(Result(Builder.TakeString()));
1989
1990 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001991 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001992 Builder.AddTypedTextChunk("sizeof...");
1993 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1994 Builder.AddPlaceholderChunk("parameter-pack");
1995 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1996 Results.AddResult(Result(Builder.TakeString()));
1997 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001998 }
1999
David Blaikiebbafb8a2012-03-11 07:00:24 +00002000 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002001 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00002002 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2003 // The interface can be NULL.
2004 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002005 if (ID->getSuperClass()) {
2006 std::string SuperType;
2007 SuperType = ID->getSuperClass()->getNameAsString();
2008 if (Method->isInstanceMethod())
2009 SuperType += " *";
2010
2011 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2012 Builder.AddTypedTextChunk("super");
2013 Results.AddResult(Result(Builder.TakeString()));
2014 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002015 }
2016
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002017 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002018 }
2019
Jordan Rose58d54722012-06-30 21:33:57 +00002020 if (SemaRef.getLangOpts().C11) {
2021 // _Alignof
2022 Builder.AddResultTypeChunk("size_t");
Richard Smith20e883e2015-04-29 23:20:19 +00002023 if (SemaRef.PP.isMacroDefined("alignof"))
Jordan Rose58d54722012-06-30 21:33:57 +00002024 Builder.AddTypedTextChunk("alignof");
2025 else
2026 Builder.AddTypedTextChunk("_Alignof");
2027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2028 Builder.AddPlaceholderChunk("type");
2029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2030 Results.AddResult(Result(Builder.TakeString()));
2031 }
2032
Douglas Gregorf4c33342010-05-28 00:22:41 +00002033 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002034 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002035 Builder.AddTypedTextChunk("sizeof");
2036 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2037 Builder.AddPlaceholderChunk("expression-or-type");
2038 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2039 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002040 break;
2041 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002042
John McCallfaf5fb42010-08-26 23:41:50 +00002043 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002044 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002045 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002046 }
2047
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2049 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002050
David Blaikiebbafb8a2012-03-11 07:00:24 +00002051 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002052 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002053}
2054
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002055/// \brief If the given declaration has an associated type, add it as a result
2056/// type chunk.
2057static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002058 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002059 const NamedDecl *ND,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002060 QualType BaseType,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002061 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002062 if (!ND)
2063 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002064
2065 // Skip constructors and conversion functions, which have their return types
2066 // built into their names.
2067 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2068 return;
2069
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002070 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002071 QualType T;
2072 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002073 T = Function->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002074 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2075 if (!BaseType.isNull())
2076 T = Method->getSendResultType(BaseType);
2077 else
2078 T = Method->getReturnType();
2079 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002080 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2081 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2082 /* Do nothing: ignore unresolved using declarations*/
Douglas Gregorc3425b12015-07-07 06:20:19 +00002083 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2084 if (!BaseType.isNull())
2085 T = Ivar->getUsageType(BaseType);
2086 else
2087 T = Ivar->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002088 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002089 T = Value->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002090 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2091 if (!BaseType.isNull())
2092 T = Property->getUsageType(BaseType);
2093 else
2094 T = Property->getType();
2095 }
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002096
2097 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2098 return;
2099
Douglas Gregor75acd922011-09-27 23:30:47 +00002100 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002101 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002102}
2103
Richard Smith20e883e2015-04-29 23:20:19 +00002104static void MaybeAddSentinel(Preprocessor &PP,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002105 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002106 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002107 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2108 if (Sentinel->getSentinel() == 0) {
Richard Smith20e883e2015-04-29 23:20:19 +00002109 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002110 Result.AddTextChunk(", nil");
Richard Smith20e883e2015-04-29 23:20:19 +00002111 else if (PP.isMacroDefined("NULL"))
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002112 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002113 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002114 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002115 }
2116}
2117
Douglas Gregor86b42682015-06-19 18:27:52 +00002118static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2119 QualType &Type) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002120 std::string Result;
2121 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002122 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002123 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002124 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002125 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002126 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002127 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002128 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002129 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002130 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002131 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002132 Result += "oneway ";
Douglas Gregor86b42682015-06-19 18:27:52 +00002133 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2134 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2135 switch (*nullability) {
2136 case NullabilityKind::NonNull:
2137 Result += "nonnull ";
2138 break;
2139
2140 case NullabilityKind::Nullable:
2141 Result += "nullable ";
2142 break;
2143
2144 case NullabilityKind::Unspecified:
2145 Result += "null_unspecified ";
2146 break;
2147 }
2148 }
2149 }
Douglas Gregor8f08d742011-07-30 07:55:26 +00002150 return Result;
2151}
2152
Richard Smith20e883e2015-04-29 23:20:19 +00002153static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002154 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002155 bool SuppressName = false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002156 bool SuppressBlock = false,
2157 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002158 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2159 if (Param->getType()->isDependentType() ||
2160 !Param->getType()->isBlockPointerType()) {
2161 // The argument for a dependent or non-block parameter is a placeholder
2162 // containing that parameter's type.
2163 std::string Result;
2164
Douglas Gregor981a0c42010-08-29 19:47:46 +00002165 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002166 Result = Param->getIdentifier()->getName();
2167
Douglas Gregor86b42682015-06-19 18:27:52 +00002168 QualType Type = Param->getType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002169 if (ObjCSubsts)
2170 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2171 ObjCSubstitutionContext::Parameter);
Douglas Gregore90dd002010-08-24 16:15:59 +00002172 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002173 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2174 Type);
2175 Result += Type.getAsString(Policy) + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002176 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002177 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002178 } else {
2179 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002180 }
2181 return Result;
2182 }
2183
2184 // The argument for a block pointer parameter is a block literal with
2185 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002186 FunctionTypeLoc Block;
2187 FunctionProtoTypeLoc BlockProto;
Douglas Gregore90dd002010-08-24 16:15:59 +00002188 TypeLoc TL;
2189 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2190 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2191 while (true) {
2192 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002193 if (!SuppressBlock) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002194 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2195 if (TypeSourceInfo *InnerTSInfo =
2196 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002197 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2198 continue;
2199 }
2200 }
2201
2202 // Look through qualified types
David Blaikie6adc78e2013-02-18 22:06:02 +00002203 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2204 TL = QualifiedTL.getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002205 continue;
2206 }
Douglas Gregor4c850f32015-07-07 06:20:22 +00002207
2208 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2209 TL = AttrTL.getModifiedLoc();
2210 continue;
2211 }
Douglas Gregore90dd002010-08-24 16:15:59 +00002212 }
2213
Douglas Gregore90dd002010-08-24 16:15:59 +00002214 // Try to get the function prototype behind the block pointer type,
2215 // then we're done.
David Blaikie6adc78e2013-02-18 22:06:02 +00002216 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2217 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2218 Block = TL.getAs<FunctionTypeLoc>();
2219 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregore90dd002010-08-24 16:15:59 +00002220 }
2221 break;
2222 }
2223 }
2224
2225 if (!Block) {
2226 // We were unable to find a FunctionProtoTypeLoc with parameter names
2227 // for the block; just use the parameter type as a placeholder.
2228 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002229 if (!ObjCMethodParam && Param->getIdentifier())
2230 Result = Param->getIdentifier()->getName();
2231
Douglas Gregor86b42682015-06-19 18:27:52 +00002232 QualType Type = Param->getType().getUnqualifiedType();
Douglas Gregore90dd002010-08-24 16:15:59 +00002233
2234 if (ObjCMethodParam) {
Douglas Gregor86b42682015-06-19 18:27:52 +00002235 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2236 Type);
2237 Result += Type.getAsString(Policy) + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002238 if (Param->getIdentifier())
2239 Result += Param->getIdentifier()->getName();
Douglas Gregor86b42682015-06-19 18:27:52 +00002240 } else {
2241 Type.getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002242 }
2243
2244 return Result;
2245 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002246
Douglas Gregore90dd002010-08-24 16:15:59 +00002247 // We have the function prototype behind the block pointer type, as it was
2248 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002249 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002250 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregorc3425b12015-07-07 06:20:19 +00002251 if (ObjCSubsts)
2252 ResultType = ResultType.substObjCTypeArgs(Param->getASTContext(),
2253 *ObjCSubsts,
2254 ObjCSubstitutionContext::Result);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002255 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002256 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002257
2258 // Format the parameter list.
2259 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002260 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002261 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002262 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002263 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002264 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002265 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002266 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002267 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002268 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002269 Params += ", ";
Richard Smith20e883e2015-04-29 23:20:19 +00002270 Params += FormatFunctionParameter(Policy, Block.getParam(I),
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002271 /*SuppressName=*/false,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002272 /*SuppressBlock=*/true,
2273 ObjCSubsts);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002274
David Blaikie6adc78e2013-02-18 22:06:02 +00002275 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002276 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002277 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002278 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002279 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002280
Douglas Gregord793e7c2011-10-18 04:23:19 +00002281 if (SuppressBlock) {
2282 // Format as a parameter.
2283 Result = Result + " (^";
2284 if (Param->getIdentifier())
2285 Result += Param->getIdentifier()->getName();
2286 Result += ")";
2287 Result += Params;
2288 } else {
2289 // Format as a block literal argument.
2290 Result = '^' + Result;
2291 Result += Params;
2292
2293 if (Param->getIdentifier())
2294 Result += Param->getIdentifier()->getName();
2295 }
2296
Douglas Gregore90dd002010-08-24 16:15:59 +00002297 return Result;
2298}
2299
Douglas Gregor3545ff42009-09-21 16:56:56 +00002300/// \brief Add function parameter chunks to the given code completion string.
Richard Smith20e883e2015-04-29 23:20:19 +00002301static void AddFunctionParameterChunks(Preprocessor &PP,
Douglas Gregor75acd922011-09-27 23:30:47 +00002302 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002303 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002304 CodeCompletionBuilder &Result,
2305 unsigned Start = 0,
2306 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002307 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002308
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002309 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002310 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002311
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002312 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002313 // When we see an optional default argument, put that argument and
2314 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002315 CodeCompletionBuilder Opt(Result.getAllocator(),
2316 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002317 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002318 Opt.AddChunk(CodeCompletionString::CK_Comma);
Richard Smith20e883e2015-04-29 23:20:19 +00002319 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002320 Result.AddOptionalChunk(Opt.TakeString());
2321 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002322 }
2323
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002324 if (FirstParameter)
2325 FirstParameter = false;
2326 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002327 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002328
2329 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002330
2331 // Format the placeholder string.
Richard Smith20e883e2015-04-29 23:20:19 +00002332 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2333
Douglas Gregor400f5972010-08-31 05:13:43 +00002334 if (Function->isVariadic() && P == N - 1)
2335 PlaceholderStr += ", ...";
2336
Douglas Gregor3545ff42009-09-21 16:56:56 +00002337 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002338 Result.AddPlaceholderChunk(
2339 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002340 }
Douglas Gregorba449032009-09-22 21:42:17 +00002341
2342 if (const FunctionProtoType *Proto
2343 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002344 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002345 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002346 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002347
Richard Smith20e883e2015-04-29 23:20:19 +00002348 MaybeAddSentinel(PP, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002349 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002350}
2351
2352/// \brief Add template parameter chunks to the given code completion string.
2353static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002354 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002355 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002356 CodeCompletionBuilder &Result,
2357 unsigned MaxParameters = 0,
2358 unsigned Start = 0,
2359 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002360 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002361
2362 // Prefer to take the template parameter names from the first declaration of
2363 // the template.
2364 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2365
Douglas Gregor3545ff42009-09-21 16:56:56 +00002366 TemplateParameterList *Params = Template->getTemplateParameters();
2367 TemplateParameterList::iterator PEnd = Params->end();
2368 if (MaxParameters)
2369 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002370 for (TemplateParameterList::iterator P = Params->begin() + Start;
2371 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002372 bool HasDefaultArg = false;
2373 std::string PlaceholderStr;
2374 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2375 if (TTP->wasDeclaredWithTypename())
2376 PlaceholderStr = "typename";
2377 else
2378 PlaceholderStr = "class";
2379
2380 if (TTP->getIdentifier()) {
2381 PlaceholderStr += ' ';
2382 PlaceholderStr += TTP->getIdentifier()->getName();
2383 }
2384
2385 HasDefaultArg = TTP->hasDefaultArgument();
2386 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002387 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002388 if (NTTP->getIdentifier())
2389 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002390 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002391 HasDefaultArg = NTTP->hasDefaultArgument();
2392 } else {
2393 assert(isa<TemplateTemplateParmDecl>(*P));
2394 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2395
2396 // Since putting the template argument list into the placeholder would
2397 // be very, very long, we just use an abbreviation.
2398 PlaceholderStr = "template<...> class";
2399 if (TTP->getIdentifier()) {
2400 PlaceholderStr += ' ';
2401 PlaceholderStr += TTP->getIdentifier()->getName();
2402 }
2403
2404 HasDefaultArg = TTP->hasDefaultArgument();
2405 }
2406
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002407 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002408 // When we see an optional default argument, put that argument and
2409 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002410 CodeCompletionBuilder Opt(Result.getAllocator(),
2411 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002412 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002413 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002414 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002415 P - Params->begin(), true);
2416 Result.AddOptionalChunk(Opt.TakeString());
2417 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002418 }
2419
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002420 InDefaultArg = false;
2421
Douglas Gregor3545ff42009-09-21 16:56:56 +00002422 if (FirstParameter)
2423 FirstParameter = false;
2424 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002425 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002426
2427 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002428 Result.AddPlaceholderChunk(
2429 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002430 }
2431}
2432
Douglas Gregorf2510672009-09-21 19:57:38 +00002433/// \brief Add a qualifier to the given code-completion string, if the
2434/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002435static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002436AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002437 NestedNameSpecifier *Qualifier,
2438 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002439 ASTContext &Context,
2440 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002441 if (!Qualifier)
2442 return;
2443
2444 std::string PrintedNNS;
2445 {
2446 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002447 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002448 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002449 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002450 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002451 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002452 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002453}
2454
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002455static void
2456AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002457 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002458 const FunctionProtoType *Proto
2459 = Function->getType()->getAs<FunctionProtoType>();
2460 if (!Proto || !Proto->getTypeQuals())
2461 return;
2462
Douglas Gregor304f9b02011-02-01 21:15:40 +00002463 // FIXME: Add ref-qualifier!
2464
2465 // Handle single qualifiers without copying
2466 if (Proto->getTypeQuals() == Qualifiers::Const) {
2467 Result.AddInformativeChunk(" const");
2468 return;
2469 }
2470
2471 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2472 Result.AddInformativeChunk(" volatile");
2473 return;
2474 }
2475
2476 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2477 Result.AddInformativeChunk(" restrict");
2478 return;
2479 }
2480
2481 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002482 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002483 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002484 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002485 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002486 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002487 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002488 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002489 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002490}
2491
Douglas Gregor0212fd72010-09-21 16:06:22 +00002492/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002493static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002494 const NamedDecl *ND,
2495 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002496 DeclarationName Name = ND->getDeclName();
2497 if (!Name)
2498 return;
2499
2500 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002501 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002502 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002503 switch (Name.getCXXOverloadedOperator()) {
2504 case OO_None:
2505 case OO_Conditional:
2506 case NUM_OVERLOADED_OPERATORS:
2507 OperatorName = "operator";
2508 break;
2509
2510#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2511 case OO_##Name: OperatorName = "operator" Spelling; break;
2512#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2513#include "clang/Basic/OperatorKinds.def"
2514
2515 case OO_New: OperatorName = "operator new"; break;
2516 case OO_Delete: OperatorName = "operator delete"; break;
2517 case OO_Array_New: OperatorName = "operator new[]"; break;
2518 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2519 case OO_Call: OperatorName = "operator()"; break;
2520 case OO_Subscript: OperatorName = "operator[]"; break;
2521 }
2522 Result.AddTypedTextChunk(OperatorName);
2523 break;
2524 }
2525
Douglas Gregor0212fd72010-09-21 16:06:22 +00002526 case DeclarationName::Identifier:
2527 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002528 case DeclarationName::CXXDestructorName:
2529 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002530 Result.AddTypedTextChunk(
2531 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002532 break;
2533
2534 case DeclarationName::CXXUsingDirective:
2535 case DeclarationName::ObjCZeroArgSelector:
2536 case DeclarationName::ObjCOneArgSelector:
2537 case DeclarationName::ObjCMultiArgSelector:
2538 break;
2539
2540 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002541 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002542 QualType Ty = Name.getCXXNameType();
2543 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2544 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2545 else if (const InjectedClassNameType *InjectedTy
2546 = Ty->getAs<InjectedClassNameType>())
2547 Record = InjectedTy->getDecl();
2548 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002549 Result.AddTypedTextChunk(
2550 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002551 break;
2552 }
2553
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002554 Result.AddTypedTextChunk(
2555 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002556 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002557 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002558 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002559 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002560 }
2561 break;
2562 }
2563 }
2564}
2565
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002566CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002567 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002568 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002569 CodeCompletionTUInfo &CCTUInfo,
2570 bool IncludeBriefComments) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002571 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2572 CCTUInfo, IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002573}
2574
Douglas Gregor3545ff42009-09-21 16:56:56 +00002575/// \brief If possible, create a new code completion string for the given
2576/// result.
2577///
2578/// \returns Either a new, heap-allocated code completion string describing
2579/// how to use this result, or NULL to indicate that the string or name of the
2580/// result is all that is needed.
2581CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002582CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2583 Preprocessor &PP,
Douglas Gregorc3425b12015-07-07 06:20:19 +00002584 const CodeCompletionContext &CCContext,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002585 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002586 CodeCompletionTUInfo &CCTUInfo,
2587 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002588 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002589
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002590 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002591 if (Kind == RK_Pattern) {
2592 Pattern->Priority = Priority;
2593 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002594
2595 if (Declaration) {
2596 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002597 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002598 // Provide code completion comment for self.GetterName where
2599 // GetterName is the getter method for a property with name
2600 // different from the property name (declared via a property
2601 // getter attribute.
2602 const NamedDecl *ND = Declaration;
2603 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2604 if (M->isPropertyAccessor())
2605 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2606 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002607 PDecl->getIdentifier() != M->getIdentifier()) {
2608 if (const RawComment *RC =
2609 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002610 Result.addBriefComment(RC->getBriefText(Ctx));
2611 Pattern->BriefComment = Result.getBriefComment();
2612 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002613 else if (const RawComment *RC =
2614 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2615 Result.addBriefComment(RC->getBriefText(Ctx));
2616 Pattern->BriefComment = Result.getBriefComment();
2617 }
2618 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002619 }
2620
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002621 return Pattern;
2622 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002623
Douglas Gregorf09935f2009-12-01 05:55:20 +00002624 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002625 Result.AddTypedTextChunk(Keyword);
2626 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002627 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002628
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002629 if (Kind == RK_Macro) {
Richard Smith20e883e2015-04-29 23:20:19 +00002630 const MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002631 Result.AddTypedTextChunk(
2632 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002633
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002634 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002635 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002636
2637 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002638 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002639 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002640
2641 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2642 if (MI->isC99Varargs()) {
2643 --AEnd;
2644
2645 if (A == AEnd) {
2646 Result.AddPlaceholderChunk("...");
2647 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002648 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002649
Douglas Gregor0c505312011-07-30 08:17:44 +00002650 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002651 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002652 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002653
2654 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002655 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002656 if (MI->isC99Varargs())
2657 Arg += ", ...";
2658 else
2659 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002660 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002661 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002662 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002663
2664 // Non-variadic macros are simple.
2665 Result.AddPlaceholderChunk(
2666 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002667 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002668 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002669 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002670 }
2671
Douglas Gregorf64acca2010-05-25 21:41:55 +00002672 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002673 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002674 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002675
2676 if (IncludeBriefComments) {
2677 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002678 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002679 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002680 }
2681 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2682 if (OMD->isPropertyAccessor())
2683 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2684 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2685 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002686 }
2687
Douglas Gregor9eb77012009-11-07 00:00:49 +00002688 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002689 Result.AddTypedTextChunk(
2690 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002691 Result.AddTextChunk("::");
2692 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002693 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002694
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002695 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2696 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002697
Douglas Gregorc3425b12015-07-07 06:20:19 +00002698 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002699
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002700 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002701 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002702 Ctx, Policy);
2703 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002704 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002705 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002706 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002707 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002708 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002709 }
2710
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002711 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002712 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002713 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002714 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002715 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002716
Douglas Gregor3545ff42009-09-21 16:56:56 +00002717 // Figure out which template parameters are deduced (or have default
2718 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002719 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002720 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002721 unsigned LastDeducibleArgument;
2722 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2723 --LastDeducibleArgument) {
2724 if (!Deduced[LastDeducibleArgument - 1]) {
2725 // C++0x: Figure out if the template argument has a default. If so,
2726 // the user doesn't need to type this argument.
2727 // FIXME: We need to abstract template parameters better!
2728 bool HasDefaultArg = false;
2729 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002730 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002731 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2732 HasDefaultArg = TTP->hasDefaultArgument();
2733 else if (NonTypeTemplateParmDecl *NTTP
2734 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2735 HasDefaultArg = NTTP->hasDefaultArgument();
2736 else {
2737 assert(isa<TemplateTemplateParmDecl>(Param));
2738 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002739 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002740 }
2741
2742 if (!HasDefaultArg)
2743 break;
2744 }
2745 }
2746
2747 if (LastDeducibleArgument) {
2748 // Some of the function template arguments cannot be deduced from a
2749 // function call, so we introduce an explicit template argument list
2750 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002751 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002752 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002753 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002754 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002755 }
2756
2757 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002758 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Richard Smith20e883e2015-04-29 23:20:19 +00002759 AddFunctionParameterChunks(PP, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002760 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002761 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002762 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002763 }
2764
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002765 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002766 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002767 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002768 Result.AddTypedTextChunk(
2769 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002770 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002771 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002772 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002773 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002774 }
2775
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002776 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002777 Selector Sel = Method->getSelector();
2778 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002779 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002780 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002781 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002782 }
2783
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002784 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002785 SelName += ':';
2786 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002787 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002788 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002789 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002790
2791 // If there is only one parameter, and we're past it, add an empty
2792 // typed-text chunk since there is nothing to type.
2793 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002794 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002795 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002796 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002797 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2798 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002799 P != PEnd; (void)++P, ++Idx) {
2800 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002801 std::string Keyword;
2802 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002803 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002804 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002805 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002806 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002807 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002808 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002809 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002810 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002811 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002812
2813 // If we're before the starting parameter, skip the placeholder.
2814 if (Idx < StartParameter)
2815 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002816
2817 std::string Arg;
Douglas Gregorc3425b12015-07-07 06:20:19 +00002818 QualType ParamType = (*P)->getType();
2819 Optional<ArrayRef<QualType>> ObjCSubsts;
2820 if (!CCContext.getBaseType().isNull())
2821 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2822
2823 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2824 Arg = FormatFunctionParameter(Policy, *P, true,
2825 /*SuppressBlock=*/false,
2826 ObjCSubsts);
Douglas Gregore90dd002010-08-24 16:15:59 +00002827 else {
Douglas Gregorc3425b12015-07-07 06:20:19 +00002828 if (ObjCSubsts)
2829 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2830 ObjCSubstitutionContext::Parameter);
Douglas Gregor86b42682015-06-19 18:27:52 +00002831 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00002832 ParamType);
2833 Arg += ParamType.getAsString(Policy) + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002834 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002835 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002836 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002837 }
2838
Douglas Gregor400f5972010-08-31 05:13:43 +00002839 if (Method->isVariadic() && (P + 1) == PEnd)
2840 Arg += ", ...";
2841
Douglas Gregor95887f92010-07-08 23:20:03 +00002842 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002843 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002844 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002845 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002846 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002847 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002848 }
2849
Douglas Gregor04c5f972009-12-23 00:21:46 +00002850 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002851 if (Method->param_size() == 0) {
2852 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002853 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002854 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002855 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002856 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002857 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002858 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002859
Richard Smith20e883e2015-04-29 23:20:19 +00002860 MaybeAddSentinel(PP, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002861 }
2862
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002863 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002864 }
2865
Douglas Gregorf09935f2009-12-01 05:55:20 +00002866 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002867 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002868 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002869
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002870 Result.AddTypedTextChunk(
2871 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002872 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002873}
2874
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002875/// \brief Add function overload parameter chunks to the given code completion
2876/// string.
2877static void AddOverloadParameterChunks(ASTContext &Context,
2878 const PrintingPolicy &Policy,
2879 const FunctionDecl *Function,
2880 const FunctionProtoType *Prototype,
2881 CodeCompletionBuilder &Result,
2882 unsigned CurrentArg,
2883 unsigned Start = 0,
2884 bool InOptional = false) {
2885 bool FirstParameter = true;
2886 unsigned NumParams = Function ? Function->getNumParams()
2887 : Prototype->getNumParams();
2888
2889 for (unsigned P = Start; P != NumParams; ++P) {
2890 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2891 // When we see an optional default argument, put that argument and
2892 // the remaining default arguments into a new, optional string.
2893 CodeCompletionBuilder Opt(Result.getAllocator(),
2894 Result.getCodeCompletionTUInfo());
2895 if (!FirstParameter)
2896 Opt.AddChunk(CodeCompletionString::CK_Comma);
2897 // Optional sections are nested.
2898 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2899 CurrentArg, P, /*InOptional=*/true);
2900 Result.AddOptionalChunk(Opt.TakeString());
2901 return;
2902 }
2903
2904 if (FirstParameter)
2905 FirstParameter = false;
2906 else
2907 Result.AddChunk(CodeCompletionString::CK_Comma);
2908
2909 InOptional = false;
2910
2911 // Format the placeholder string.
2912 std::string Placeholder;
2913 if (Function)
Richard Smith20e883e2015-04-29 23:20:19 +00002914 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002915 else
2916 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2917
2918 if (P == CurrentArg)
2919 Result.AddCurrentParameterChunk(
2920 Result.getAllocator().CopyString(Placeholder));
2921 else
2922 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2923 }
2924
2925 if (Prototype && Prototype->isVariadic()) {
2926 CodeCompletionBuilder Opt(Result.getAllocator(),
2927 Result.getCodeCompletionTUInfo());
2928 if (!FirstParameter)
2929 Opt.AddChunk(CodeCompletionString::CK_Comma);
2930
2931 if (CurrentArg < NumParams)
2932 Opt.AddPlaceholderChunk("...");
2933 else
2934 Opt.AddCurrentParameterChunk("...");
2935
2936 Result.AddOptionalChunk(Opt.TakeString());
2937 }
2938}
2939
Douglas Gregorf0f51982009-09-23 00:34:09 +00002940CodeCompletionString *
2941CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002942 unsigned CurrentArg, Sema &S,
2943 CodeCompletionAllocator &Allocator,
2944 CodeCompletionTUInfo &CCTUInfo,
2945 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002946 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002947
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002948 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002949 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002950 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002951 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00002952 = dyn_cast<FunctionProtoType>(getFunctionType());
2953 if (!FDecl && !Proto) {
2954 // Function without a prototype. Just give the return type and a
2955 // highlighted ellipsis.
2956 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002957 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
2958 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002959 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2960 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2961 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002962 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002963 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002964
2965 if (FDecl) {
2966 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
2967 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
2968 FDecl->getParamDecl(CurrentArg)))
2969 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
Douglas Gregorc3425b12015-07-07 06:20:19 +00002970 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002971 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002972 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2973 } else {
2974 Result.AddResultTypeChunk(
2975 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00002976 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002977 }
Alp Toker314cc812014-01-25 16:55:45 +00002978
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002979 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002980 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
2981 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002982 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002983
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002984 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002985}
2986
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002987unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002988 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002989 bool PreferredTypeIsPointer) {
2990 unsigned Priority = CCP_Macro;
2991
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002992 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2993 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2994 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002995 Priority = CCP_Constant;
2996 if (PreferredTypeIsPointer)
2997 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002998 }
2999 // Treat "YES", "NO", "true", and "false" as constants.
3000 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3001 MacroName.equals("true") || MacroName.equals("false"))
3002 Priority = CCP_Constant;
3003 // Treat "bool" as a type.
3004 else if (MacroName.equals("bool"))
3005 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3006
Douglas Gregor6e240332010-08-16 16:18:59 +00003007
3008 return Priority;
3009}
3010
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003011CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003012 if (!D)
3013 return CXCursor_UnexposedDecl;
3014
3015 switch (D->getKind()) {
3016 case Decl::Enum: return CXCursor_EnumDecl;
3017 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3018 case Decl::Field: return CXCursor_FieldDecl;
3019 case Decl::Function:
3020 return CXCursor_FunctionDecl;
3021 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3022 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003023 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003024
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003025 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003026 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3027 case Decl::ObjCMethod:
3028 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3029 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3030 case Decl::CXXMethod: return CXCursor_CXXMethod;
3031 case Decl::CXXConstructor: return CXCursor_Constructor;
3032 case Decl::CXXDestructor: return CXCursor_Destructor;
3033 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3034 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00003035 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003036 case Decl::ParmVar: return CXCursor_ParmDecl;
3037 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00003038 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003039 case Decl::Var: return CXCursor_VarDecl;
3040 case Decl::Namespace: return CXCursor_Namespace;
3041 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3042 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3043 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3044 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3045 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3046 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00003047 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003048 case Decl::ClassTemplatePartialSpecialization:
3049 return CXCursor_ClassTemplatePartialSpecialization;
3050 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor3e653b32012-04-30 23:41:16 +00003051 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003052
3053 case Decl::Using:
3054 case Decl::UnresolvedUsingValue:
3055 case Decl::UnresolvedUsingTypename:
3056 return CXCursor_UsingDeclaration;
3057
Douglas Gregor4cd65962011-06-03 23:08:58 +00003058 case Decl::ObjCPropertyImpl:
3059 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3060 case ObjCPropertyImplDecl::Dynamic:
3061 return CXCursor_ObjCDynamicDecl;
3062
3063 case ObjCPropertyImplDecl::Synthesize:
3064 return CXCursor_ObjCSynthesizeDecl;
3065 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003066
3067 case Decl::Import:
3068 return CXCursor_ModuleImportDecl;
Douglas Gregor85f3f952015-07-07 03:57:15 +00003069
3070 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3071
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003072 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003073 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003074 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003075 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003076 case TTK_Struct: return CXCursor_StructDecl;
3077 case TTK_Class: return CXCursor_ClassDecl;
3078 case TTK_Union: return CXCursor_UnionDecl;
3079 case TTK_Enum: return CXCursor_EnumDecl;
3080 }
3081 }
3082 }
3083
3084 return CXCursor_UnexposedDecl;
3085}
3086
Douglas Gregor55b037b2010-07-08 20:55:51 +00003087static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003088 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003089 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003090 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003091
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003092 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003093
Douglas Gregor9eb77012009-11-07 00:00:49 +00003094 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3095 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003096 M != MEnd; ++M) {
Richard Smith20e883e2015-04-29 23:20:19 +00003097 auto MD = PP.getMacroDefinition(M->first);
3098 if (IncludeUndefined || MD) {
3099 if (MacroInfo *MI = MD.getMacroInfo())
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003100 if (MI->isUsedForHeaderGuard())
3101 continue;
3102
Douglas Gregor8cb17462012-10-09 16:01:50 +00003103 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003104 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003105 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003106 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003107 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003108 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003109
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003110 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003111
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003112}
3113
Douglas Gregorce0e8562010-08-23 21:54:33 +00003114static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3115 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003116 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003117
3118 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003119
Douglas Gregorce0e8562010-08-23 21:54:33 +00003120 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3121 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003122 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003123 Results.AddResult(Result("__func__", CCP_Constant));
3124 Results.ExitScope();
3125}
3126
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003127static void HandleCodeCompleteResults(Sema *S,
3128 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003129 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003130 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003131 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003132 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003133 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003134}
3135
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003136static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3137 Sema::ParserCompletionContext PCC) {
3138 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003139 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003140 return CodeCompletionContext::CCC_TopLevel;
3141
John McCallfaf5fb42010-08-26 23:41:50 +00003142 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003143 return CodeCompletionContext::CCC_ClassStructUnion;
3144
John McCallfaf5fb42010-08-26 23:41:50 +00003145 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003146 return CodeCompletionContext::CCC_ObjCInterface;
3147
John McCallfaf5fb42010-08-26 23:41:50 +00003148 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003149 return CodeCompletionContext::CCC_ObjCImplementation;
3150
John McCallfaf5fb42010-08-26 23:41:50 +00003151 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003152 return CodeCompletionContext::CCC_ObjCIvarList;
3153
John McCallfaf5fb42010-08-26 23:41:50 +00003154 case Sema::PCC_Template:
3155 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003156 if (S.CurContext->isFileContext())
3157 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003158 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003159 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003160 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003161
John McCallfaf5fb42010-08-26 23:41:50 +00003162 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003163 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003164
John McCallfaf5fb42010-08-26 23:41:50 +00003165 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003166 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3167 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003168 return CodeCompletionContext::CCC_ParenthesizedExpression;
3169 else
3170 return CodeCompletionContext::CCC_Expression;
3171
3172 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003173 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003174 return CodeCompletionContext::CCC_Expression;
3175
John McCallfaf5fb42010-08-26 23:41:50 +00003176 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003177 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003178
John McCallfaf5fb42010-08-26 23:41:50 +00003179 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003180 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003181
3182 case Sema::PCC_ParenthesizedExpression:
3183 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003184
3185 case Sema::PCC_LocalDeclarationSpecifiers:
3186 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003187 }
David Blaikie8a40f702012-01-17 06:56:22 +00003188
3189 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003190}
3191
Douglas Gregorac322ec2010-08-27 21:18:54 +00003192/// \brief If we're in a C++ virtual member function, add completion results
3193/// that invoke the functions we override, since it's common to invoke the
3194/// overridden function as well as adding new functionality.
3195///
3196/// \param S The semantic analysis object for which we are generating results.
3197///
3198/// \param InContext This context in which the nested-name-specifier preceding
3199/// the code-completion point
3200static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3201 ResultBuilder &Results) {
3202 // Look through blocks.
3203 DeclContext *CurContext = S.CurContext;
3204 while (isa<BlockDecl>(CurContext))
3205 CurContext = CurContext->getParent();
3206
3207
3208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3209 if (!Method || !Method->isVirtual())
3210 return;
3211
3212 // We need to have names for all of the parameters, if we're going to
3213 // generate a forwarding call.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003214 for (auto P : Method->params())
3215 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003216 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003217
Douglas Gregor75acd922011-09-27 23:30:47 +00003218 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003219 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3220 MEnd = Method->end_overridden_methods();
3221 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003222 CodeCompletionBuilder Builder(Results.getAllocator(),
3223 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003224 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003225 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3226 continue;
3227
3228 // If we need a nested-name-specifier, add one now.
3229 if (!InContext) {
3230 NestedNameSpecifier *NNS
3231 = getRequiredQualification(S.Context, CurContext,
3232 Overridden->getDeclContext());
3233 if (NNS) {
3234 std::string Str;
3235 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003236 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003237 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003238 }
3239 } else if (!InContext->Equals(Overridden->getDeclContext()))
3240 continue;
3241
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003242 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003243 Overridden->getNameAsString()));
3244 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003245 bool FirstParam = true;
Aaron Ballman43b68be2014-03-07 17:50:17 +00003246 for (auto P : Method->params()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003247 if (FirstParam)
3248 FirstParam = false;
3249 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003250 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003251
Aaron Ballman43b68be2014-03-07 17:50:17 +00003252 Builder.AddPlaceholderChunk(
3253 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003254 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003255 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3256 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003257 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003258 CXCursor_CXXMethod,
3259 CXAvailability_Available,
3260 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003261 Results.Ignore(Overridden);
3262 }
3263}
3264
Douglas Gregor07f43572012-01-29 18:15:03 +00003265void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3266 ModuleIdPath Path) {
3267 typedef CodeCompletionResult Result;
3268 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003269 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003270 CodeCompletionContext::CCC_Other);
3271 Results.EnterNewScope();
3272
3273 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003274 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003275 typedef CodeCompletionResult Result;
3276 if (Path.empty()) {
3277 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003278 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003279 PP.getHeaderSearchInfo().collectAllModules(Modules);
3280 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3281 Builder.AddTypedTextChunk(
3282 Builder.getAllocator().CopyString(Modules[I]->Name));
3283 Results.AddResult(Result(Builder.TakeString(),
3284 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003285 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003286 Modules[I]->isAvailable()
3287 ? CXAvailability_Available
3288 : CXAvailability_NotAvailable));
3289 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003290 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003291 // Load the named module.
3292 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3293 Module::AllVisible,
3294 /*IsInclusionDirective=*/false);
3295 // Enumerate submodules.
3296 if (Mod) {
3297 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3298 SubEnd = Mod->submodule_end();
3299 Sub != SubEnd; ++Sub) {
3300
3301 Builder.AddTypedTextChunk(
3302 Builder.getAllocator().CopyString((*Sub)->Name));
3303 Results.AddResult(Result(Builder.TakeString(),
3304 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003305 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003306 (*Sub)->isAvailable()
3307 ? CXAvailability_Available
3308 : CXAvailability_NotAvailable));
3309 }
3310 }
3311 }
3312 Results.ExitScope();
3313 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3314 Results.data(),Results.size());
3315}
3316
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003317void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003318 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003319 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003320 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003321 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003322 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003323
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003324 // Determine how to filter results, e.g., so that the names of
3325 // values (functions, enumerators, function templates, etc.) are
3326 // only allowed where we can have an expression.
3327 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003328 case PCC_Namespace:
3329 case PCC_Class:
3330 case PCC_ObjCInterface:
3331 case PCC_ObjCImplementation:
3332 case PCC_ObjCInstanceVariableList:
3333 case PCC_Template:
3334 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003335 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003336 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003337 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3338 break;
3339
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003340 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003341 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003342 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003343 case PCC_ForInit:
3344 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003345 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003346 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3347 else
3348 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003349
David Blaikiebbafb8a2012-03-11 07:00:24 +00003350 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003351 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003352 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003353
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003354 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003355 // Unfiltered
3356 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003357 }
3358
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003359 // If we are in a C++ non-static member function, check the qualifiers on
3360 // the member function to filter/prioritize the results list.
3361 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3362 if (CurMethod->isInstance())
3363 Results.setObjectTypeQualifiers(
3364 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3365
Douglas Gregorc580c522010-01-14 01:09:38 +00003366 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003367 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3368 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003369
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003370 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003371 Results.ExitScope();
3372
Douglas Gregorce0e8562010-08-23 21:54:33 +00003373 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003374 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003375 case PCC_Expression:
3376 case PCC_Statement:
3377 case PCC_RecoveryInFunction:
3378 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00003379 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003380 break;
3381
3382 case PCC_Namespace:
3383 case PCC_Class:
3384 case PCC_ObjCInterface:
3385 case PCC_ObjCImplementation:
3386 case PCC_ObjCInstanceVariableList:
3387 case PCC_Template:
3388 case PCC_MemberTemplate:
3389 case PCC_ForInit:
3390 case PCC_Condition:
3391 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003392 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003393 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003394 }
3395
Douglas Gregor9eb77012009-11-07 00:00:49 +00003396 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003397 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003398
Douglas Gregor50832e02010-09-20 22:39:41 +00003399 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003400 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003401}
3402
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003403static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3404 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003405 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003406 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003407 bool IsSuper,
3408 ResultBuilder &Results);
3409
3410void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3411 bool AllowNonIdentifiers,
3412 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003413 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003414 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003415 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003416 AllowNestedNameSpecifiers
3417 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3418 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003419 Results.EnterNewScope();
3420
3421 // Type qualifiers can come after names.
3422 Results.AddResult(Result("const"));
3423 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003424 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003425 Results.AddResult(Result("restrict"));
3426
David Blaikiebbafb8a2012-03-11 07:00:24 +00003427 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003428 if (AllowNonIdentifiers) {
3429 Results.AddResult(Result("operator"));
3430 }
3431
3432 // Add nested-name-specifiers.
3433 if (AllowNestedNameSpecifiers) {
3434 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003435 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003436 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3437 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3438 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003439 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003440 }
3441 }
3442 Results.ExitScope();
3443
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003444 // If we're in a context where we might have an expression (rather than a
3445 // declaration), and what we've seen so far is an Objective-C type that could
3446 // be a receiver of a class message, this may be a class message send with
3447 // the initial opening bracket '[' missing. Add appropriate completions.
3448 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003449 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003450 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003451 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3452 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003453 !DS.isTypeAltiVecVector() &&
3454 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003455 (S->getFlags() & Scope::DeclScope) != 0 &&
3456 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3457 Scope::FunctionPrototypeScope |
3458 Scope::AtCatchScope)) == 0) {
3459 ParsedType T = DS.getRepAsType();
3460 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003461 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003462 }
3463
Douglas Gregor56ccce02010-08-24 04:59:56 +00003464 // Note that we intentionally suppress macro results here, since we do not
3465 // encourage using macros to produce the names of entities.
3466
Douglas Gregor0ac41382010-09-23 23:01:17 +00003467 HandleCodeCompleteResults(this, CodeCompleter,
3468 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003469 Results.data(), Results.size());
3470}
3471
Douglas Gregor68762e72010-08-23 21:17:50 +00003472struct Sema::CodeCompleteExpressionData {
3473 CodeCompleteExpressionData(QualType PreferredType = QualType())
3474 : PreferredType(PreferredType), IntegralConstantExpression(false),
3475 ObjCCollection(false) { }
3476
3477 QualType PreferredType;
3478 bool IntegralConstantExpression;
3479 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003480 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003481};
3482
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003483/// \brief Perform code-completion in an expression context when we know what
3484/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003485void Sema::CodeCompleteExpression(Scope *S,
3486 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003487 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003488 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003489 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003490 if (Data.ObjCCollection)
3491 Results.setFilter(&ResultBuilder::IsObjCCollection);
3492 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003493 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003494 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003495 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3496 else
3497 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003498
3499 if (!Data.PreferredType.isNull())
3500 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3501
3502 // Ignore any declarations that we were told that we don't care about.
3503 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3504 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003505
3506 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003507 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3508 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003509
3510 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003511 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003512 Results.ExitScope();
3513
Douglas Gregor55b037b2010-07-08 20:55:51 +00003514 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003515 if (!Data.PreferredType.isNull())
3516 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3517 || Data.PreferredType->isMemberPointerType()
3518 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003519
Douglas Gregorce0e8562010-08-23 21:54:33 +00003520 if (S->getFnParent() &&
3521 !Data.ObjCCollection &&
3522 !Data.IntegralConstantExpression)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003524
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003525 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003526 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003527 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003528 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3529 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003530 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003531}
3532
Douglas Gregoreda7e542010-09-18 01:28:11 +00003533void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3534 if (E.isInvalid())
3535 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003536 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003537 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003538}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003539
Douglas Gregorb888acf2010-12-09 23:01:55 +00003540/// \brief The set of properties that have already been added, referenced by
3541/// property name.
3542typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3543
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003544/// \brief Retrieve the container definition, if any?
3545static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3546 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3547 if (Interface->hasDefinition())
3548 return Interface->getDefinition();
3549
3550 return Interface;
3551 }
3552
3553 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3554 if (Protocol->hasDefinition())
3555 return Protocol->getDefinition();
3556
3557 return Protocol;
3558 }
3559 return Container;
3560}
3561
Douglas Gregorc3425b12015-07-07 06:20:19 +00003562static void AddObjCProperties(const CodeCompletionContext &CCContext,
3563 ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003564 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003565 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003566 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003567 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003568 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003569 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003570
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003571 // Retrieve the definition.
3572 Container = getContainerDef(Container);
3573
Douglas Gregor9291bad2009-11-18 01:29:26 +00003574 // Add properties in this container.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003575 for (const auto *P : Container->properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003576 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003577 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003578 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003579
Douglas Gregor95147142011-05-05 15:50:42 +00003580 // Add nullary methods
3581 if (AllowNullaryMethods) {
3582 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003583 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003584 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003585 if (M->getSelector().isUnarySelector())
3586 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003587 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003588 CodeCompletionBuilder Builder(Results.getAllocator(),
3589 Results.getCodeCompletionTUInfo());
Douglas Gregorc3425b12015-07-07 06:20:19 +00003590 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3591 Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003592 Builder.AddTypedTextChunk(
3593 Results.getAllocator().CopyString(Name->getName()));
3594
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003595 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003596 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003597 CurContext);
3598 }
3599 }
3600 }
3601
3602
Douglas Gregor9291bad2009-11-18 01:29:26 +00003603 // Add properties in referenced protocols.
3604 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003605 for (auto *P : Protocol->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003606 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3607 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003608 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003609 if (AllowCategories) {
3610 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003611 for (auto *Cat : IFace->known_categories())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003612 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3613 CurContext, AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003614 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003615
Douglas Gregor9291bad2009-11-18 01:29:26 +00003616 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003617 for (auto *I : IFace->all_referenced_protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003618 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3619 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003620
3621 // Look in the superclass.
3622 if (IFace->getSuperClass())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003623 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003624 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003625 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003626 } else if (const ObjCCategoryDecl *Category
3627 = dyn_cast<ObjCCategoryDecl>(Container)) {
3628 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003629 for (auto *P : Category->protocols())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003630 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3631 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003632 }
3633}
3634
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003635void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003636 SourceLocation OpLoc,
3637 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003638 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003639 return;
3640
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003641 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3642 if (ConvertedBase.isInvalid())
3643 return;
3644 Base = ConvertedBase.get();
3645
John McCall276321a2010-08-25 06:19:51 +00003646 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003647
Douglas Gregor2436e712009-09-17 21:32:03 +00003648 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003649
3650 if (IsArrow) {
3651 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3652 BaseType = Ptr->getPointeeType();
3653 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003654 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003655 else
3656 return;
3657 }
3658
Douglas Gregor21325842011-07-07 16:03:39 +00003659 enum CodeCompletionContext::Kind contextKind;
3660
3661 if (IsArrow) {
3662 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3663 }
3664 else {
3665 if (BaseType->isObjCObjectPointerType() ||
3666 BaseType->isObjCObjectOrInterfaceType()) {
3667 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3668 }
3669 else {
3670 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3671 }
3672 }
Douglas Gregorc3425b12015-07-07 06:20:19 +00003673
3674 CodeCompletionContext CCContext(contextKind, BaseType);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003675 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003676 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00003677 CCContext,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003678 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003679 Results.EnterNewScope();
3680 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003681 // Indicate that we are performing a member access, and the cv-qualifiers
3682 // for the base object type.
3683 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3684
Douglas Gregor9291bad2009-11-18 01:29:26 +00003685 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003686 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003687 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003688 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3689 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003690
David Blaikiebbafb8a2012-03-11 07:00:24 +00003691 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003692 if (!Results.empty()) {
3693 // The "template" keyword can follow "->" or "." in the grammar.
3694 // However, we only want to suggest the template keyword if something
3695 // is dependent.
3696 bool IsDependent = BaseType->isDependentType();
3697 if (!IsDependent) {
3698 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003699 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003700 IsDependent = Ctx->isDependentContext();
3701 break;
3702 }
3703 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003704
Douglas Gregor9291bad2009-11-18 01:29:26 +00003705 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003706 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003707 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003708 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003709 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3710 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003711 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003712
3713 // Add property results based on our interface.
3714 const ObjCObjectPointerType *ObjCPtr
3715 = BaseType->getAsObjCInterfacePointerType();
3716 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregorc3425b12015-07-07 06:20:19 +00003717 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
Douglas Gregor95147142011-05-05 15:50:42 +00003718 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003719 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003720
3721 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003722 for (auto *I : ObjCPtr->quals())
Douglas Gregorc3425b12015-07-07 06:20:19 +00003723 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3724 CurContext, AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003725 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003726 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003727 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003728 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003729 if (const ObjCObjectPointerType *ObjCPtr
3730 = BaseType->getAs<ObjCObjectPointerType>())
3731 Class = ObjCPtr->getInterfaceDecl();
3732 else
John McCall8b07ec22010-05-15 11:32:37 +00003733 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003734
3735 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003736 if (Class) {
3737 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3738 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003739 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3740 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003741 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003742 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003743
3744 // FIXME: How do we cope with isa?
3745
3746 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003747
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003748 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003749 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003750 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003751 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003752}
3753
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003754void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3755 if (!CodeCompleter)
3756 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003757
3758 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003759 enum CodeCompletionContext::Kind ContextKind
3760 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003761 switch ((DeclSpec::TST)TagSpec) {
3762 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003763 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003764 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003765 break;
3766
3767 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003768 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003769 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003770 break;
3771
3772 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003773 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003774 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003775 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003776 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003777 break;
3778
3779 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003780 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003781 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003782
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003783 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3784 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003785 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003786
3787 // First pass: look for tags.
3788 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003789 LookupVisibleDecls(S, LookupTagName, Consumer,
3790 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003791
Douglas Gregor39982192010-08-15 06:18:01 +00003792 if (CodeCompleter->includeGlobals()) {
3793 // Second pass: look for nested name specifiers.
3794 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3795 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3796 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003797
Douglas Gregor0ac41382010-09-23 23:01:17 +00003798 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003799 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003800}
3801
Douglas Gregor28c78432010-08-27 17:35:51 +00003802void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003803 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003804 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003805 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003806 Results.EnterNewScope();
3807 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3808 Results.AddResult("const");
3809 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3810 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003811 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003812 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3813 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003814 if (getLangOpts().C11 &&
3815 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3816 Results.AddResult("_Atomic");
Douglas Gregor28c78432010-08-27 17:35:51 +00003817 Results.ExitScope();
3818 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003819 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003820 Results.data(), Results.size());
3821}
3822
Douglas Gregord328d572009-09-21 18:10:23 +00003823void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003824 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003825 return;
John McCall5939b162011-08-06 07:30:58 +00003826
John McCallaab3e412010-08-25 08:40:02 +00003827 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003828 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3829 if (!type->isEnumeralType()) {
3830 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003831 Data.IntegralConstantExpression = true;
3832 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003833 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003834 }
Douglas Gregord328d572009-09-21 18:10:23 +00003835
3836 // Code-complete the cases of a switch statement over an enumeration type
3837 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003838 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003839 if (EnumDecl *Def = Enum->getDefinition())
3840 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003841
3842 // Determine which enumerators we have already seen in the switch statement.
3843 // FIXME: Ideally, we would also be able to look *past* the code-completion
3844 // token, in case we are code-completing in the middle of the switch and not
3845 // at the end. However, we aren't able to do so at the moment.
3846 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003847 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003848 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3849 SC = SC->getNextSwitchCase()) {
3850 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3851 if (!Case)
3852 continue;
3853
3854 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3856 if (EnumConstantDecl *Enumerator
3857 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3858 // We look into the AST of the case statement to determine which
3859 // enumerator was named. Alternatively, we could compute the value of
3860 // the integral constant expression, then compare it against the
3861 // values of each enumerator. However, value-based approach would not
3862 // work as well with C++ templates where enumerators declared within a
3863 // template are type- and value-dependent.
3864 EnumeratorsSeen.insert(Enumerator);
3865
Douglas Gregorf2510672009-09-21 19:57:38 +00003866 // If this is a qualified-id, keep track of the nested-name-specifier
3867 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003868 //
3869 // switch (TagD.getKind()) {
3870 // case TagDecl::TK_enum:
3871 // break;
3872 // case XXX
3873 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003874 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003875 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3876 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003877 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003878 }
3879 }
3880
David Blaikiebbafb8a2012-03-11 07:00:24 +00003881 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003882 // If there are no prior enumerators in C++, check whether we have to
3883 // qualify the names of the enumerators that we suggest, because they
3884 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003885 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003886 }
3887
Douglas Gregord328d572009-09-21 18:10:23 +00003888 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003889 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003890 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003891 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003892 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003893 for (auto *E : Enum->enumerators()) {
3894 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003895 continue;
3896
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003897 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003898 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003899 }
3900 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003901
Douglas Gregor21325842011-07-07 16:03:39 +00003902 //We need to make sure we're setting the right context,
3903 //so only say we include macros if the code completer says we do
3904 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3905 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003906 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003907 kind = CodeCompletionContext::CCC_OtherWithMacros;
3908 }
3909
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003910 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003911 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003912 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003913}
3914
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003915static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003916 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003917 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003918
3919 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003920 if (!Args[I])
3921 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003922
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003923 return false;
3924}
3925
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003926typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3927
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003928static void mergeCandidatesWithResults(Sema &SemaRef,
3929 SmallVectorImpl<ResultCandidate> &Results,
3930 OverloadCandidateSet &CandidateSet,
3931 SourceLocation Loc) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003932 if (!CandidateSet.empty()) {
3933 // Sort the overload candidate set by placing the best overloads first.
3934 std::stable_sort(
3935 CandidateSet.begin(), CandidateSet.end(),
3936 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3937 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3938 });
3939
3940 // Add the remaining viable overload candidates as code-completion results.
3941 for (auto &Candidate : CandidateSet)
3942 if (Candidate.Viable)
3943 Results.push_back(ResultCandidate(Candidate.Function));
3944 }
3945}
3946
3947/// \brief Get the type of the Nth parameter from a given set of overload
3948/// candidates.
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003949static QualType getParamType(Sema &SemaRef,
3950 ArrayRef<ResultCandidate> Candidates,
3951 unsigned N) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003952
3953 // Given the overloads 'Candidates' for a function call matching all arguments
3954 // up to N, return the type of the Nth parameter if it is the same for all
3955 // overload candidates.
3956 QualType ParamType;
3957 for (auto &Candidate : Candidates) {
3958 if (auto FType = Candidate.getFunctionType())
3959 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3960 if (N < Proto->getNumParams()) {
3961 if (ParamType.isNull())
3962 ParamType = Proto->getParamType(N);
3963 else if (!SemaRef.Context.hasSameUnqualifiedType(
3964 ParamType.getNonReferenceType(),
3965 Proto->getParamType(N).getNonReferenceType()))
3966 // Otherwise return a default-constructed QualType.
3967 return QualType();
3968 }
3969 }
3970
3971 return ParamType;
3972}
3973
Francisco Lopes da Silva8cafefa2015-01-29 05:54:59 +00003974static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3975 MutableArrayRef<ResultCandidate> Candidates,
3976 unsigned CurrentArg,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003977 bool CompleteExpressionWithCurrentArg = true) {
3978 QualType ParamType;
3979 if (CompleteExpressionWithCurrentArg)
3980 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3981
3982 if (ParamType.isNull())
3983 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3984 else
3985 SemaRef.CodeCompleteExpression(S, ParamType);
3986
3987 if (!Candidates.empty())
3988 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3989 Candidates.data(),
3990 Candidates.size());
3991}
3992
3993void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003994 if (!CodeCompleter)
3995 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003996
3997 // When we're code-completing for a call, we fall back to ordinary
3998 // name code-completion whenever we can't produce specific
3999 // results. We may want to revisit this strategy in the future,
4000 // e.g., by merging the two kinds of results.
4001
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004002 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00004003
Douglas Gregorcabea402009-09-22 15:41:20 +00004004 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004005 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4006 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004007 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00004008 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00004009 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004010
John McCall57500772009-12-16 12:17:52 +00004011 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00004012 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00004013 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00004014
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004015 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00004016
John McCall57500772009-12-16 12:17:52 +00004017 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004018 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004019 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004020 /*PartialOverloading=*/true);
4021 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4022 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4023 if (UME->hasExplicitTemplateArgs()) {
4024 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4025 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00004026 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004027 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4028 ArgExprs.append(Args.begin(), Args.end());
4029 UnresolvedSet<8> Decls;
4030 Decls.append(UME->decls_begin(), UME->decls_end());
4031 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4032 /*SuppressUsedConversions=*/false,
4033 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004034 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004035 FunctionDecl *FD = nullptr;
4036 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4037 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4038 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4039 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004040 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00004041 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004042 !FD->getType()->getAs<FunctionProtoType>())
4043 Results.push_back(ResultCandidate(FD));
4044 else
4045 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4046 Args, CandidateSet,
4047 /*SuppressUsedConversions=*/false,
4048 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004049
4050 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4051 // If expression's type is CXXRecordDecl, it may overload the function
4052 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004053 // A complete type is needed to lookup for member function call operators.
Francisco Lopes da Silva1a4f8552015-01-25 17:00:47 +00004054 if (!RequireCompleteType(Loc, NakedFn->getType(), 0)) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00004055 DeclarationName OpName = Context.DeclarationNames
4056 .getCXXOperatorName(OO_Call);
4057 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4058 LookupQualifiedName(R, DC);
4059 R.suppressDiagnostics();
4060 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4061 ArgExprs.append(Args.begin(), Args.end());
4062 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4063 /*ExplicitArgs=*/nullptr,
4064 /*SuppressUsedConversions=*/false,
4065 /*PartialOverloading=*/true);
4066 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004067 } else {
4068 // Lastly we check whether expression's type is function pointer or
4069 // function.
4070 QualType T = NakedFn->getType();
4071 if (!T->getPointeeType().isNull())
4072 T = T->getPointeeType();
4073
4074 if (auto FP = T->getAs<FunctionProtoType>()) {
4075 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004076 /*PartialOverloading=*/true) ||
4077 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004078 Results.push_back(ResultCandidate(FP));
4079 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004080 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004081 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004082 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004083 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004084
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004085 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4086 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4087 !CandidateSet.empty());
4088}
4089
4090void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4091 ArrayRef<Expr *> Args) {
4092 if (!CodeCompleter)
4093 return;
4094
4095 // A complete type is needed to lookup for constructors.
4096 if (RequireCompleteType(Loc, Type, 0))
4097 return;
4098
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004099 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4100 if (!RD) {
4101 CodeCompleteExpression(S, Type);
4102 return;
4103 }
4104
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004105 // FIXME: Provide support for member initializers.
4106 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004107
4108 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4109
Argyrios Kyrtzidisee1d76f2015-03-13 07:39:30 +00004110 for (auto C : LookupConstructors(RD)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004111 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4112 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4113 Args, CandidateSet,
4114 /*SuppressUsedConversions=*/false,
4115 /*PartialOverloading=*/true);
4116 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4117 AddTemplateOverloadCandidate(FTD,
4118 DeclAccessPair::make(FTD, C->getAccess()),
4119 /*ExplicitTemplateArgs=*/nullptr,
4120 Args, CandidateSet,
4121 /*SuppressUsedConversions=*/false,
4122 /*PartialOverloading=*/true);
4123 }
4124 }
4125
4126 SmallVector<ResultCandidate, 8> Results;
4127 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4128 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004129}
4130
John McCall48871652010-08-21 09:40:31 +00004131void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4132 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004133 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004134 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004135 return;
4136 }
4137
4138 CodeCompleteExpression(S, VD->getType());
4139}
4140
4141void Sema::CodeCompleteReturn(Scope *S) {
4142 QualType ResultType;
4143 if (isa<BlockDecl>(CurContext)) {
4144 if (BlockScopeInfo *BSI = getCurBlock())
4145 ResultType = BSI->ReturnType;
4146 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004147 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004148 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004149 ResultType = Method->getReturnType();
4150
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004151 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004152 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004153 else
4154 CodeCompleteExpression(S, ResultType);
4155}
4156
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004157void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004158 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004159 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004160 mapCodeCompletionContext(*this, PCC_Statement));
4161 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4162 Results.EnterNewScope();
4163
4164 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4165 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4166 CodeCompleter->includeGlobals());
4167
4168 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4169
4170 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004171 CodeCompletionBuilder Builder(Results.getAllocator(),
4172 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004173 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004174 if (Results.includeCodePatterns()) {
4175 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4176 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4177 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4178 Builder.AddPlaceholderChunk("statements");
4179 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4180 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4181 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004182 Results.AddResult(Builder.TakeString());
4183
4184 // "else if" block
4185 Builder.AddTypedTextChunk("else");
4186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4187 Builder.AddTextChunk("if");
4188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4189 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004190 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004191 Builder.AddPlaceholderChunk("condition");
4192 else
4193 Builder.AddPlaceholderChunk("expression");
4194 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004195 if (Results.includeCodePatterns()) {
4196 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4197 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4198 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4199 Builder.AddPlaceholderChunk("statements");
4200 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4201 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4202 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004203 Results.AddResult(Builder.TakeString());
4204
4205 Results.ExitScope();
4206
4207 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004208 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004209
4210 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004211 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004212
4213 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4214 Results.data(),Results.size());
4215}
4216
Richard Trieu2bd04012011-09-09 02:00:50 +00004217void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004218 if (LHS)
4219 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4220 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004221 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004222}
4223
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004224void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004225 bool EnteringContext) {
4226 if (!SS.getScopeRep() || !CodeCompleter)
4227 return;
4228
Douglas Gregor3545ff42009-09-21 16:56:56 +00004229 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4230 if (!Ctx)
4231 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004232
4233 // Try to instantiate any non-dependent declaration contexts before
4234 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004235 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004236 return;
4237
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004238 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004239 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004240 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004241 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004242
Douglas Gregor3545ff42009-09-21 16:56:56 +00004243 // The "template" keyword can follow "::" in the grammar, but only
4244 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004245 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004246 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004247 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004248
4249 // Add calls to overridden virtual functions, if there are any.
4250 //
4251 // FIXME: This isn't wonderful, because we don't know whether we're actually
4252 // in a context that permits expressions. This is a general issue with
4253 // qualified-id completions.
4254 if (!EnteringContext)
4255 MaybeAddOverrideCalls(*this, Ctx, Results);
4256 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004257
Douglas Gregorac322ec2010-08-27 21:18:54 +00004258 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4259 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4260
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004261 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004262 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004263 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004264}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004265
4266void Sema::CodeCompleteUsing(Scope *S) {
4267 if (!CodeCompleter)
4268 return;
4269
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004270 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004271 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004272 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4273 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004274 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004275
4276 // If we aren't in class scope, we could see the "namespace" keyword.
4277 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004278 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004279
4280 // After "using", we can see anything that would start a
4281 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004282 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004283 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4284 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004285 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004286
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004287 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004288 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004289 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004290}
4291
4292void Sema::CodeCompleteUsingDirective(Scope *S) {
4293 if (!CodeCompleter)
4294 return;
4295
Douglas Gregor3545ff42009-09-21 16:56:56 +00004296 // After "using namespace", we expect to see a namespace name or namespace
4297 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004298 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004299 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004300 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004301 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004302 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004303 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004304 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4305 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004306 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004307 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004308 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004309 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004310}
4311
4312void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4313 if (!CodeCompleter)
4314 return;
4315
Ted Kremenekc37877d2013-10-08 17:08:03 +00004316 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004317 if (!S->getParent())
4318 Ctx = Context.getTranslationUnitDecl();
4319
Douglas Gregor0ac41382010-09-23 23:01:17 +00004320 bool SuppressedGlobalResults
4321 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4322
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004323 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004324 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004325 SuppressedGlobalResults
4326 ? CodeCompletionContext::CCC_Namespace
4327 : CodeCompletionContext::CCC_Other,
4328 &ResultBuilder::IsNamespace);
4329
4330 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004331 // We only want to see those namespaces that have already been defined
4332 // within this scope, because its likely that the user is creating an
4333 // extended namespace declaration. Keep track of the most recent
4334 // definition of each namespace.
4335 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4336 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4337 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4338 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004339 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004340
4341 // Add the most recent definition (or extended definition) of each
4342 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004343 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004344 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004345 NS = OrigToLatest.begin(),
4346 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004347 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004348 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004349 NS->second, Results.getBasePriority(NS->second),
4350 nullptr),
4351 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004352 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004353 }
4354
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004355 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004356 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004357 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004358}
4359
4360void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4361 if (!CodeCompleter)
4362 return;
4363
Douglas Gregor3545ff42009-09-21 16:56:56 +00004364 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004365 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004366 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004367 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004368 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004369 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004370 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4371 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004372 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004373 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004374 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004375}
4376
Douglas Gregorc811ede2009-09-18 20:05:18 +00004377void Sema::CodeCompleteOperatorName(Scope *S) {
4378 if (!CodeCompleter)
4379 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004380
John McCall276321a2010-08-25 06:19:51 +00004381 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004383 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004384 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004385 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004386 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004387
Douglas Gregor3545ff42009-09-21 16:56:56 +00004388 // Add the names of overloadable operators.
4389#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4390 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004391 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004392#include "clang/Basic/OperatorKinds.def"
4393
4394 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004395 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004396 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004397 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4398 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004399
4400 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004401 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004402 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004403
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004404 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004405 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004406 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004407}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004408
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004409void Sema::CodeCompleteConstructorInitializer(
4410 Decl *ConstructorD,
4411 ArrayRef <CXXCtorInitializer *> Initializers) {
Douglas Gregor75acd922011-09-27 23:30:47 +00004412 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004413 CXXConstructorDecl *Constructor
4414 = static_cast<CXXConstructorDecl *>(ConstructorD);
4415 if (!Constructor)
4416 return;
4417
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004418 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004419 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004420 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004421 Results.EnterNewScope();
4422
4423 // Fill in any already-initialized fields or base classes.
4424 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4425 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004426 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004427 if (Initializers[I]->isBaseInitializer())
4428 InitializedBases.insert(
4429 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4430 else
Francois Pichetd583da02010-12-04 09:14:42 +00004431 InitializedFields.insert(cast<FieldDecl>(
4432 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004433 }
4434
4435 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004436 CodeCompletionBuilder Builder(Results.getAllocator(),
4437 Results.getCodeCompletionTUInfo());
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004438 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004439 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004440 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004441 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4442 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004443 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004444 = !Initializers.empty() &&
4445 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004446 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004447 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004448 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004449 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004450
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004451 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004452 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004453 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004454 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4455 Builder.AddPlaceholderChunk("args");
4456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4457 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004458 SawLastInitializer? CCP_NextInitializer
4459 : CCP_MemberDeclaration));
4460 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004461 }
4462
4463 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004464 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004465 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4466 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004467 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004468 = !Initializers.empty() &&
4469 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004470 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004471 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004472 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004473 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004474
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004475 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004476 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004477 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004478 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4479 Builder.AddPlaceholderChunk("args");
4480 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4481 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004482 SawLastInitializer? CCP_NextInitializer
4483 : CCP_MemberDeclaration));
4484 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004485 }
4486
4487 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004488 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004489 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4490 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004491 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004492 = !Initializers.empty() &&
4493 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004494 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004495 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004496 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004497
4498 if (!Field->getDeclName())
4499 continue;
4500
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004501 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004502 Field->getIdentifier()->getName()));
4503 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4504 Builder.AddPlaceholderChunk("args");
4505 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4506 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004507 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004508 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004509 CXCursor_MemberRef,
4510 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004511 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004512 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004513 }
4514 Results.ExitScope();
4515
Douglas Gregor0ac41382010-09-23 23:01:17 +00004516 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004517 Results.data(), Results.size());
4518}
4519
Douglas Gregord8c61782012-02-15 15:34:24 +00004520/// \brief Determine whether this scope denotes a namespace.
4521static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004522 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004523 if (!DC)
4524 return false;
4525
4526 return DC->isFileContext();
4527}
4528
4529void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4530 bool AfterAmpersand) {
4531 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004532 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004533 CodeCompletionContext::CCC_Other);
4534 Results.EnterNewScope();
4535
4536 // Note what has already been captured.
4537 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4538 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004539 for (const auto &C : Intro.Captures) {
4540 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004541 IncludedThis = true;
4542 continue;
4543 }
4544
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004545 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004546 }
4547
4548 // Look for other capturable variables.
4549 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004550 for (const auto *D : S->decls()) {
4551 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004552 if (!Var ||
4553 !Var->hasLocalStorage() ||
4554 Var->hasAttr<BlocksAttr>())
4555 continue;
4556
David Blaikie82e95a32014-11-19 07:49:47 +00004557 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004558 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004559 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004560 }
4561 }
4562
4563 // Add 'this', if it would be valid.
4564 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4565 addThisCompletion(*this, Results);
4566
4567 Results.ExitScope();
4568
4569 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4570 Results.data(), Results.size());
4571}
4572
James Dennett596e4752012-06-14 03:11:41 +00004573/// Macro that optionally prepends an "@" to the string literal passed in via
4574/// Keyword, depending on whether NeedAt is true or false.
4575#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4576
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004577static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004578 ResultBuilder &Results,
4579 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004580 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004581 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004582 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004583
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004584 CodeCompletionBuilder Builder(Results.getAllocator(),
4585 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004586 if (LangOpts.ObjC2) {
4587 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004588 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004589 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4590 Builder.AddPlaceholderChunk("property");
4591 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004592
4593 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004594 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
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}
4600
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004601static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004602 ResultBuilder &Results,
4603 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004604 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004605
4606 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004607 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004608
4609 if (LangOpts.ObjC2) {
4610 // @property
James Dennett596e4752012-06-14 03:11:41 +00004611 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004612
4613 // @required
James Dennett596e4752012-06-14 03:11:41 +00004614 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004615
4616 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004617 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004618 }
4619}
4620
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004621static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004622 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004623 CodeCompletionBuilder Builder(Results.getAllocator(),
4624 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004625
4626 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004627 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4629 Builder.AddPlaceholderChunk("name");
4630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004631
Douglas Gregorf4c33342010-05-28 00:22:41 +00004632 if (Results.includeCodePatterns()) {
4633 // @interface name
4634 // FIXME: Could introduce the whole pattern, including superclasses and
4635 // such.
James Dennett596e4752012-06-14 03:11:41 +00004636 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004637 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4638 Builder.AddPlaceholderChunk("class");
4639 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004640
Douglas Gregorf4c33342010-05-28 00:22:41 +00004641 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004642 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004643 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4644 Builder.AddPlaceholderChunk("protocol");
4645 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004646
4647 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004648 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4650 Builder.AddPlaceholderChunk("class");
4651 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004652 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004653
4654 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004655 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4657 Builder.AddPlaceholderChunk("alias");
4658 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4659 Builder.AddPlaceholderChunk("class");
4660 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004661
4662 if (Results.getSema().getLangOpts().Modules) {
4663 // @import name
4664 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4666 Builder.AddPlaceholderChunk("module");
4667 Results.AddResult(Result(Builder.TakeString()));
4668 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004669}
4670
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004671void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004672 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004673 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004674 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004675 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004676 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004677 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004678 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004679 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004680 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004681 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004682 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004683 HandleCodeCompleteResults(this, CodeCompleter,
4684 CodeCompletionContext::CCC_Other,
4685 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004686}
4687
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004688static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004689 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004690 CodeCompletionBuilder Builder(Results.getAllocator(),
4691 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004692
4693 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004694 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004695 if (Results.getSema().getLangOpts().CPlusPlus ||
4696 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004697 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004698 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004699 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004700 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4701 Builder.AddPlaceholderChunk("type-name");
4702 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4703 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004704
4705 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004706 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004707 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004708 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4709 Builder.AddPlaceholderChunk("protocol-name");
4710 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4711 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004712
4713 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004714 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004715 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004716 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4717 Builder.AddPlaceholderChunk("selector");
4718 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4719 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004720
4721 // @"string"
4722 Builder.AddResultTypeChunk("NSString *");
4723 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4724 Builder.AddPlaceholderChunk("string");
4725 Builder.AddTextChunk("\"");
4726 Results.AddResult(Result(Builder.TakeString()));
4727
Douglas Gregor951de302012-07-17 23:24:47 +00004728 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004729 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004730 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004731 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004732 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4733 Results.AddResult(Result(Builder.TakeString()));
4734
Douglas Gregor951de302012-07-17 23:24:47 +00004735 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004736 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004737 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004738 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004739 Builder.AddChunk(CodeCompletionString::CK_Colon);
4740 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4741 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004742 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4743 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004744
Douglas Gregor951de302012-07-17 23:24:47 +00004745 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004746 Builder.AddResultTypeChunk("id");
4747 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004748 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4750 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004751}
4752
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004753static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004754 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004755 CodeCompletionBuilder Builder(Results.getAllocator(),
4756 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004757
Douglas Gregorf4c33342010-05-28 00:22:41 +00004758 if (Results.includeCodePatterns()) {
4759 // @try { statements } @catch ( declaration ) { statements } @finally
4760 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004761 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004762 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4763 Builder.AddPlaceholderChunk("statements");
4764 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4765 Builder.AddTextChunk("@catch");
4766 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4767 Builder.AddPlaceholderChunk("parameter");
4768 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4769 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4770 Builder.AddPlaceholderChunk("statements");
4771 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4772 Builder.AddTextChunk("@finally");
4773 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4774 Builder.AddPlaceholderChunk("statements");
4775 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004777 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004778
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004779 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004780 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4782 Builder.AddPlaceholderChunk("expression");
4783 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004784
Douglas Gregorf4c33342010-05-28 00:22:41 +00004785 if (Results.includeCodePatterns()) {
4786 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004787 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004788 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4790 Builder.AddPlaceholderChunk("expression");
4791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4792 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4793 Builder.AddPlaceholderChunk("statements");
4794 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4795 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004796 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004797}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004798
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004799static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004800 ResultBuilder &Results,
4801 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004802 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004803 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4804 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4805 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004806 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004807 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004808}
4809
4810void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004811 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004812 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004813 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004814 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004815 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004816 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004817 HandleCodeCompleteResults(this, CodeCompleter,
4818 CodeCompletionContext::CCC_Other,
4819 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004820}
4821
4822void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004823 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004824 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004825 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004826 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004827 AddObjCStatementResults(Results, false);
4828 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004829 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004830 HandleCodeCompleteResults(this, CodeCompleter,
4831 CodeCompletionContext::CCC_Other,
4832 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004833}
4834
4835void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004836 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004837 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004838 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004839 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004840 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004841 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004842 HandleCodeCompleteResults(this, CodeCompleter,
4843 CodeCompletionContext::CCC_Other,
4844 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004845}
4846
Douglas Gregore6078da2009-11-19 00:14:45 +00004847/// \brief Determine whether the addition of the given flag to an Objective-C
4848/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004849static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004850 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004851 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004852 return true;
4853
Bill Wendling44426052012-12-20 19:22:21 +00004854 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004855
4856 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004857 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4858 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004859 return true;
4860
Jordan Rose53cb2f32012-08-20 20:01:13 +00004861 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004862 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004863 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004864 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004865 ObjCDeclSpec::DQ_PR_retain |
4866 ObjCDeclSpec::DQ_PR_strong |
4867 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004868 if (AssignCopyRetMask &&
4869 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004870 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004871 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004872 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004873 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4874 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004875 return true;
4876
4877 return false;
4878}
4879
Douglas Gregor36029f42009-11-18 23:08:07 +00004880void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004881 if (!CodeCompleter)
4882 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004883
Bill Wendling44426052012-12-20 19:22:21 +00004884 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004885
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004886 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004887 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004888 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004889 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004890 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004891 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004892 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004893 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004894 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004895 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4896 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004897 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004898 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004899 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004900 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004901 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004902 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004903 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004904 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004905 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004906 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004907 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004908 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004909
4910 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall3deb1ad2012-08-21 02:47:43 +00004911 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004912 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004913 Results.AddResult(CodeCompletionResult("weak"));
4914
Bill Wendling44426052012-12-20 19:22:21 +00004915 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004916 CodeCompletionBuilder Setter(Results.getAllocator(),
4917 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004918 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004919 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004920 Setter.AddPlaceholderChunk("method");
4921 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004922 }
Bill Wendling44426052012-12-20 19:22:21 +00004923 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004924 CodeCompletionBuilder Getter(Results.getAllocator(),
4925 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004926 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004927 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004928 Getter.AddPlaceholderChunk("method");
4929 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004930 }
Douglas Gregor86b42682015-06-19 18:27:52 +00004931 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4932 Results.AddResult(CodeCompletionResult("nonnull"));
4933 Results.AddResult(CodeCompletionResult("nullable"));
4934 Results.AddResult(CodeCompletionResult("null_unspecified"));
4935 Results.AddResult(CodeCompletionResult("null_resettable"));
4936 }
Steve Naroff936354c2009-10-08 21:55:05 +00004937 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004938 HandleCodeCompleteResults(this, CodeCompleter,
4939 CodeCompletionContext::CCC_Other,
4940 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004941}
Steve Naroffeae65032009-11-07 02:08:14 +00004942
James Dennettf1243872012-06-17 05:33:25 +00004943/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004944/// via code completion.
4945enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004946 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4947 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4948 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004949};
4950
Douglas Gregor67c692c2010-08-26 15:07:07 +00004951static bool isAcceptableObjCSelector(Selector Sel,
4952 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004953 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004954 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004955 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004956 if (NumSelIdents > Sel.getNumArgs())
4957 return false;
4958
4959 switch (WantKind) {
4960 case MK_Any: break;
4961 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4962 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4963 }
4964
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004965 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4966 return false;
4967
Douglas Gregor67c692c2010-08-26 15:07:07 +00004968 for (unsigned I = 0; I != NumSelIdents; ++I)
4969 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4970 return false;
4971
4972 return true;
4973}
4974
Douglas Gregorc8537c52009-11-19 07:41:15 +00004975static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4976 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004977 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004978 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004979 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004980 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004981}
Douglas Gregor1154e272010-09-16 16:06:31 +00004982
4983namespace {
4984 /// \brief A set of selectors, which is used to avoid introducing multiple
4985 /// completions with the same selector into the result set.
4986 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4987}
4988
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004989/// \brief Add all of the Objective-C methods in the given Objective-C
4990/// container to the set of results.
4991///
4992/// The container will be a class, protocol, category, or implementation of
4993/// any of the above. This mether will recurse to include methods from
4994/// the superclasses of classes along with their categories, protocols, and
4995/// implementations.
4996///
4997/// \param Container the container in which we'll look to find methods.
4998///
James Dennett596e4752012-06-14 03:11:41 +00004999/// \param WantInstanceMethods Whether to add instance methods (only); if
5000/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005001///
5002/// \param CurContext the context in which we're performing the lookup that
5003/// finds methods.
5004///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005005/// \param AllowSameLength Whether we allow a method to be added to the list
5006/// when it has the same number of parameters as we have selector identifiers.
5007///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005008/// \param Results the structure into which we'll add results.
5009static void AddObjCMethods(ObjCContainerDecl *Container,
5010 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00005011 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005012 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005013 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00005014 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005015 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00005016 ResultBuilder &Results,
5017 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00005018 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00005019 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00005020 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5021 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005022 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00005023 // The instance methods on the root class can be messaged via the
5024 // metaclass.
5025 if (M->isInstanceMethod() == WantInstanceMethods ||
5026 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00005027 // Check whether the selector identifiers we've been given are a
5028 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005029 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00005030 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00005031
David Blaikie82e95a32014-11-19 07:49:47 +00005032 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005033 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005034
5035 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005036 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00005037 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00005038 if (!InOriginalClass)
5039 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00005040 Results.MaybeAddResult(R, CurContext);
5041 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005042 }
5043
Douglas Gregorf37c9492010-09-16 15:34:59 +00005044 // Visit the protocols of protocols.
5045 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00005046 if (Protocol->hasDefinition()) {
5047 const ObjCList<ObjCProtocolDecl> &Protocols
5048 = Protocol->getReferencedProtocols();
5049 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5050 E = Protocols.end();
5051 I != E; ++I)
5052 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005053 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00005054 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00005055 }
5056
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00005057 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005058 return;
5059
5060 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00005061 for (auto *I : IFace->protocols())
5062 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005063 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005064
5065 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00005066 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005067 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005068 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005069 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005070
5071 // Add a categories protocol methods.
5072 const ObjCList<ObjCProtocolDecl> &Protocols
5073 = CatDecl->getReferencedProtocols();
5074 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5075 E = Protocols.end();
5076 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005077 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005078 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005079 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005080
5081 // Add methods in category implementations.
5082 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005083 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005084 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005085 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005086 }
5087
5088 // Add methods in superclass.
5089 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005090 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005091 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005092 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005093
5094 // Add methods in our implementation, if any.
5095 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005096 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005097 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005098 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005099}
5100
5101
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005102void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005103 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005104 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005105 if (!Class) {
5106 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005107 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005108 Class = Category->getClassInterface();
5109
5110 if (!Class)
5111 return;
5112 }
5113
5114 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005115 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005116 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005117 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005118 Results.EnterNewScope();
5119
Douglas Gregor1154e272010-09-16 16:06:31 +00005120 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005121 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005122 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005123 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005124 HandleCodeCompleteResults(this, CodeCompleter,
5125 CodeCompletionContext::CCC_Other,
5126 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005127}
5128
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005129void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005130 // Try to find the interface where setters might live.
5131 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005132 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005133 if (!Class) {
5134 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005135 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005136 Class = Category->getClassInterface();
5137
5138 if (!Class)
5139 return;
5140 }
5141
5142 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005143 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005144 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005145 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005146 Results.EnterNewScope();
5147
Douglas Gregor1154e272010-09-16 16:06:31 +00005148 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005149 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005150 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005151
5152 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005153 HandleCodeCompleteResults(this, CodeCompleter,
5154 CodeCompletionContext::CCC_Other,
5155 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005156}
5157
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005158void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5159 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005161 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005162 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005163 Results.EnterNewScope();
5164
5165 // Add context-sensitive, Objective-C parameter-passing keywords.
5166 bool AddedInOut = false;
5167 if ((DS.getObjCDeclQualifier() &
5168 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5169 Results.AddResult("in");
5170 Results.AddResult("inout");
5171 AddedInOut = true;
5172 }
5173 if ((DS.getObjCDeclQualifier() &
5174 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5175 Results.AddResult("out");
5176 if (!AddedInOut)
5177 Results.AddResult("inout");
5178 }
5179 if ((DS.getObjCDeclQualifier() &
5180 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5181 ObjCDeclSpec::DQ_Oneway)) == 0) {
5182 Results.AddResult("bycopy");
5183 Results.AddResult("byref");
5184 Results.AddResult("oneway");
5185 }
Douglas Gregor86b42682015-06-19 18:27:52 +00005186 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5187 Results.AddResult("nonnull");
5188 Results.AddResult("nullable");
5189 Results.AddResult("null_unspecified");
5190 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00005191
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005192 // If we're completing the return type of an Objective-C method and the
5193 // identifier IBAction refers to a macro, provide a completion item for
5194 // an action, e.g.,
5195 // IBAction)<#selector#>:(id)sender
5196 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
Richard Smith20e883e2015-04-29 23:20:19 +00005197 PP.isMacroDefined("IBAction")) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005198 CodeCompletionBuilder Builder(Results.getAllocator(),
5199 Results.getCodeCompletionTUInfo(),
5200 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005201 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005202 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005203 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005204 Builder.AddChunk(CodeCompletionString::CK_Colon);
5205 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005206 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005207 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005208 Builder.AddTextChunk("sender");
5209 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5210 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005211
5212 // If we're completing the return type, provide 'instancetype'.
5213 if (!IsParameter) {
5214 Results.AddResult(CodeCompletionResult("instancetype"));
5215 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005216
Douglas Gregor99fa2642010-08-24 01:06:58 +00005217 // Add various builtin type names and specifiers.
5218 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5219 Results.ExitScope();
5220
5221 // Add the various type names
5222 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5223 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5224 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5225 CodeCompleter->includeGlobals());
5226
5227 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005228 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005229
5230 HandleCodeCompleteResults(this, CodeCompleter,
5231 CodeCompletionContext::CCC_Type,
5232 Results.data(), Results.size());
5233}
5234
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005235/// \brief When we have an expression with type "id", we may assume
5236/// that it has some more-specific class type based on knowledge of
5237/// common uses of Objective-C. This routine returns that class type,
5238/// or NULL if no better result could be determined.
5239static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005240 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005241 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005242 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005243
5244 Selector Sel = Msg->getSelector();
5245 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005246 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005247
5248 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5249 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005250 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005251
5252 ObjCMethodDecl *Method = Msg->getMethodDecl();
5253 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005254 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005255
5256 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005257 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005258 switch (Msg->getReceiverKind()) {
5259 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005260 if (const ObjCObjectType *ObjType
5261 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5262 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005263 break;
5264
5265 case ObjCMessageExpr::Instance: {
5266 QualType T = Msg->getInstanceReceiver()->getType();
5267 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5268 IFace = Ptr->getInterfaceDecl();
5269 break;
5270 }
5271
5272 case ObjCMessageExpr::SuperInstance:
5273 case ObjCMessageExpr::SuperClass:
5274 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005275 }
5276
5277 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005278 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005279
5280 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5281 if (Method->isInstanceMethod())
5282 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5283 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005284 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005285 .Case("autorelease", IFace)
5286 .Case("copy", IFace)
5287 .Case("copyWithZone", IFace)
5288 .Case("mutableCopy", IFace)
5289 .Case("mutableCopyWithZone", IFace)
5290 .Case("awakeFromCoder", IFace)
5291 .Case("replacementObjectFromCoder", IFace)
5292 .Case("class", IFace)
5293 .Case("classForCoder", IFace)
5294 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005295 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005296
5297 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5298 .Case("new", IFace)
5299 .Case("alloc", IFace)
5300 .Case("allocWithZone", IFace)
5301 .Case("class", IFace)
5302 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005303 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005304}
5305
Douglas Gregor6fc04132010-08-27 15:10:57 +00005306// Add a special completion for a message send to "super", which fills in the
5307// most likely case of forwarding all of our arguments to the superclass
5308// function.
5309///
5310/// \param S The semantic analysis object.
5311///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005312/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005313/// the "super" keyword. Otherwise, we just need to provide the arguments.
5314///
5315/// \param SelIdents The identifiers in the selector that have already been
5316/// provided as arguments for a send to "super".
5317///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005318/// \param Results The set of results to augment.
5319///
5320/// \returns the Objective-C method declaration that would be invoked by
5321/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005322static ObjCMethodDecl *AddSuperSendCompletion(
5323 Sema &S, bool NeedSuperKeyword,
5324 ArrayRef<IdentifierInfo *> SelIdents,
5325 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005326 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5327 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005328 return nullptr;
5329
Douglas Gregor6fc04132010-08-27 15:10:57 +00005330 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5331 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005332 return nullptr;
5333
Douglas Gregor6fc04132010-08-27 15:10:57 +00005334 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005335 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005336 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5337 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005338 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5339 CurMethod->isInstanceMethod());
5340
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005341 // Check in categories or class extensions.
5342 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005343 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005344 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005345 CurMethod->isInstanceMethod())))
5346 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005347 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005348 }
5349 }
5350
Douglas Gregor6fc04132010-08-27 15:10:57 +00005351 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005352 return nullptr;
5353
Douglas Gregor6fc04132010-08-27 15:10:57 +00005354 // Check whether the superclass method has the same signature.
5355 if (CurMethod->param_size() != SuperMethod->param_size() ||
5356 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005357 return nullptr;
5358
Douglas Gregor6fc04132010-08-27 15:10:57 +00005359 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5360 CurPEnd = CurMethod->param_end(),
5361 SuperP = SuperMethod->param_begin();
5362 CurP != CurPEnd; ++CurP, ++SuperP) {
5363 // Make sure the parameter types are compatible.
5364 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5365 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005366 return nullptr;
5367
Douglas Gregor6fc04132010-08-27 15:10:57 +00005368 // Make sure we have a parameter name to forward!
5369 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005370 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005371 }
5372
5373 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005374 CodeCompletionBuilder Builder(Results.getAllocator(),
5375 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005376
5377 // Give this completion a return type.
Douglas Gregorc3425b12015-07-07 06:20:19 +00005378 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5379 Results.getCompletionContext().getBaseType(),
Douglas Gregor75acd922011-09-27 23:30:47 +00005380 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005381
5382 // If we need the "super" keyword, add it (plus some spacing).
5383 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005384 Builder.AddTypedTextChunk("super");
5385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005386 }
5387
5388 Selector Sel = CurMethod->getSelector();
5389 if (Sel.isUnarySelector()) {
5390 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005391 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005392 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005393 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005394 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005395 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005396 } else {
5397 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5398 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005399 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005401
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005402 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005403 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005404 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005405 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005406 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005407 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005408 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005409 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005410 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005411 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005412 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005413 Builder.AddTypedTextChunk(
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 }
5419 }
5420 }
5421
Douglas Gregor78254c82012-03-27 23:34:16 +00005422 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5423 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005424 return SuperMethod;
5425}
5426
Douglas Gregora817a192010-05-27 23:06:34 +00005427void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005428 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005429 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005430 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005431 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005432 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005433 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5434 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005435
Douglas Gregora817a192010-05-27 23:06:34 +00005436 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5437 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005438 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5439 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005440
5441 // If we are in an Objective-C method inside a class that has a superclass,
5442 // add "super" as an option.
5443 if (ObjCMethodDecl *Method = getCurMethodDecl())
5444 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005445 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005446 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005447
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005448 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005449 }
Douglas Gregora817a192010-05-27 23:06:34 +00005450
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005451 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005452 addThisCompletion(*this, Results);
5453
Douglas Gregora817a192010-05-27 23:06:34 +00005454 Results.ExitScope();
5455
5456 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005457 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005458 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005459 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005460
5461}
5462
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005463void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005464 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005465 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005466 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005467 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5468 // Figure out which interface we're in.
5469 CDecl = CurMethod->getClassInterface();
5470 if (!CDecl)
5471 return;
5472
5473 // Find the superclass of this class.
5474 CDecl = CDecl->getSuperClass();
5475 if (!CDecl)
5476 return;
5477
5478 if (CurMethod->isInstanceMethod()) {
5479 // We are inside an instance method, which means that the message
5480 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005481 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005482 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005483 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005484 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005485 }
5486
5487 // Fall through to send to the superclass in CDecl.
5488 } else {
5489 // "super" may be the name of a type or variable. Figure out which
5490 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005491 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005492 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5493 LookupOrdinaryName);
5494 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5495 // "super" names an interface. Use it.
5496 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005497 if (const ObjCObjectType *Iface
5498 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5499 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005500 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5501 // "super" names an unresolved type; we can't be more specific.
5502 } else {
5503 // Assume that "super" names some kind of value and parse that way.
5504 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005505 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005506 UnqualifiedId id;
5507 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005508 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5509 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005510 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005511 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005512 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005513 }
5514
5515 // Fall through
5516 }
5517
John McCallba7bf592010-08-24 05:47:05 +00005518 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005519 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005520 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005521 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005522 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005523 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005524}
5525
Douglas Gregor74661272010-09-21 00:03:25 +00005526/// \brief Given a set of code-completion results for the argument of a message
5527/// send, determine the preferred type (if any) for that argument expression.
5528static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5529 unsigned NumSelIdents) {
5530 typedef CodeCompletionResult Result;
5531 ASTContext &Context = Results.getSema().Context;
5532
5533 QualType PreferredType;
5534 unsigned BestPriority = CCP_Unlikely * 2;
5535 Result *ResultsData = Results.data();
5536 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5537 Result &R = ResultsData[I];
5538 if (R.Kind == Result::RK_Declaration &&
5539 isa<ObjCMethodDecl>(R.Declaration)) {
5540 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005541 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005542 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005543 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005544 ->getType();
5545 if (R.Priority < BestPriority || PreferredType.isNull()) {
5546 BestPriority = R.Priority;
5547 PreferredType = MyPreferredType;
5548 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5549 MyPreferredType)) {
5550 PreferredType = QualType();
5551 }
5552 }
5553 }
5554 }
5555 }
5556
5557 return PreferredType;
5558}
5559
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005560static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5561 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005562 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005563 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005564 bool IsSuper,
5565 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005566 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005567 ObjCInterfaceDecl *CDecl = nullptr;
5568
Douglas Gregor8ce33212009-11-17 17:59:40 +00005569 // If the given name refers to an interface type, retrieve the
5570 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005571 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005572 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005573 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005574 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5575 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005576 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005577
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005578 // Add all of the factory methods in this Objective-C class, its protocols,
5579 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005580 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005581
Douglas Gregor6fc04132010-08-27 15:10:57 +00005582 // If this is a send-to-super, try to add the special "super" send
5583 // completion.
5584 if (IsSuper) {
5585 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005586 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005587 Results.Ignore(SuperMethod);
5588 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005589
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005590 // If we're inside an Objective-C method definition, prefer its selector to
5591 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005592 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005593 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005594
Douglas Gregor1154e272010-09-16 16:06:31 +00005595 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005596 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005597 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005598 SemaRef.CurContext, Selectors, AtArgumentExpression,
5599 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005600 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005601 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005602
Douglas Gregord720daf2010-04-06 17:30:22 +00005603 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005604 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005605 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005606 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005607 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005608 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005609 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005610 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005611 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005612
5613 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005614 }
5615 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005616
5617 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5618 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005619 M != MEnd; ++M) {
5620 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005621 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005622 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005623 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005624 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005625
Nico Weber2e0c8f72014-12-27 03:58:08 +00005626 Result R(MethList->getMethod(),
5627 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005628 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005629 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005630 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005631 }
5632 }
5633 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005634
5635 Results.ExitScope();
5636}
Douglas Gregor6285f752010-04-06 16:40:00 +00005637
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005638void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005639 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005640 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005641 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005642
5643 QualType T = this->GetTypeFromParser(Receiver);
5644
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005645 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005646 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005647 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005648 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005649
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005650 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005651 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005652
5653 // If we're actually at the argument expression (rather than prior to the
5654 // selector), we're actually performing code completion for an expression.
5655 // Determine whether we have a single, best method. If so, we can
5656 // code-complete the expression using the corresponding parameter type as
5657 // our preferred type, improving completion results.
5658 if (AtArgumentExpression) {
5659 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005660 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005661 if (PreferredType.isNull())
5662 CodeCompleteOrdinaryName(S, PCC_Expression);
5663 else
5664 CodeCompleteExpression(S, PreferredType);
5665 return;
5666 }
5667
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005668 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005669 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005670 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005671}
5672
Richard Trieu2bd04012011-09-09 02:00:50 +00005673void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005674 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005675 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005676 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005677 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005678
5679 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005680
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005681 // If necessary, apply function/array conversion to the receiver.
5682 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005683 if (RecExpr) {
5684 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5685 if (Conv.isInvalid()) // conversion failed. bail.
5686 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005687 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005688 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005689 QualType ReceiverType = RecExpr? RecExpr->getType()
5690 : Super? Context.getObjCObjectPointerType(
5691 Context.getObjCInterfaceType(Super))
5692 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005693
Douglas Gregordc520b02010-11-08 21:12:30 +00005694 // If we're messaging an expression with type "id" or "Class", check
5695 // whether we know something special about the receiver that allows
5696 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005697 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005698 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5699 if (ReceiverType->isObjCClassType())
5700 return CodeCompleteObjCClassMessage(S,
5701 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005702 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005703 AtArgumentExpression, Super);
5704
5705 ReceiverType = Context.getObjCObjectPointerType(
5706 Context.getObjCInterfaceType(IFace));
5707 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005708 } else if (RecExpr && getLangOpts().CPlusPlus) {
5709 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5710 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005711 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005712 ReceiverType = RecExpr->getType();
5713 }
5714 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005715
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005716 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005717 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005718 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005719 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005720 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005721
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005722 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005723
Douglas Gregor6fc04132010-08-27 15:10:57 +00005724 // If this is a send-to-super, try to add the special "super" send
5725 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005726 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005727 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005728 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005729 Results.Ignore(SuperMethod);
5730 }
5731
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005732 // If we're inside an Objective-C method definition, prefer its selector to
5733 // others.
5734 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5735 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005736
Douglas Gregor1154e272010-09-16 16:06:31 +00005737 // Keep track of the selectors we've already added.
5738 VisitedSelectorSet Selectors;
5739
Douglas Gregora3329fa2009-11-18 00:06:18 +00005740 // Handle messages to Class. This really isn't a message to an instance
5741 // method, so we treat it the same way we would treat a message send to a
5742 // class method.
5743 if (ReceiverType->isObjCClassType() ||
5744 ReceiverType->isObjCQualifiedClassType()) {
5745 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5746 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005747 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005748 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005749 }
5750 }
5751 // Handle messages to a qualified ID ("id<foo>").
5752 else if (const ObjCObjectPointerType *QualID
5753 = ReceiverType->getAsObjCQualifiedIdType()) {
5754 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005755 for (auto *I : QualID->quals())
5756 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005757 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005758 }
5759 // Handle messages to a pointer to interface type.
5760 else if (const ObjCObjectPointerType *IFacePtr
5761 = ReceiverType->getAsObjCInterfacePointerType()) {
5762 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005763 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005764 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005765 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005766
5767 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005768 for (auto *I : IFacePtr->quals())
5769 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005770 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005771 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005772 // Handle messages to "id".
5773 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005774 // We're messaging "id", so provide all instance methods we know
5775 // about as code-completion results.
5776
5777 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005778 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005779 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005780 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5781 I != N; ++I) {
5782 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005783 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005784 continue;
5785
Sebastian Redl75d8a322010-08-02 23:18:59 +00005786 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005787 }
5788 }
5789
Sebastian Redl75d8a322010-08-02 23:18:59 +00005790 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5791 MEnd = MethodPool.end();
5792 M != MEnd; ++M) {
5793 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005794 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005795 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005796 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005797 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005798
Nico Weber2e0c8f72014-12-27 03:58:08 +00005799 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005800 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005801
Nico Weber2e0c8f72014-12-27 03:58:08 +00005802 Result R(MethList->getMethod(),
5803 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005804 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005805 R.AllParametersAreInformative = false;
5806 Results.MaybeAddResult(R, CurContext);
5807 }
5808 }
5809 }
Steve Naroffeae65032009-11-07 02:08:14 +00005810 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005811
5812
5813 // If we're actually at the argument expression (rather than prior to the
5814 // selector), we're actually performing code completion for an expression.
5815 // Determine whether we have a single, best method. If so, we can
5816 // code-complete the expression using the corresponding parameter type as
5817 // our preferred type, improving completion results.
5818 if (AtArgumentExpression) {
5819 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005820 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005821 if (PreferredType.isNull())
5822 CodeCompleteOrdinaryName(S, PCC_Expression);
5823 else
5824 CodeCompleteExpression(S, PreferredType);
5825 return;
5826 }
5827
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005828 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005829 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005830 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005831}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005832
Douglas Gregor68762e72010-08-23 21:17:50 +00005833void Sema::CodeCompleteObjCForCollection(Scope *S,
5834 DeclGroupPtrTy IterationVar) {
5835 CodeCompleteExpressionData Data;
5836 Data.ObjCCollection = true;
5837
5838 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005839 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005840 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5841 if (*I)
5842 Data.IgnoreDecls.push_back(*I);
5843 }
5844 }
5845
5846 CodeCompleteExpression(S, Data);
5847}
5848
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005849void Sema::CodeCompleteObjCSelector(Scope *S,
5850 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005851 // If we have an external source, load the entire class method
5852 // pool from the AST file.
5853 if (ExternalSource) {
5854 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5855 I != N; ++I) {
5856 Selector Sel = ExternalSource->GetExternalSelector(I);
5857 if (Sel.isNull() || MethodPool.count(Sel))
5858 continue;
5859
5860 ReadMethodPool(Sel);
5861 }
5862 }
5863
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005864 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005865 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005866 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005867 Results.EnterNewScope();
5868 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5869 MEnd = MethodPool.end();
5870 M != MEnd; ++M) {
5871
5872 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005873 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005874 continue;
5875
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005876 CodeCompletionBuilder Builder(Results.getAllocator(),
5877 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005878 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005879 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005880 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005881 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005882 continue;
5883 }
5884
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005885 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005886 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005887 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005888 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005889 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005890 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005891 Accumulator.clear();
5892 }
5893 }
5894
Benjamin Kramer632500c2011-07-26 16:59:25 +00005895 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005896 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005897 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005898 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005899 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005900 }
5901 Results.ExitScope();
5902
5903 HandleCodeCompleteResults(this, CodeCompleter,
5904 CodeCompletionContext::CCC_SelectorName,
5905 Results.data(), Results.size());
5906}
5907
Douglas Gregorbaf69612009-11-18 04:19:12 +00005908/// \brief Add all of the protocol declarations that we find in the given
5909/// (translation unit) context.
5910static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005911 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005912 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005913 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005914
Aaron Ballman629afae2014-03-07 19:56:05 +00005915 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005916 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005917 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005918 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005919 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5920 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005921 }
5922}
5923
5924void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5925 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005926 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005927 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005928 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005929
Douglas Gregora3b23b02010-12-09 21:44:02 +00005930 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5931 Results.EnterNewScope();
5932
5933 // Tell the result set to ignore all of the protocols we have
5934 // already seen.
5935 // FIXME: This doesn't work when caching code-completion results.
5936 for (unsigned I = 0; I != NumProtocols; ++I)
5937 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5938 Protocols[I].second))
5939 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005940
Douglas Gregora3b23b02010-12-09 21:44:02 +00005941 // Add all protocols.
5942 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5943 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005944
Douglas Gregora3b23b02010-12-09 21:44:02 +00005945 Results.ExitScope();
5946 }
5947
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005948 HandleCodeCompleteResults(this, CodeCompleter,
5949 CodeCompletionContext::CCC_ObjCProtocolName,
5950 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005951}
5952
5953void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005954 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005955 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005956 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005957
Douglas Gregora3b23b02010-12-09 21:44:02 +00005958 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5959 Results.EnterNewScope();
5960
5961 // Add all protocols.
5962 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5963 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005964
Douglas Gregora3b23b02010-12-09 21:44:02 +00005965 Results.ExitScope();
5966 }
5967
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005968 HandleCodeCompleteResults(this, CodeCompleter,
5969 CodeCompletionContext::CCC_ObjCProtocolName,
5970 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005971}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005972
5973/// \brief Add all of the Objective-C interface declarations that we find in
5974/// the given (translation unit) context.
5975static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5976 bool OnlyForwardDeclarations,
5977 bool OnlyUnimplemented,
5978 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005979 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005980
Aaron Ballman629afae2014-03-07 19:56:05 +00005981 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005982 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005983 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005984 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005985 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005986 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5987 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005988 }
5989}
5990
5991void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005992 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005993 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005994 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005995 Results.EnterNewScope();
5996
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005997 if (CodeCompleter->includeGlobals()) {
5998 // Add all classes.
5999 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6000 false, Results);
6001 }
6002
Douglas Gregor49c22a72009-11-18 16:26:39 +00006003 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006004
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006005 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006006 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006007 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006008}
6009
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006010void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6011 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006012 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006013 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006014 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006015 Results.EnterNewScope();
6016
6017 // Make sure that we ignore the class we're currently defining.
6018 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006019 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006020 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00006021 Results.Ignore(CurClass);
6022
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006023 if (CodeCompleter->includeGlobals()) {
6024 // Add all classes.
6025 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6026 false, Results);
6027 }
6028
Douglas Gregor49c22a72009-11-18 16:26:39 +00006029 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006030
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006031 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006032 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006033 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006034}
6035
6036void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006037 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006038 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006039 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00006040 Results.EnterNewScope();
6041
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006042 if (CodeCompleter->includeGlobals()) {
6043 // Add all unimplemented classes.
6044 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6045 true, Results);
6046 }
6047
Douglas Gregor49c22a72009-11-18 16:26:39 +00006048 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006049
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006050 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00006051 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006052 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00006053}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006054
6055void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006056 IdentifierInfo *ClassName,
6057 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006058 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006059
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006060 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006061 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006062 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006063
6064 // Ignore any categories we find that have already been implemented by this
6065 // interface.
6066 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6067 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006068 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006069 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006070 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006071 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006072 }
6073
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006074 // Add all of the categories we know about.
6075 Results.EnterNewScope();
6076 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00006077 for (const auto *D : TU->decls())
6078 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00006079 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006080 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6081 nullptr),
6082 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006083 Results.ExitScope();
6084
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006085 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006086 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006087 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006088}
6089
6090void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006091 IdentifierInfo *ClassName,
6092 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006093 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006094
6095 // Find the corresponding interface. If we couldn't find the interface, the
6096 // program itself is ill-formed. However, we'll try to be helpful still by
6097 // providing the list of all of the categories we know about.
6098 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006099 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006100 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6101 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006102 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006103
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006104 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006105 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006106 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006107
6108 // Add all of the categories that have have corresponding interface
6109 // declarations in this class and any of its superclasses, except for
6110 // already-implemented categories in the class itself.
6111 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6112 Results.EnterNewScope();
6113 bool IgnoreImplemented = true;
6114 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006115 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006116 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006117 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006118 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6119 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006120 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006121
6122 Class = Class->getSuperClass();
6123 IgnoreImplemented = false;
6124 }
6125 Results.ExitScope();
6126
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006127 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006128 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006129 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006130}
Douglas Gregor5d649882009-11-18 22:32:06 +00006131
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006132void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorc3425b12015-07-07 06:20:19 +00006133 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006134 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006135 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorc3425b12015-07-07 06:20:19 +00006136 CCContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006137
6138 // Figure out where this @synthesize lives.
6139 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006140 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006141 if (!Container ||
6142 (!isa<ObjCImplementationDecl>(Container) &&
6143 !isa<ObjCCategoryImplDecl>(Container)))
6144 return;
6145
6146 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006147 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006148 for (const auto *D : Container->decls())
6149 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006150 Results.Ignore(PropertyImpl->getPropertyDecl());
6151
6152 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006153 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006154 Results.EnterNewScope();
6155 if (ObjCImplementationDecl *ClassImpl
6156 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregorc3425b12015-07-07 06:20:19 +00006157 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
Douglas Gregor95147142011-05-05 15:50:42 +00006158 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006159 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006160 else
Douglas Gregorc3425b12015-07-07 06:20:19 +00006161 AddObjCProperties(CCContext,
6162 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006163 false, /*AllowNullaryMethods=*/false, CurContext,
6164 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006165 Results.ExitScope();
6166
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006167 HandleCodeCompleteResults(this, CodeCompleter,
6168 CodeCompletionContext::CCC_Other,
6169 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006170}
6171
6172void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006173 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006174 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006175 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006176 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006177 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006178
6179 // Figure out where this @synthesize lives.
6180 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006181 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006182 if (!Container ||
6183 (!isa<ObjCImplementationDecl>(Container) &&
6184 !isa<ObjCCategoryImplDecl>(Container)))
6185 return;
6186
6187 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006188 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006189 if (ObjCImplementationDecl *ClassImpl
6190 = dyn_cast<ObjCImplementationDecl>(Container))
6191 Class = ClassImpl->getClassInterface();
6192 else
6193 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6194 ->getClassInterface();
6195
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006196 // Determine the type of the property we're synthesizing.
6197 QualType PropertyType = Context.getObjCIdType();
6198 if (Class) {
6199 if (ObjCPropertyDecl *Property
6200 = Class->FindPropertyDeclaration(PropertyName)) {
6201 PropertyType
6202 = Property->getType().getNonReferenceType().getUnqualifiedType();
6203
6204 // Give preference to ivars
6205 Results.setPreferredType(PropertyType);
6206 }
6207 }
6208
Douglas Gregor5d649882009-11-18 22:32:06 +00006209 // Add all of the instance variables in this class and its superclasses.
6210 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006211 bool SawSimilarlyNamedIvar = false;
6212 std::string NameWithPrefix;
6213 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006214 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006215 std::string NameWithSuffix = PropertyName->getName().str();
6216 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006217 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006218 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6219 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006220 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6221 CurContext, nullptr, false);
6222
Douglas Gregor331faa02011-04-18 14:13:53 +00006223 // Determine whether we've seen an ivar with a name similar to the
6224 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006225 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006226 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006227 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006228 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006229
6230 // Reduce the priority of this result by one, to give it a slight
6231 // advantage over other results whose names don't match so closely.
6232 if (Results.size() &&
6233 Results.data()[Results.size() - 1].Kind
6234 == CodeCompletionResult::RK_Declaration &&
6235 Results.data()[Results.size() - 1].Declaration == Ivar)
6236 Results.data()[Results.size() - 1].Priority--;
6237 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006238 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006239 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006240
6241 if (!SawSimilarlyNamedIvar) {
6242 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006243 // an ivar of the appropriate type.
6244 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006245 typedef CodeCompletionResult Result;
6246 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006247 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6248 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006249
Douglas Gregor75acd922011-09-27 23:30:47 +00006250 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006251 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006252 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006253 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6254 Results.AddResult(Result(Builder.TakeString(), Priority,
6255 CXCursor_ObjCIvarDecl));
6256 }
6257
Douglas Gregor5d649882009-11-18 22:32:06 +00006258 Results.ExitScope();
6259
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006260 HandleCodeCompleteResults(this, CodeCompleter,
6261 CodeCompletionContext::CCC_Other,
6262 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006263}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006264
Douglas Gregor416b5752010-08-25 01:08:01 +00006265// Mapping from selectors to the methods that implement that selector, along
6266// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006267typedef llvm::DenseMap<
6268 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006269
6270/// \brief Find all of the methods that reside in the given container
6271/// (and its superclasses, protocols, etc.) that meet the given
6272/// criteria. Insert those methods into the map of known methods,
6273/// indexed by selector so they can be easily found.
6274static void FindImplementableMethods(ASTContext &Context,
6275 ObjCContainerDecl *Container,
6276 bool WantInstanceMethods,
6277 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006278 KnownMethodsMap &KnownMethods,
6279 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006280 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006281 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006282 if (!IFace->hasDefinition())
6283 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006284
6285 IFace = IFace->getDefinition();
6286 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006287
Douglas Gregor636a61e2010-04-07 00:21:17 +00006288 const ObjCList<ObjCProtocolDecl> &Protocols
6289 = IFace->getReferencedProtocols();
6290 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006291 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006292 I != E; ++I)
6293 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006294 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006295
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006296 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006297 for (auto *Cat : IFace->visible_categories()) {
6298 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006299 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006300 }
6301
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006302 // Visit the superclass.
6303 if (IFace->getSuperClass())
6304 FindImplementableMethods(Context, IFace->getSuperClass(),
6305 WantInstanceMethods, ReturnType,
6306 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006307 }
6308
6309 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6310 // Recurse into protocols.
6311 const ObjCList<ObjCProtocolDecl> &Protocols
6312 = Category->getReferencedProtocols();
6313 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006314 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006315 I != E; ++I)
6316 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006317 KnownMethods, InOriginalClass);
6318
6319 // If this category is the original class, jump to the interface.
6320 if (InOriginalClass && Category->getClassInterface())
6321 FindImplementableMethods(Context, Category->getClassInterface(),
6322 WantInstanceMethods, ReturnType, KnownMethods,
6323 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006324 }
6325
6326 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006327 // Make sure we have a definition; that's what we'll walk.
6328 if (!Protocol->hasDefinition())
6329 return;
6330 Protocol = Protocol->getDefinition();
6331 Container = Protocol;
6332
6333 // Recurse into protocols.
6334 const ObjCList<ObjCProtocolDecl> &Protocols
6335 = Protocol->getReferencedProtocols();
6336 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6337 E = Protocols.end();
6338 I != E; ++I)
6339 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6340 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006341 }
6342
6343 // Add methods in this container. This operation occurs last because
6344 // we want the methods from this container to override any methods
6345 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006346 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006347 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006348 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006349 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006350 continue;
6351
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006352 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006353 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006354 }
6355 }
6356}
6357
Douglas Gregor669a25a2011-02-17 00:22:45 +00006358/// \brief Add the parenthesized return or parameter type chunk to a code
6359/// completion string.
6360static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006361 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006362 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006363 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006364 CodeCompletionBuilder &Builder) {
6365 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor86b42682015-06-19 18:27:52 +00006366 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
Douglas Gregor29979142012-04-10 18:35:07 +00006367 if (!Quals.empty())
6368 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006369 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006370 Builder.getAllocator()));
6371 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6372}
6373
6374/// \brief Determine whether the given class is or inherits from a class by
6375/// the given name.
6376static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006377 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006378 if (!Class)
6379 return false;
6380
6381 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6382 return true;
6383
6384 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6385}
6386
6387/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6388/// Key-Value Observing (KVO).
6389static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6390 bool IsInstanceMethod,
6391 QualType ReturnType,
6392 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006393 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006394 ResultBuilder &Results) {
6395 IdentifierInfo *PropName = Property->getIdentifier();
6396 if (!PropName || PropName->getLength() == 0)
6397 return;
6398
Douglas Gregor75acd922011-09-27 23:30:47 +00006399 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6400
Douglas Gregor669a25a2011-02-17 00:22:45 +00006401 // Builder that will create each code completion.
6402 typedef CodeCompletionResult Result;
6403 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006404 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006405
6406 // The selector table.
6407 SelectorTable &Selectors = Context.Selectors;
6408
6409 // The property name, copied into the code completion allocation region
6410 // on demand.
6411 struct KeyHolder {
6412 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006413 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006414 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006415
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006416 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006417 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6418
Douglas Gregor669a25a2011-02-17 00:22:45 +00006419 operator const char *() {
6420 if (CopiedKey)
6421 return CopiedKey;
6422
6423 return CopiedKey = Allocator.CopyString(Key);
6424 }
6425 } Key(Allocator, PropName->getName());
6426
6427 // The uppercased name of the property name.
6428 std::string UpperKey = PropName->getName();
6429 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006430 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006431
6432 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6433 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6434 Property->getType());
6435 bool ReturnTypeMatchesVoid
6436 = ReturnType.isNull() || ReturnType->isVoidType();
6437
6438 // Add the normal accessor -(type)key.
6439 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006440 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006441 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6442 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006443 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6444 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006445
6446 Builder.AddTypedTextChunk(Key);
6447 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6448 CXCursor_ObjCInstanceMethodDecl));
6449 }
6450
6451 // If we have an integral or boolean property (or the user has provided
6452 // an integral or boolean return type), add the accessor -(type)isKey.
6453 if (IsInstanceMethod &&
6454 ((!ReturnType.isNull() &&
6455 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6456 (ReturnType.isNull() &&
6457 (Property->getType()->isIntegerType() ||
6458 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006459 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006460 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006461 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6462 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006463 if (ReturnType.isNull()) {
6464 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6465 Builder.AddTextChunk("BOOL");
6466 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6467 }
6468
6469 Builder.AddTypedTextChunk(
6470 Allocator.CopyString(SelectorId->getName()));
6471 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6472 CXCursor_ObjCInstanceMethodDecl));
6473 }
6474 }
6475
6476 // Add the normal mutator.
6477 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6478 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006479 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006480 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006481 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006482 if (ReturnType.isNull()) {
6483 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6484 Builder.AddTextChunk("void");
6485 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6486 }
6487
6488 Builder.AddTypedTextChunk(
6489 Allocator.CopyString(SelectorId->getName()));
6490 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006491 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6492 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006493 Builder.AddTextChunk(Key);
6494 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6495 CXCursor_ObjCInstanceMethodDecl));
6496 }
6497 }
6498
6499 // Indexed and unordered accessors
6500 unsigned IndexedGetterPriority = CCP_CodePattern;
6501 unsigned IndexedSetterPriority = CCP_CodePattern;
6502 unsigned UnorderedGetterPriority = CCP_CodePattern;
6503 unsigned UnorderedSetterPriority = CCP_CodePattern;
6504 if (const ObjCObjectPointerType *ObjCPointer
6505 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6506 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6507 // If this interface type is not provably derived from a known
6508 // collection, penalize the corresponding completions.
6509 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6510 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6511 if (!InheritsFromClassNamed(IFace, "NSArray"))
6512 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6513 }
6514
6515 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6516 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6517 if (!InheritsFromClassNamed(IFace, "NSSet"))
6518 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6519 }
6520 }
6521 } else {
6522 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6523 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6524 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6525 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6526 }
6527
6528 // Add -(NSUInteger)countOf<key>
6529 if (IsInstanceMethod &&
6530 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006531 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006532 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006533 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6534 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006535 if (ReturnType.isNull()) {
6536 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6537 Builder.AddTextChunk("NSUInteger");
6538 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6539 }
6540
6541 Builder.AddTypedTextChunk(
6542 Allocator.CopyString(SelectorId->getName()));
6543 Results.AddResult(Result(Builder.TakeString(),
6544 std::min(IndexedGetterPriority,
6545 UnorderedGetterPriority),
6546 CXCursor_ObjCInstanceMethodDecl));
6547 }
6548 }
6549
6550 // Indexed getters
6551 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6552 if (IsInstanceMethod &&
6553 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006554 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006555 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006556 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006557 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006558 if (ReturnType.isNull()) {
6559 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6560 Builder.AddTextChunk("id");
6561 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6562 }
6563
6564 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6565 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6566 Builder.AddTextChunk("NSUInteger");
6567 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6568 Builder.AddTextChunk("index");
6569 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6570 CXCursor_ObjCInstanceMethodDecl));
6571 }
6572 }
6573
6574 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6575 if (IsInstanceMethod &&
6576 (ReturnType.isNull() ||
6577 (ReturnType->isObjCObjectPointerType() &&
6578 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6579 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6580 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006581 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006582 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006583 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006584 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006585 if (ReturnType.isNull()) {
6586 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6587 Builder.AddTextChunk("NSArray *");
6588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6589 }
6590
6591 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6592 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6593 Builder.AddTextChunk("NSIndexSet *");
6594 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6595 Builder.AddTextChunk("indexes");
6596 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6597 CXCursor_ObjCInstanceMethodDecl));
6598 }
6599 }
6600
6601 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6602 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006603 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006604 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006605 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006606 &Context.Idents.get("range")
6607 };
6608
David Blaikie82e95a32014-11-19 07:49:47 +00006609 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006610 if (ReturnType.isNull()) {
6611 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6612 Builder.AddTextChunk("void");
6613 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6614 }
6615
6616 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6617 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6618 Builder.AddPlaceholderChunk("object-type");
6619 Builder.AddTextChunk(" **");
6620 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6621 Builder.AddTextChunk("buffer");
6622 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6623 Builder.AddTypedTextChunk("range:");
6624 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6625 Builder.AddTextChunk("NSRange");
6626 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6627 Builder.AddTextChunk("inRange");
6628 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6629 CXCursor_ObjCInstanceMethodDecl));
6630 }
6631 }
6632
6633 // Mutable indexed accessors
6634
6635 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6636 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006637 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006638 IdentifierInfo *SelectorIds[2] = {
6639 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006640 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006641 };
6642
David Blaikie82e95a32014-11-19 07:49:47 +00006643 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006644 if (ReturnType.isNull()) {
6645 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6646 Builder.AddTextChunk("void");
6647 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6648 }
6649
6650 Builder.AddTypedTextChunk("insertObject:");
6651 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6652 Builder.AddPlaceholderChunk("object-type");
6653 Builder.AddTextChunk(" *");
6654 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6655 Builder.AddTextChunk("object");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6658 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6659 Builder.AddPlaceholderChunk("NSUInteger");
6660 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6661 Builder.AddTextChunk("index");
6662 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6663 CXCursor_ObjCInstanceMethodDecl));
6664 }
6665 }
6666
6667 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6668 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006669 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006670 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006671 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006672 &Context.Idents.get("atIndexes")
6673 };
6674
David Blaikie82e95a32014-11-19 07:49:47 +00006675 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006676 if (ReturnType.isNull()) {
6677 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6678 Builder.AddTextChunk("void");
6679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6680 }
6681
6682 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6683 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6684 Builder.AddTextChunk("NSArray *");
6685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6686 Builder.AddTextChunk("array");
6687 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6688 Builder.AddTypedTextChunk("atIndexes:");
6689 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6690 Builder.AddPlaceholderChunk("NSIndexSet *");
6691 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6692 Builder.AddTextChunk("indexes");
6693 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6694 CXCursor_ObjCInstanceMethodDecl));
6695 }
6696 }
6697
6698 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6699 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006700 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006701 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006702 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006703 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006704 if (ReturnType.isNull()) {
6705 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6706 Builder.AddTextChunk("void");
6707 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6708 }
6709
6710 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6711 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6712 Builder.AddTextChunk("NSUInteger");
6713 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6714 Builder.AddTextChunk("index");
6715 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6716 CXCursor_ObjCInstanceMethodDecl));
6717 }
6718 }
6719
6720 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6721 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006722 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006723 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006724 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006725 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006726 if (ReturnType.isNull()) {
6727 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6728 Builder.AddTextChunk("void");
6729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6730 }
6731
6732 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6733 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6734 Builder.AddTextChunk("NSIndexSet *");
6735 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6736 Builder.AddTextChunk("indexes");
6737 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6738 CXCursor_ObjCInstanceMethodDecl));
6739 }
6740 }
6741
6742 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6743 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006744 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006745 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006746 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006747 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006748 &Context.Idents.get("withObject")
6749 };
6750
David Blaikie82e95a32014-11-19 07:49:47 +00006751 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006752 if (ReturnType.isNull()) {
6753 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6754 Builder.AddTextChunk("void");
6755 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6756 }
6757
6758 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6759 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6760 Builder.AddPlaceholderChunk("NSUInteger");
6761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6762 Builder.AddTextChunk("index");
6763 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6764 Builder.AddTypedTextChunk("withObject:");
6765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6766 Builder.AddTextChunk("id");
6767 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6768 Builder.AddTextChunk("object");
6769 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6770 CXCursor_ObjCInstanceMethodDecl));
6771 }
6772 }
6773
6774 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6775 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006776 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006777 = (Twine("replace") + UpperKey + "AtIndexes").str();
6778 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006779 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006780 &Context.Idents.get(SelectorName1),
6781 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006782 };
6783
David Blaikie82e95a32014-11-19 07:49:47 +00006784 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006785 if (ReturnType.isNull()) {
6786 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6787 Builder.AddTextChunk("void");
6788 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6789 }
6790
6791 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6792 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6793 Builder.AddPlaceholderChunk("NSIndexSet *");
6794 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6795 Builder.AddTextChunk("indexes");
6796 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6797 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6798 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6799 Builder.AddTextChunk("NSArray *");
6800 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6801 Builder.AddTextChunk("array");
6802 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6803 CXCursor_ObjCInstanceMethodDecl));
6804 }
6805 }
6806
6807 // Unordered getters
6808 // - (NSEnumerator *)enumeratorOfKey
6809 if (IsInstanceMethod &&
6810 (ReturnType.isNull() ||
6811 (ReturnType->isObjCObjectPointerType() &&
6812 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6813 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6814 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006815 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006816 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006817 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6818 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006819 if (ReturnType.isNull()) {
6820 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6821 Builder.AddTextChunk("NSEnumerator *");
6822 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6823 }
6824
6825 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6826 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6827 CXCursor_ObjCInstanceMethodDecl));
6828 }
6829 }
6830
6831 // - (type *)memberOfKey:(type *)object
6832 if (IsInstanceMethod &&
6833 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006834 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006835 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006836 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006837 if (ReturnType.isNull()) {
6838 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6839 Builder.AddPlaceholderChunk("object-type");
6840 Builder.AddTextChunk(" *");
6841 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6842 }
6843
6844 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6845 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6846 if (ReturnType.isNull()) {
6847 Builder.AddPlaceholderChunk("object-type");
6848 Builder.AddTextChunk(" *");
6849 } else {
6850 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006851 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006852 Builder.getAllocator()));
6853 }
6854 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6855 Builder.AddTextChunk("object");
6856 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6857 CXCursor_ObjCInstanceMethodDecl));
6858 }
6859 }
6860
6861 // Mutable unordered accessors
6862 // - (void)addKeyObject:(type *)object
6863 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006864 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006865 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006866 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006867 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006868 if (ReturnType.isNull()) {
6869 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6870 Builder.AddTextChunk("void");
6871 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6872 }
6873
6874 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6875 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6876 Builder.AddPlaceholderChunk("object-type");
6877 Builder.AddTextChunk(" *");
6878 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6879 Builder.AddTextChunk("object");
6880 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6881 CXCursor_ObjCInstanceMethodDecl));
6882 }
6883 }
6884
6885 // - (void)addKey:(NSSet *)objects
6886 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006887 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006888 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006889 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006890 if (ReturnType.isNull()) {
6891 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6892 Builder.AddTextChunk("void");
6893 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6894 }
6895
6896 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6897 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6898 Builder.AddTextChunk("NSSet *");
6899 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6900 Builder.AddTextChunk("objects");
6901 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6902 CXCursor_ObjCInstanceMethodDecl));
6903 }
6904 }
6905
6906 // - (void)removeKeyObject:(type *)object
6907 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006908 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006909 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006910 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006911 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006912 if (ReturnType.isNull()) {
6913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6914 Builder.AddTextChunk("void");
6915 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6916 }
6917
6918 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6919 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6920 Builder.AddPlaceholderChunk("object-type");
6921 Builder.AddTextChunk(" *");
6922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6923 Builder.AddTextChunk("object");
6924 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6925 CXCursor_ObjCInstanceMethodDecl));
6926 }
6927 }
6928
6929 // - (void)removeKey:(NSSet *)objects
6930 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006931 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006932 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006933 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006934 if (ReturnType.isNull()) {
6935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6936 Builder.AddTextChunk("void");
6937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6938 }
6939
6940 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942 Builder.AddTextChunk("NSSet *");
6943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 Builder.AddTextChunk("objects");
6945 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6946 CXCursor_ObjCInstanceMethodDecl));
6947 }
6948 }
6949
6950 // - (void)intersectKey:(NSSet *)objects
6951 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006952 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006953 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006954 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006955 if (ReturnType.isNull()) {
6956 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6957 Builder.AddTextChunk("void");
6958 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6959 }
6960
6961 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6962 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6963 Builder.AddTextChunk("NSSet *");
6964 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6965 Builder.AddTextChunk("objects");
6966 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6967 CXCursor_ObjCInstanceMethodDecl));
6968 }
6969 }
6970
6971 // Key-Value Observing
6972 // + (NSSet *)keyPathsForValuesAffectingKey
6973 if (!IsInstanceMethod &&
6974 (ReturnType.isNull() ||
6975 (ReturnType->isObjCObjectPointerType() &&
6976 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6977 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6978 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006979 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006980 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006981 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006982 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6983 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006984 if (ReturnType.isNull()) {
6985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6986 Builder.AddTextChunk("NSSet *");
6987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6988 }
6989
6990 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6991 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006992 CXCursor_ObjCClassMethodDecl));
6993 }
6994 }
6995
6996 // + (BOOL)automaticallyNotifiesObserversForKey
6997 if (!IsInstanceMethod &&
6998 (ReturnType.isNull() ||
6999 ReturnType->isIntegerType() ||
7000 ReturnType->isBooleanType())) {
7001 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007002 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00007003 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00007004 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7005 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00007006 if (ReturnType.isNull()) {
7007 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7008 Builder.AddTextChunk("BOOL");
7009 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7010 }
7011
7012 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7013 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7014 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00007015 }
7016 }
7017}
7018
Douglas Gregor636a61e2010-04-07 00:21:17 +00007019void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7020 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007021 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007022 // Determine the return type of the method we're declaring, if
7023 // provided.
7024 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00007025 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00007026 if (CurContext->isObjCContainer()) {
7027 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7028 IDecl = cast<Decl>(OCD);
7029 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007030 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00007031 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00007032 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00007033 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007034 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7035 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007036 IsInImplementation = true;
7037 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007038 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007039 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00007040 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007041 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00007042 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007043 }
7044
7045 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00007046 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00007047 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007048 }
7049
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007050 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007051 HandleCodeCompleteResults(this, CodeCompleter,
7052 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00007053 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007054 return;
7055 }
7056
7057 // Find all of the methods that we could declare/implement here.
7058 KnownMethodsMap KnownMethods;
7059 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00007060 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007061
Douglas Gregor636a61e2010-04-07 00:21:17 +00007062 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00007063 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007064 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007065 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007066 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007067 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00007068 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007069 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7070 MEnd = KnownMethods.end();
7071 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007072 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007073 CodeCompletionBuilder Builder(Results.getAllocator(),
7074 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007075
7076 // If the result type was not already provided, add it to the
7077 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00007078 if (ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00007079 AddObjCPassingTypeChunk(Method->getReturnType(),
7080 Method->getObjCDeclQualifier(), Context, Policy,
7081 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007082
7083 Selector Sel = Method->getSelector();
7084
7085 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007086 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007087 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007088
7089 // Add parameters to the pattern.
7090 unsigned I = 0;
7091 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7092 PEnd = Method->param_end();
7093 P != PEnd; (void)++P, ++I) {
7094 // Add the part of the selector name.
7095 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007096 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007097 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007098 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7099 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007100 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007101 } else
7102 break;
7103
7104 // Add the parameter type.
Douglas Gregor86b42682015-06-19 18:27:52 +00007105 QualType ParamType;
7106 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7107 ParamType = (*P)->getType();
7108 else
7109 ParamType = (*P)->getOriginalType();
7110 AddObjCPassingTypeChunk(ParamType,
Douglas Gregor29979142012-04-10 18:35:07 +00007111 (*P)->getObjCDeclQualifier(),
7112 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007113 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007114
7115 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007116 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007117 }
7118
7119 if (Method->isVariadic()) {
7120 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007121 Builder.AddChunk(CodeCompletionString::CK_Comma);
7122 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007123 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007124
Douglas Gregord37c59d2010-05-28 00:57:46 +00007125 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007126 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007127 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7128 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7129 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007130 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007131 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007132 Builder.AddTextChunk("return");
7133 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7134 Builder.AddPlaceholderChunk("expression");
7135 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007136 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007137 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007138
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007139 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7140 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007141 }
7142
Douglas Gregor416b5752010-08-25 01:08:01 +00007143 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007144 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007145 Priority += CCD_InBaseClass;
7146
Douglas Gregor78254c82012-03-27 23:34:16 +00007147 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007148 }
7149
Douglas Gregor669a25a2011-02-17 00:22:45 +00007150 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7151 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007152 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007153 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007154 Containers.push_back(SearchDecl);
7155
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007156 VisitedSelectorSet KnownSelectors;
7157 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7158 MEnd = KnownMethods.end();
7159 M != MEnd; ++M)
7160 KnownSelectors.insert(M->first);
7161
7162
Douglas Gregor669a25a2011-02-17 00:22:45 +00007163 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7164 if (!IFace)
7165 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7166 IFace = Category->getClassInterface();
7167
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007168 if (IFace)
7169 for (auto *Cat : IFace->visible_categories())
7170 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007171
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007172 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Aaron Ballmand174edf2014-03-13 19:11:50 +00007173 for (auto *P : Containers[I]->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007174 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007175 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007176 }
7177
Douglas Gregor636a61e2010-04-07 00:21:17 +00007178 Results.ExitScope();
7179
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007180 HandleCodeCompleteResults(this, CodeCompleter,
7181 CodeCompletionContext::CCC_Other,
7182 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007183}
Douglas Gregor95887f92010-07-08 23:20:03 +00007184
7185void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7186 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007187 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007188 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007189 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007190 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007191 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007192 if (ExternalSource) {
7193 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7194 I != N; ++I) {
7195 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007196 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007197 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007198
7199 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007200 }
7201 }
7202
7203 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007204 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007205 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007206 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007207 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007208
7209 if (ReturnTy)
7210 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007211
Douglas Gregor95887f92010-07-08 23:20:03 +00007212 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007213 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7214 MEnd = MethodPool.end();
7215 M != MEnd; ++M) {
7216 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7217 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007218 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007219 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007220 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007221 continue;
7222
Douglas Gregor45879692010-07-08 23:37:41 +00007223 if (AtParameterName) {
7224 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007225 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007226 if (NumSelIdents &&
7227 NumSelIdents <= MethList->getMethod()->param_size()) {
7228 ParmVarDecl *Param =
7229 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007230 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007231 CodeCompletionBuilder Builder(Results.getAllocator(),
7232 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007233 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007234 Param->getIdentifier()->getName()));
7235 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007236 }
7237 }
7238
7239 continue;
7240 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007241
Nico Weber2e0c8f72014-12-27 03:58:08 +00007242 Result R(MethList->getMethod(),
7243 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007244 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007245 R.AllParametersAreInformative = false;
7246 R.DeclaringEntity = true;
7247 Results.MaybeAddResult(R, CurContext);
7248 }
7249 }
7250
7251 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007252 HandleCodeCompleteResults(this, CodeCompleter,
7253 CodeCompletionContext::CCC_Other,
7254 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007255}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007256
Douglas Gregorec00a262010-08-24 22:20:20 +00007257void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007258 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007259 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007260 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007261 Results.EnterNewScope();
7262
7263 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007264 CodeCompletionBuilder Builder(Results.getAllocator(),
7265 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007266 Builder.AddTypedTextChunk("if");
7267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7268 Builder.AddPlaceholderChunk("condition");
7269 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007270
7271 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007272 Builder.AddTypedTextChunk("ifdef");
7273 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7274 Builder.AddPlaceholderChunk("macro");
7275 Results.AddResult(Builder.TakeString());
7276
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007277 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007278 Builder.AddTypedTextChunk("ifndef");
7279 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7280 Builder.AddPlaceholderChunk("macro");
7281 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007282
7283 if (InConditional) {
7284 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007285 Builder.AddTypedTextChunk("elif");
7286 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7287 Builder.AddPlaceholderChunk("condition");
7288 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007289
7290 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007291 Builder.AddTypedTextChunk("else");
7292 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007293
7294 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007295 Builder.AddTypedTextChunk("endif");
7296 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007297 }
7298
7299 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007300 Builder.AddTypedTextChunk("include");
7301 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7302 Builder.AddTextChunk("\"");
7303 Builder.AddPlaceholderChunk("header");
7304 Builder.AddTextChunk("\"");
7305 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007306
7307 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007308 Builder.AddTypedTextChunk("include");
7309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7310 Builder.AddTextChunk("<");
7311 Builder.AddPlaceholderChunk("header");
7312 Builder.AddTextChunk(">");
7313 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007314
7315 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007316 Builder.AddTypedTextChunk("define");
7317 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7318 Builder.AddPlaceholderChunk("macro");
7319 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007320
7321 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007322 Builder.AddTypedTextChunk("define");
7323 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7324 Builder.AddPlaceholderChunk("macro");
7325 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7326 Builder.AddPlaceholderChunk("args");
7327 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7328 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007329
7330 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007331 Builder.AddTypedTextChunk("undef");
7332 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7333 Builder.AddPlaceholderChunk("macro");
7334 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007335
7336 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007337 Builder.AddTypedTextChunk("line");
7338 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7339 Builder.AddPlaceholderChunk("number");
7340 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007341
7342 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007343 Builder.AddTypedTextChunk("line");
7344 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7345 Builder.AddPlaceholderChunk("number");
7346 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7347 Builder.AddTextChunk("\"");
7348 Builder.AddPlaceholderChunk("filename");
7349 Builder.AddTextChunk("\"");
7350 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007351
7352 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007353 Builder.AddTypedTextChunk("error");
7354 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7355 Builder.AddPlaceholderChunk("message");
7356 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007357
7358 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007359 Builder.AddTypedTextChunk("pragma");
7360 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7361 Builder.AddPlaceholderChunk("arguments");
7362 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007363
David Blaikiebbafb8a2012-03-11 07:00:24 +00007364 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007365 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007366 Builder.AddTypedTextChunk("import");
7367 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7368 Builder.AddTextChunk("\"");
7369 Builder.AddPlaceholderChunk("header");
7370 Builder.AddTextChunk("\"");
7371 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007372
7373 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007374 Builder.AddTypedTextChunk("import");
7375 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7376 Builder.AddTextChunk("<");
7377 Builder.AddPlaceholderChunk("header");
7378 Builder.AddTextChunk(">");
7379 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007380 }
7381
7382 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007383 Builder.AddTypedTextChunk("include_next");
7384 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7385 Builder.AddTextChunk("\"");
7386 Builder.AddPlaceholderChunk("header");
7387 Builder.AddTextChunk("\"");
7388 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007389
7390 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007391 Builder.AddTypedTextChunk("include_next");
7392 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7393 Builder.AddTextChunk("<");
7394 Builder.AddPlaceholderChunk("header");
7395 Builder.AddTextChunk(">");
7396 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007397
7398 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007399 Builder.AddTypedTextChunk("warning");
7400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7401 Builder.AddPlaceholderChunk("message");
7402 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007403
7404 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7405 // completions for them. And __include_macros is a Clang-internal extension
7406 // that we don't want to encourage anyone to use.
7407
7408 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7409 Results.ExitScope();
7410
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007411 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007412 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007413 Results.data(), Results.size());
7414}
7415
7416void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007417 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007418 S->getFnParent()? Sema::PCC_RecoveryInFunction
7419 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007420}
7421
Douglas Gregorec00a262010-08-24 22:20:20 +00007422void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007423 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007424 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007425 IsDefinition? CodeCompletionContext::CCC_MacroName
7426 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007427 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7428 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007429 CodeCompletionBuilder Builder(Results.getAllocator(),
7430 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007431 Results.EnterNewScope();
7432 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7433 MEnd = PP.macro_end();
7434 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007435 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007436 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007437 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7438 CCP_CodePattern,
7439 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007440 }
7441 Results.ExitScope();
7442 } else if (IsDefinition) {
7443 // FIXME: Can we detect when the user just wrote an include guard above?
7444 }
7445
Douglas Gregor0ac41382010-09-23 23:01:17 +00007446 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007447 Results.data(), Results.size());
7448}
7449
Douglas Gregorec00a262010-08-24 22:20:20 +00007450void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007451 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007452 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007453 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007454
7455 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007456 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007457
7458 // defined (<macro>)
7459 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007460 CodeCompletionBuilder Builder(Results.getAllocator(),
7461 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007462 Builder.AddTypedTextChunk("defined");
7463 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7464 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7465 Builder.AddPlaceholderChunk("macro");
7466 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7467 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007468 Results.ExitScope();
7469
7470 HandleCodeCompleteResults(this, CodeCompleter,
7471 CodeCompletionContext::CCC_PreprocessorExpression,
7472 Results.data(), Results.size());
7473}
7474
7475void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7476 IdentifierInfo *Macro,
7477 MacroInfo *MacroInfo,
7478 unsigned Argument) {
7479 // FIXME: In the future, we could provide "overload" results, much like we
7480 // do for function calls.
7481
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007482 // Now just ignore this. There will be another code-completion callback
7483 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007484}
7485
Douglas Gregor11583702010-08-25 17:04:25 +00007486void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007487 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007488 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007489 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007490}
7491
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007492void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007493 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007494 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007495 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7496 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007497 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7498 CodeCompletionDeclConsumer Consumer(Builder,
7499 Context.getTranslationUnitDecl());
7500 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7501 Consumer);
7502 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007503
7504 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007505 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007506
7507 Results.clear();
7508 Results.insert(Results.end(),
7509 Builder.data(), Builder.data() + Builder.size());
7510}