blob: aa8629c62bffe0397a668b84f16d9ab9710a6241 [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 };
345}
346
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));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000802 DeclContext::lookup_const_result Ctors = Record->lookup(ConstructorName);
803 for (DeclContext::lookup_const_iterator I = Ctors.begin(),
804 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.
1021void ResultBuilder::EnterNewScope() {
1022 ShadowMaps.push_back(ShadowMap());
1023}
1024
1025/// \brief Exit from the current scope.
1026void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001027 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1028 EEnd = ShadowMaps.back().end();
1029 E != EEnd;
1030 ++E)
1031 E->second.Destroy();
1032
Douglas Gregor3545ff42009-09-21 16:56:56 +00001033 ShadowMaps.pop_back();
1034}
1035
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001036/// \brief Determines whether this given declaration will be found by
1037/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001038bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001039 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1040
Richard Smith541b38b2013-09-20 01:15:31 +00001041 // If name lookup finds a local extern declaration, then we are in a
1042 // context where it behaves like an ordinary name.
1043 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001044 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001045 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001046 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001047 if (isa<ObjCIvarDecl>(ND))
1048 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001049 }
1050
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001051 return ND->getIdentifierNamespace() & IDNS;
1052}
1053
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001054/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001055/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001056bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001057 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1058 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1059 return false;
1060
Richard Smith541b38b2013-09-20 01:15:31 +00001061 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001062 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001063 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001064 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001065 if (isa<ObjCIvarDecl>(ND))
1066 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001067 }
1068
Douglas Gregor70febae2010-05-28 00:49:12 +00001069 return ND->getIdentifierNamespace() & IDNS;
1070}
1071
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001072bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001073 if (!IsOrdinaryNonTypeName(ND))
1074 return 0;
1075
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001076 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001077 if (VD->getType()->isIntegralOrEnumerationType())
1078 return true;
1079
1080 return false;
1081}
1082
Douglas Gregor70febae2010-05-28 00:49:12 +00001083/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001084/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001085bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001086 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1087
Richard Smith541b38b2013-09-20 01:15:31 +00001088 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001089 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001090 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001091
1092 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001093 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1094 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001095}
1096
Douglas Gregor3545ff42009-09-21 16:56:56 +00001097/// \brief Determines whether the given declaration is suitable as the
1098/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001099bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001101 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001102 ND = ClassTemplate->getTemplatedDecl();
1103
1104 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1105}
1106
1107/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001108bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001109 return isa<EnumDecl>(ND);
1110}
1111
1112/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001113bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001114 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001115 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001116 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001117
1118 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001119 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001120 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001121 RD->getTagKind() == TTK_Struct ||
1122 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001123
1124 return false;
1125}
1126
1127/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001128bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001129 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001130 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001131 ND = ClassTemplate->getTemplatedDecl();
1132
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001133 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001134 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001135
1136 return false;
1137}
1138
1139/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001140bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001141 return isa<NamespaceDecl>(ND);
1142}
1143
1144/// \brief Determines whether the given declaration is a namespace or
1145/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001146bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001147 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1148}
1149
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001150/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001151bool ResultBuilder::IsType(const NamedDecl *ND) const {
1152 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fa2642010-08-24 01:06:58 +00001153 ND = Using->getTargetDecl();
1154
1155 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001156}
1157
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001158/// \brief Determines which members of a class should be visible via
1159/// "." or "->". Only value declarations, nested name specifiers, and
1160/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001161bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1162 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001163 ND = Using->getTargetDecl();
1164
Douglas Gregor70788392009-12-11 18:14:22 +00001165 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1166 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001167}
1168
Douglas Gregora817a192010-05-27 23:06:34 +00001169static bool isObjCReceiverType(ASTContext &C, QualType T) {
1170 T = C.getCanonicalType(T);
1171 switch (T->getTypeClass()) {
1172 case Type::ObjCObject:
1173 case Type::ObjCInterface:
1174 case Type::ObjCObjectPointer:
1175 return true;
1176
1177 case Type::Builtin:
1178 switch (cast<BuiltinType>(T)->getKind()) {
1179 case BuiltinType::ObjCId:
1180 case BuiltinType::ObjCClass:
1181 case BuiltinType::ObjCSel:
1182 return true;
1183
1184 default:
1185 break;
1186 }
1187 return false;
1188
1189 default:
1190 break;
1191 }
1192
David Blaikiebbafb8a2012-03-11 07:00:24 +00001193 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001194 return false;
1195
1196 // FIXME: We could perform more analysis here to determine whether a
1197 // particular class type has any conversions to Objective-C types. For now,
1198 // just accept all class types.
1199 return T->isDependentType() || T->isRecordType();
1200}
1201
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001202bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001203 QualType T = getDeclUsageType(SemaRef.Context, ND);
1204 if (T.isNull())
1205 return false;
1206
1207 T = SemaRef.Context.getBaseElementType(T);
1208 return isObjCReceiverType(SemaRef.Context, T);
1209}
1210
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001211bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001212 if (IsObjCMessageReceiver(ND))
1213 return true;
1214
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001215 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001216 if (!Var)
1217 return false;
1218
1219 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1220}
1221
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001222bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001223 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1224 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001225 return false;
1226
1227 QualType T = getDeclUsageType(SemaRef.Context, ND);
1228 if (T.isNull())
1229 return false;
1230
1231 T = SemaRef.Context.getBaseElementType(T);
1232 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1233 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001234 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001235}
Douglas Gregora817a192010-05-27 23:06:34 +00001236
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001237bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001238 return false;
1239}
1240
James Dennettf1243872012-06-17 05:33:25 +00001241/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001242/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001243bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001244 return isa<ObjCIvarDecl>(ND);
1245}
1246
Douglas Gregorc580c522010-01-14 01:09:38 +00001247namespace {
1248 /// \brief Visible declaration consumer that adds a code-completion result
1249 /// for each visible declaration.
1250 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1251 ResultBuilder &Results;
1252 DeclContext *CurContext;
1253
1254 public:
1255 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1256 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001257
1258 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1259 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001260 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001261 if (Ctx)
1262 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001263
1264 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1265 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001266 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001267 }
1268 };
1269}
1270
Douglas Gregor3545ff42009-09-21 16:56:56 +00001271/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001272static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001273 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001274 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001275 Results.AddResult(Result("short", CCP_Type));
1276 Results.AddResult(Result("long", CCP_Type));
1277 Results.AddResult(Result("signed", CCP_Type));
1278 Results.AddResult(Result("unsigned", CCP_Type));
1279 Results.AddResult(Result("void", CCP_Type));
1280 Results.AddResult(Result("char", CCP_Type));
1281 Results.AddResult(Result("int", CCP_Type));
1282 Results.AddResult(Result("float", CCP_Type));
1283 Results.AddResult(Result("double", CCP_Type));
1284 Results.AddResult(Result("enum", CCP_Type));
1285 Results.AddResult(Result("struct", CCP_Type));
1286 Results.AddResult(Result("union", CCP_Type));
1287 Results.AddResult(Result("const", CCP_Type));
1288 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001289
Douglas Gregor3545ff42009-09-21 16:56:56 +00001290 if (LangOpts.C99) {
1291 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001292 Results.AddResult(Result("_Complex", CCP_Type));
1293 Results.AddResult(Result("_Imaginary", CCP_Type));
1294 Results.AddResult(Result("_Bool", CCP_Type));
1295 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001296 }
1297
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001298 CodeCompletionBuilder Builder(Results.getAllocator(),
1299 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001300 if (LangOpts.CPlusPlus) {
1301 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001302 Results.AddResult(Result("bool", CCP_Type +
1303 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001304 Results.AddResult(Result("class", CCP_Type));
1305 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001306
Douglas Gregorf4c33342010-05-28 00:22:41 +00001307 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001308 Builder.AddTypedTextChunk("typename");
1309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1310 Builder.AddPlaceholderChunk("qualifier");
1311 Builder.AddTextChunk("::");
1312 Builder.AddPlaceholderChunk("name");
1313 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001314
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001315 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001316 Results.AddResult(Result("auto", CCP_Type));
1317 Results.AddResult(Result("char16_t", CCP_Type));
1318 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001319
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001320 Builder.AddTypedTextChunk("decltype");
1321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1322 Builder.AddPlaceholderChunk("expression");
1323 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1324 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001325 }
1326 }
1327
1328 // GNU extensions
1329 if (LangOpts.GNUMode) {
1330 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001331 // Results.AddResult(Result("_Decimal32"));
1332 // Results.AddResult(Result("_Decimal64"));
1333 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001334
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001335 Builder.AddTypedTextChunk("typeof");
1336 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1337 Builder.AddPlaceholderChunk("expression");
1338 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001339
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001340 Builder.AddTypedTextChunk("typeof");
1341 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1342 Builder.AddPlaceholderChunk("type");
1343 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1344 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001345 }
1346}
1347
John McCallfaf5fb42010-08-26 23:41:50 +00001348static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001349 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001350 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001351 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001352 // Note: we don't suggest either "auto" or "register", because both
1353 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1354 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001355 Results.AddResult(Result("extern"));
1356 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001357}
1358
John McCallfaf5fb42010-08-26 23:41:50 +00001359static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001361 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001362 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001363 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001364 case Sema::PCC_Class:
1365 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001367 Results.AddResult(Result("explicit"));
1368 Results.AddResult(Result("friend"));
1369 Results.AddResult(Result("mutable"));
1370 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001371 }
1372 // Fall through
1373
John McCallfaf5fb42010-08-26 23:41:50 +00001374 case Sema::PCC_ObjCInterface:
1375 case Sema::PCC_ObjCImplementation:
1376 case Sema::PCC_Namespace:
1377 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001378 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001379 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001380 break;
1381
John McCallfaf5fb42010-08-26 23:41:50 +00001382 case Sema::PCC_ObjCInstanceVariableList:
1383 case Sema::PCC_Expression:
1384 case Sema::PCC_Statement:
1385 case Sema::PCC_ForInit:
1386 case Sema::PCC_Condition:
1387 case Sema::PCC_RecoveryInFunction:
1388 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001389 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001390 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001391 break;
1392 }
1393}
1394
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001395static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1396static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1397static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001398 ResultBuilder &Results,
1399 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001400static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001401 ResultBuilder &Results,
1402 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001403static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001404 ResultBuilder &Results,
1405 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001406static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001407
Douglas Gregorf4c33342010-05-28 00:22:41 +00001408static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001409 CodeCompletionBuilder Builder(Results.getAllocator(),
1410 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("typedef");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("type");
1414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1415 Builder.AddPlaceholderChunk("name");
1416 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001417}
1418
John McCallfaf5fb42010-08-26 23:41:50 +00001419static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001420 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001421 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001422 case Sema::PCC_Namespace:
1423 case Sema::PCC_Class:
1424 case Sema::PCC_ObjCInstanceVariableList:
1425 case Sema::PCC_Template:
1426 case Sema::PCC_MemberTemplate:
1427 case Sema::PCC_Statement:
1428 case Sema::PCC_RecoveryInFunction:
1429 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001430 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001431 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001432 return true;
1433
John McCallfaf5fb42010-08-26 23:41:50 +00001434 case Sema::PCC_Expression:
1435 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001436 return LangOpts.CPlusPlus;
1437
1438 case Sema::PCC_ObjCInterface:
1439 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001440 return false;
1441
John McCallfaf5fb42010-08-26 23:41:50 +00001442 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001443 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001444 }
David Blaikie8a40f702012-01-17 06:56:22 +00001445
1446 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001447}
1448
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001449static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1450 const Preprocessor &PP) {
1451 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001452 Policy.AnonymousTagLocations = false;
1453 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001454 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001455 return Policy;
1456}
1457
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001458/// \brief Retrieve a printing policy suitable for code completion.
1459static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1460 return getCompletionPrintingPolicy(S.Context, S.PP);
1461}
1462
Douglas Gregore5c79d52011-10-18 21:20:17 +00001463/// \brief Retrieve the string representation of the given type as a string
1464/// that has the appropriate lifetime for code completion.
1465///
1466/// This routine provides a fast path where we provide constant strings for
1467/// common type names.
1468static const char *GetCompletionTypeString(QualType T,
1469 ASTContext &Context,
1470 const PrintingPolicy &Policy,
1471 CodeCompletionAllocator &Allocator) {
1472 if (!T.getLocalQualifiers()) {
1473 // Built-in type names are constant strings.
1474 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001475 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001476
1477 // Anonymous tag types are constant strings.
1478 if (const TagType *TagT = dyn_cast<TagType>(T))
1479 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001480 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001481 switch (Tag->getTagKind()) {
1482 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001483 case TTK_Interface: return "__interface <anonymous>";
1484 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001485 case TTK_Union: return "union <anonymous>";
1486 case TTK_Enum: return "enum <anonymous>";
1487 }
1488 }
1489 }
1490
1491 // Slow path: format the type as a string.
1492 std::string Result;
1493 T.getAsStringInternal(Result, Policy);
1494 return Allocator.CopyString(Result);
1495}
1496
Douglas Gregord8c61782012-02-15 15:34:24 +00001497/// \brief Add a completion for "this", if we're in a member function.
1498static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1499 QualType ThisTy = S.getCurrentThisType();
1500 if (ThisTy.isNull())
1501 return;
1502
1503 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001504 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001505 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1506 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1507 S.Context,
1508 Policy,
1509 Allocator));
1510 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001511 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001512}
1513
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001514/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001515static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001516 Scope *S,
1517 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001518 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001519 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001520 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregore5c79d52011-10-18 21:20:17 +00001521 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001522
John McCall276321a2010-08-25 06:19:51 +00001523 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001524 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001525 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001527 if (Results.includeCodePatterns()) {
1528 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001529 Builder.AddTypedTextChunk("namespace");
1530 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1531 Builder.AddPlaceholderChunk("identifier");
1532 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1533 Builder.AddPlaceholderChunk("declarations");
1534 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1535 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1536 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001537 }
1538
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001539 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001540 Builder.AddTypedTextChunk("namespace");
1541 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1542 Builder.AddPlaceholderChunk("name");
1543 Builder.AddChunk(CodeCompletionString::CK_Equal);
1544 Builder.AddPlaceholderChunk("namespace");
1545 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001546
1547 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001548 Builder.AddTypedTextChunk("using");
1549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1550 Builder.AddTextChunk("namespace");
1551 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1552 Builder.AddPlaceholderChunk("identifier");
1553 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001554
1555 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001556 Builder.AddTypedTextChunk("asm");
1557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1558 Builder.AddPlaceholderChunk("string-literal");
1559 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1560 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001561
Douglas Gregorf4c33342010-05-28 00:22:41 +00001562 if (Results.includeCodePatterns()) {
1563 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001564 Builder.AddTypedTextChunk("template");
1565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566 Builder.AddPlaceholderChunk("declaration");
1567 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001568 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001569 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001570
David Blaikiebbafb8a2012-03-11 07:00:24 +00001571 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001572 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001573
Douglas Gregorf4c33342010-05-28 00:22:41 +00001574 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001575 // Fall through
1576
John McCallfaf5fb42010-08-26 23:41:50 +00001577 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001579 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001580 Builder.AddTypedTextChunk("using");
1581 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1582 Builder.AddPlaceholderChunk("qualifier");
1583 Builder.AddTextChunk("::");
1584 Builder.AddPlaceholderChunk("name");
1585 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001586
Douglas Gregorf4c33342010-05-28 00:22:41 +00001587 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001588 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001589 Builder.AddTypedTextChunk("using");
1590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1591 Builder.AddTextChunk("typename");
1592 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1593 Builder.AddPlaceholderChunk("qualifier");
1594 Builder.AddTextChunk("::");
1595 Builder.AddPlaceholderChunk("name");
1596 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001597 }
1598
John McCallfaf5fb42010-08-26 23:41:50 +00001599 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001600 AddTypedefResult(Results);
1601
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001602 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001603 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001604 if (Results.includeCodePatterns())
1605 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001607
1608 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001609 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001610 if (Results.includeCodePatterns())
1611 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001612 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001613
1614 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001615 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001616 if (Results.includeCodePatterns())
1617 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001618 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001619 }
1620 }
1621 // Fall through
1622
John McCallfaf5fb42010-08-26 23:41:50 +00001623 case Sema::PCC_Template:
1624 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001625 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001627 Builder.AddTypedTextChunk("template");
1628 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1629 Builder.AddPlaceholderChunk("parameters");
1630 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1631 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632 }
1633
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1635 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001636 break;
1637
John McCallfaf5fb42010-08-26 23:41:50 +00001638 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001639 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1640 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1641 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001642 break;
1643
John McCallfaf5fb42010-08-26 23:41:50 +00001644 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1646 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1647 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001648 break;
1649
John McCallfaf5fb42010-08-26 23:41:50 +00001650 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001651 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001652 break;
1653
John McCallfaf5fb42010-08-26 23:41:50 +00001654 case Sema::PCC_RecoveryInFunction:
1655 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001656 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001657
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1659 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001660 Builder.AddTypedTextChunk("try");
1661 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1662 Builder.AddPlaceholderChunk("statements");
1663 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1664 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1665 Builder.AddTextChunk("catch");
1666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1667 Builder.AddPlaceholderChunk("declaration");
1668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1669 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1670 Builder.AddPlaceholderChunk("statements");
1671 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1672 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001675 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001676 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001677
Douglas Gregorf64acca2010-05-25 21:41:55 +00001678 if (Results.includeCodePatterns()) {
1679 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001680 Builder.AddTypedTextChunk("if");
1681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001684 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001685 Builder.AddPlaceholderChunk("expression");
1686 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1687 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1688 Builder.AddPlaceholderChunk("statements");
1689 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1690 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1691 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001692
Douglas Gregorf64acca2010-05-25 21:41:55 +00001693 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("switch");
1695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001696 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001697 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001698 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001699 Builder.AddPlaceholderChunk("expression");
1700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1701 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1702 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1703 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001705 }
1706
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001707 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001708 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001709 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001710 Builder.AddTypedTextChunk("case");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddPlaceholderChunk("expression");
1713 Builder.AddChunk(CodeCompletionString::CK_Colon);
1714 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001715
1716 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001717 Builder.AddTypedTextChunk("default");
1718 Builder.AddChunk(CodeCompletionString::CK_Colon);
1719 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001720 }
1721
Douglas Gregorf64acca2010-05-25 21:41:55 +00001722 if (Results.includeCodePatterns()) {
1723 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001724 Builder.AddTypedTextChunk("while");
1725 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001727 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001728 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001729 Builder.AddPlaceholderChunk("expression");
1730 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1731 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1732 Builder.AddPlaceholderChunk("statements");
1733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1734 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1735 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001736
1737 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001738 Builder.AddTypedTextChunk("do");
1739 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1740 Builder.AddPlaceholderChunk("statements");
1741 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1742 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1743 Builder.AddTextChunk("while");
1744 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1745 Builder.AddPlaceholderChunk("expression");
1746 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1747 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001748
Douglas Gregorf64acca2010-05-25 21:41:55 +00001749 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001750 Builder.AddTypedTextChunk("for");
1751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001752 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001754 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001755 Builder.AddPlaceholderChunk("init-expression");
1756 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1757 Builder.AddPlaceholderChunk("condition");
1758 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1759 Builder.AddPlaceholderChunk("inc-expression");
1760 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1761 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1762 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1763 Builder.AddPlaceholderChunk("statements");
1764 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1765 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1766 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001767 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768
1769 if (S->getContinueParent()) {
1770 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001771 Builder.AddTypedTextChunk("continue");
1772 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001773 }
1774
1775 if (S->getBreakParent()) {
1776 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001777 Builder.AddTypedTextChunk("break");
1778 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001779 }
1780
1781 // "return expression ;" or "return ;", depending on whether we
1782 // know the function is void or not.
1783 bool isVoid = false;
1784 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001785 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001786 else if (ObjCMethodDecl *Method
1787 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001788 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001789 else if (SemaRef.getCurBlock() &&
1790 !SemaRef.getCurBlock()->ReturnType.isNull())
1791 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001792 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001793 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1795 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001796 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001797 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001798
Douglas Gregorf4c33342010-05-28 00:22:41 +00001799 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001800 Builder.AddTypedTextChunk("goto");
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("label");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001804
Douglas Gregorf4c33342010-05-28 00:22:41 +00001805 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001806 Builder.AddTypedTextChunk("using");
1807 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1808 Builder.AddTextChunk("namespace");
1809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1810 Builder.AddPlaceholderChunk("identifier");
1811 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001812 }
1813
1814 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001815 case Sema::PCC_ForInit:
1816 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001818 // Fall through: conditions and statements can have expressions.
1819
Douglas Gregor5e35d592010-09-14 23:59:36 +00001820 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001822 CCC == Sema::PCC_ParenthesizedExpression) {
1823 // (__bridge <type>)<expression>
1824 Builder.AddTypedTextChunk("__bridge");
1825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1826 Builder.AddPlaceholderChunk("type");
1827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1828 Builder.AddPlaceholderChunk("expression");
1829 Results.AddResult(Result(Builder.TakeString()));
1830
1831 // (__bridge_transfer <Objective-C type>)<expression>
1832 Builder.AddTypedTextChunk("__bridge_transfer");
1833 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1834 Builder.AddPlaceholderChunk("Objective-C type");
1835 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1836 Builder.AddPlaceholderChunk("expression");
1837 Results.AddResult(Result(Builder.TakeString()));
1838
1839 // (__bridge_retained <CF type>)<expression>
1840 Builder.AddTypedTextChunk("__bridge_retained");
1841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1842 Builder.AddPlaceholderChunk("CF type");
1843 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1844 Builder.AddPlaceholderChunk("expression");
1845 Results.AddResult(Result(Builder.TakeString()));
1846 }
1847 // Fall through
1848
John McCallfaf5fb42010-08-26 23:41:50 +00001849 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001850 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001851 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001852 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001853
Douglas Gregore5c79d52011-10-18 21:20:17 +00001854 // true
1855 Builder.AddResultTypeChunk("bool");
1856 Builder.AddTypedTextChunk("true");
1857 Results.AddResult(Result(Builder.TakeString()));
1858
1859 // false
1860 Builder.AddResultTypeChunk("bool");
1861 Builder.AddTypedTextChunk("false");
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001863
David Blaikiebbafb8a2012-03-11 07:00:24 +00001864 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001865 // dynamic_cast < type-id > ( expression )
1866 Builder.AddTypedTextChunk("dynamic_cast");
1867 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1868 Builder.AddPlaceholderChunk("type");
1869 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1870 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1871 Builder.AddPlaceholderChunk("expression");
1872 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1873 Results.AddResult(Result(Builder.TakeString()));
1874 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001875
1876 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001877 Builder.AddTypedTextChunk("static_cast");
1878 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1879 Builder.AddPlaceholderChunk("type");
1880 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1882 Builder.AddPlaceholderChunk("expression");
1883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1884 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001885
Douglas Gregorf4c33342010-05-28 00:22:41 +00001886 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001887 Builder.AddTypedTextChunk("reinterpret_cast");
1888 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1889 Builder.AddPlaceholderChunk("type");
1890 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1891 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1892 Builder.AddPlaceholderChunk("expression");
1893 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1894 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001895
Douglas Gregorf4c33342010-05-28 00:22:41 +00001896 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001897 Builder.AddTypedTextChunk("const_cast");
1898 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1899 Builder.AddPlaceholderChunk("type");
1900 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1902 Builder.AddPlaceholderChunk("expression");
1903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1904 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001905
David Blaikiebbafb8a2012-03-11 07:00:24 +00001906 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001907 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001908 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001909 Builder.AddTypedTextChunk("typeid");
1910 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1911 Builder.AddPlaceholderChunk("expression-or-type");
1912 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1913 Results.AddResult(Result(Builder.TakeString()));
1914 }
1915
Douglas Gregorf4c33342010-05-28 00:22:41 +00001916 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001917 Builder.AddTypedTextChunk("new");
1918 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1919 Builder.AddPlaceholderChunk("type");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1921 Builder.AddPlaceholderChunk("expressions");
1922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1923 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001924
Douglas Gregorf4c33342010-05-28 00:22:41 +00001925 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001926 Builder.AddTypedTextChunk("new");
1927 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1928 Builder.AddPlaceholderChunk("type");
1929 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1930 Builder.AddPlaceholderChunk("size");
1931 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1932 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1933 Builder.AddPlaceholderChunk("expressions");
1934 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1935 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001936
Douglas Gregorf4c33342010-05-28 00:22:41 +00001937 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001938 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001939 Builder.AddTypedTextChunk("delete");
1940 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1941 Builder.AddPlaceholderChunk("expression");
1942 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001943
Douglas Gregorf4c33342010-05-28 00:22:41 +00001944 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001945 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001946 Builder.AddTypedTextChunk("delete");
1947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1948 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1949 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1950 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1951 Builder.AddPlaceholderChunk("expression");
1952 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001953
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001955 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001956 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001957 Builder.AddTypedTextChunk("throw");
1958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1959 Builder.AddPlaceholderChunk("expression");
1960 Results.AddResult(Result(Builder.TakeString()));
1961 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001962
Douglas Gregora2db7932010-05-26 22:00:08 +00001963 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001964
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001965 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001966 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001967 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001968 Builder.AddTypedTextChunk("nullptr");
1969 Results.AddResult(Result(Builder.TakeString()));
1970
1971 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001972 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001973 Builder.AddTypedTextChunk("alignof");
1974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1975 Builder.AddPlaceholderChunk("type");
1976 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1977 Results.AddResult(Result(Builder.TakeString()));
1978
1979 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001980 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001981 Builder.AddTypedTextChunk("noexcept");
1982 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1983 Builder.AddPlaceholderChunk("expression");
1984 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1985 Results.AddResult(Result(Builder.TakeString()));
1986
1987 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001988 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001989 Builder.AddTypedTextChunk("sizeof...");
1990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1991 Builder.AddPlaceholderChunk("parameter-pack");
1992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1993 Results.AddResult(Result(Builder.TakeString()));
1994 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001995 }
1996
David Blaikiebbafb8a2012-03-11 07:00:24 +00001997 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001998 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001999 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2000 // The interface can be NULL.
2001 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002002 if (ID->getSuperClass()) {
2003 std::string SuperType;
2004 SuperType = ID->getSuperClass()->getNameAsString();
2005 if (Method->isInstanceMethod())
2006 SuperType += " *";
2007
2008 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2009 Builder.AddTypedTextChunk("super");
2010 Results.AddResult(Result(Builder.TakeString()));
2011 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002012 }
2013
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002014 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002015 }
2016
Jordan Rose58d54722012-06-30 21:33:57 +00002017 if (SemaRef.getLangOpts().C11) {
2018 // _Alignof
2019 Builder.AddResultTypeChunk("size_t");
2020 if (SemaRef.getASTContext().Idents.get("alignof").hasMacroDefinition())
2021 Builder.AddTypedTextChunk("alignof");
2022 else
2023 Builder.AddTypedTextChunk("_Alignof");
2024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2025 Builder.AddPlaceholderChunk("type");
2026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2027 Results.AddResult(Result(Builder.TakeString()));
2028 }
2029
Douglas Gregorf4c33342010-05-28 00:22:41 +00002030 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002031 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002032 Builder.AddTypedTextChunk("sizeof");
2033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2034 Builder.AddPlaceholderChunk("expression-or-type");
2035 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002037 break;
2038 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002039
John McCallfaf5fb42010-08-26 23:41:50 +00002040 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002041 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002042 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002043 }
2044
David Blaikiebbafb8a2012-03-11 07:00:24 +00002045 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2046 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002047
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002049 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002050}
2051
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002052/// \brief If the given declaration has an associated type, add it as a result
2053/// type chunk.
2054static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002055 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002056 const NamedDecl *ND,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002057 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002058 if (!ND)
2059 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002060
2061 // Skip constructors and conversion functions, which have their return types
2062 // built into their names.
2063 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2064 return;
2065
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002066 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002067 QualType T;
2068 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002069 T = Function->getReturnType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002070 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Alp Toker314cc812014-01-25 16:55:45 +00002071 T = Method->getReturnType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002072 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002073 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2074 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2075 /* Do nothing: ignore unresolved using declarations*/
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002076 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002077 T = Value->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002078 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002079 T = Property->getType();
2080
2081 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2082 return;
2083
Douglas Gregor75acd922011-09-27 23:30:47 +00002084 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002085 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002086}
2087
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002088static void MaybeAddSentinel(ASTContext &Context,
2089 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002090 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002091 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2092 if (Sentinel->getSentinel() == 0) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002093 if (Context.getLangOpts().ObjC1 &&
Douglas Gregordbb71db2010-08-23 23:51:41 +00002094 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002095 Result.AddTextChunk(", nil");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002096 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002097 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002098 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002099 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002100 }
2101}
2102
Douglas Gregor8f08d742011-07-30 07:55:26 +00002103static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2104 std::string Result;
2105 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002106 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002107 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002108 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002109 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002110 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002111 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002112 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002113 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002114 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002115 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002116 Result += "oneway ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002117 return Result;
2118}
2119
Douglas Gregore90dd002010-08-24 16:15:59 +00002120static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002121 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002122 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002123 bool SuppressName = false,
2124 bool SuppressBlock = false) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002125 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2126 if (Param->getType()->isDependentType() ||
2127 !Param->getType()->isBlockPointerType()) {
2128 // The argument for a dependent or non-block parameter is a placeholder
2129 // containing that parameter's type.
2130 std::string Result;
2131
Douglas Gregor981a0c42010-08-29 19:47:46 +00002132 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002133 Result = Param->getIdentifier()->getName();
2134
John McCall31168b02011-06-15 23:02:42 +00002135 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002136
2137 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002138 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2139 + Result + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002140 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002141 Result += Param->getIdentifier()->getName();
2142 }
2143 return Result;
2144 }
2145
2146 // The argument for a block pointer parameter is a block literal with
2147 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002148 FunctionTypeLoc Block;
2149 FunctionProtoTypeLoc BlockProto;
Douglas Gregore90dd002010-08-24 16:15:59 +00002150 TypeLoc TL;
2151 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2152 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2153 while (true) {
2154 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002155 if (!SuppressBlock) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002156 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2157 if (TypeSourceInfo *InnerTSInfo =
2158 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002159 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2160 continue;
2161 }
2162 }
2163
2164 // Look through qualified types
David Blaikie6adc78e2013-02-18 22:06:02 +00002165 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2166 TL = QualifiedTL.getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002167 continue;
2168 }
2169 }
2170
Douglas Gregore90dd002010-08-24 16:15:59 +00002171 // Try to get the function prototype behind the block pointer type,
2172 // then we're done.
David Blaikie6adc78e2013-02-18 22:06:02 +00002173 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2174 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2175 Block = TL.getAs<FunctionTypeLoc>();
2176 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregore90dd002010-08-24 16:15:59 +00002177 }
2178 break;
2179 }
2180 }
2181
2182 if (!Block) {
2183 // We were unable to find a FunctionProtoTypeLoc with parameter names
2184 // for the block; just use the parameter type as a placeholder.
2185 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002186 if (!ObjCMethodParam && Param->getIdentifier())
2187 Result = Param->getIdentifier()->getName();
2188
John McCall31168b02011-06-15 23:02:42 +00002189 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002190
2191 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002192 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2193 + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002194 if (Param->getIdentifier())
2195 Result += Param->getIdentifier()->getName();
2196 }
2197
2198 return Result;
2199 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002200
Douglas Gregore90dd002010-08-24 16:15:59 +00002201 // We have the function prototype behind the block pointer type, as it was
2202 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002203 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002204 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002205 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002206 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002207
2208 // Format the parameter list.
2209 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002210 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002211 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002212 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002213 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002214 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002215 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002216 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002217 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002218 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002219 Params += ", ";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002220 Params += FormatFunctionParameter(Context, Policy, Block.getParam(I),
2221 /*SuppressName=*/false,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002222 /*SuppressBlock=*/true);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002223
David Blaikie6adc78e2013-02-18 22:06:02 +00002224 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002225 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002226 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002227 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002228 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002229
Douglas Gregord793e7c2011-10-18 04:23:19 +00002230 if (SuppressBlock) {
2231 // Format as a parameter.
2232 Result = Result + " (^";
2233 if (Param->getIdentifier())
2234 Result += Param->getIdentifier()->getName();
2235 Result += ")";
2236 Result += Params;
2237 } else {
2238 // Format as a block literal argument.
2239 Result = '^' + Result;
2240 Result += Params;
2241
2242 if (Param->getIdentifier())
2243 Result += Param->getIdentifier()->getName();
2244 }
2245
Douglas Gregore90dd002010-08-24 16:15:59 +00002246 return Result;
2247}
2248
Douglas Gregor3545ff42009-09-21 16:56:56 +00002249/// \brief Add function parameter chunks to the given code completion string.
2250static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002251 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002252 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002253 CodeCompletionBuilder &Result,
2254 unsigned Start = 0,
2255 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002256 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002257
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002258 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002259 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002260
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002261 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002262 // When we see an optional default argument, put that argument and
2263 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002264 CodeCompletionBuilder Opt(Result.getAllocator(),
2265 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002266 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002267 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002268 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002269 Result.AddOptionalChunk(Opt.TakeString());
2270 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002271 }
2272
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002273 if (FirstParameter)
2274 FirstParameter = false;
2275 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002276 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002277
2278 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002279
2280 // Format the placeholder string.
Douglas Gregor75acd922011-09-27 23:30:47 +00002281 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2282 Param);
Douglas Gregore90dd002010-08-24 16:15:59 +00002283
Douglas Gregor400f5972010-08-31 05:13:43 +00002284 if (Function->isVariadic() && P == N - 1)
2285 PlaceholderStr += ", ...";
2286
Douglas Gregor3545ff42009-09-21 16:56:56 +00002287 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002288 Result.AddPlaceholderChunk(
2289 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002290 }
Douglas Gregorba449032009-09-22 21:42:17 +00002291
2292 if (const FunctionProtoType *Proto
2293 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002294 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002295 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002296 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002297
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002298 MaybeAddSentinel(Context, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002299 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002300}
2301
2302/// \brief Add template parameter chunks to the given code completion string.
2303static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002304 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002305 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002306 CodeCompletionBuilder &Result,
2307 unsigned MaxParameters = 0,
2308 unsigned Start = 0,
2309 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002310 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002311
2312 // Prefer to take the template parameter names from the first declaration of
2313 // the template.
2314 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2315
Douglas Gregor3545ff42009-09-21 16:56:56 +00002316 TemplateParameterList *Params = Template->getTemplateParameters();
2317 TemplateParameterList::iterator PEnd = Params->end();
2318 if (MaxParameters)
2319 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002320 for (TemplateParameterList::iterator P = Params->begin() + Start;
2321 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002322 bool HasDefaultArg = false;
2323 std::string PlaceholderStr;
2324 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2325 if (TTP->wasDeclaredWithTypename())
2326 PlaceholderStr = "typename";
2327 else
2328 PlaceholderStr = "class";
2329
2330 if (TTP->getIdentifier()) {
2331 PlaceholderStr += ' ';
2332 PlaceholderStr += TTP->getIdentifier()->getName();
2333 }
2334
2335 HasDefaultArg = TTP->hasDefaultArgument();
2336 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002337 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002338 if (NTTP->getIdentifier())
2339 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002340 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002341 HasDefaultArg = NTTP->hasDefaultArgument();
2342 } else {
2343 assert(isa<TemplateTemplateParmDecl>(*P));
2344 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2345
2346 // Since putting the template argument list into the placeholder would
2347 // be very, very long, we just use an abbreviation.
2348 PlaceholderStr = "template<...> class";
2349 if (TTP->getIdentifier()) {
2350 PlaceholderStr += ' ';
2351 PlaceholderStr += TTP->getIdentifier()->getName();
2352 }
2353
2354 HasDefaultArg = TTP->hasDefaultArgument();
2355 }
2356
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002357 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002358 // When we see an optional default argument, put that argument and
2359 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002360 CodeCompletionBuilder Opt(Result.getAllocator(),
2361 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002362 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002363 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002364 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002365 P - Params->begin(), true);
2366 Result.AddOptionalChunk(Opt.TakeString());
2367 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002368 }
2369
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002370 InDefaultArg = false;
2371
Douglas Gregor3545ff42009-09-21 16:56:56 +00002372 if (FirstParameter)
2373 FirstParameter = false;
2374 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002375 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002376
2377 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002378 Result.AddPlaceholderChunk(
2379 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002380 }
2381}
2382
Douglas Gregorf2510672009-09-21 19:57:38 +00002383/// \brief Add a qualifier to the given code-completion string, if the
2384/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002385static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002386AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002387 NestedNameSpecifier *Qualifier,
2388 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002389 ASTContext &Context,
2390 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002391 if (!Qualifier)
2392 return;
2393
2394 std::string PrintedNNS;
2395 {
2396 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002397 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002398 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002399 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002400 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002401 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002402 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002403}
2404
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002405static void
2406AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002407 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002408 const FunctionProtoType *Proto
2409 = Function->getType()->getAs<FunctionProtoType>();
2410 if (!Proto || !Proto->getTypeQuals())
2411 return;
2412
Douglas Gregor304f9b02011-02-01 21:15:40 +00002413 // FIXME: Add ref-qualifier!
2414
2415 // Handle single qualifiers without copying
2416 if (Proto->getTypeQuals() == Qualifiers::Const) {
2417 Result.AddInformativeChunk(" const");
2418 return;
2419 }
2420
2421 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2422 Result.AddInformativeChunk(" volatile");
2423 return;
2424 }
2425
2426 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2427 Result.AddInformativeChunk(" restrict");
2428 return;
2429 }
2430
2431 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002432 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002433 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002434 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002435 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002436 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002437 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002438 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002439 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002440}
2441
Douglas Gregor0212fd72010-09-21 16:06:22 +00002442/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002443static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002444 const NamedDecl *ND,
2445 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002446 DeclarationName Name = ND->getDeclName();
2447 if (!Name)
2448 return;
2449
2450 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002451 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002452 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002453 switch (Name.getCXXOverloadedOperator()) {
2454 case OO_None:
2455 case OO_Conditional:
2456 case NUM_OVERLOADED_OPERATORS:
2457 OperatorName = "operator";
2458 break;
2459
2460#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2461 case OO_##Name: OperatorName = "operator" Spelling; break;
2462#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2463#include "clang/Basic/OperatorKinds.def"
2464
2465 case OO_New: OperatorName = "operator new"; break;
2466 case OO_Delete: OperatorName = "operator delete"; break;
2467 case OO_Array_New: OperatorName = "operator new[]"; break;
2468 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2469 case OO_Call: OperatorName = "operator()"; break;
2470 case OO_Subscript: OperatorName = "operator[]"; break;
2471 }
2472 Result.AddTypedTextChunk(OperatorName);
2473 break;
2474 }
2475
Douglas Gregor0212fd72010-09-21 16:06:22 +00002476 case DeclarationName::Identifier:
2477 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002478 case DeclarationName::CXXDestructorName:
2479 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002480 Result.AddTypedTextChunk(
2481 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002482 break;
2483
2484 case DeclarationName::CXXUsingDirective:
2485 case DeclarationName::ObjCZeroArgSelector:
2486 case DeclarationName::ObjCOneArgSelector:
2487 case DeclarationName::ObjCMultiArgSelector:
2488 break;
2489
2490 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002491 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002492 QualType Ty = Name.getCXXNameType();
2493 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2494 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2495 else if (const InjectedClassNameType *InjectedTy
2496 = Ty->getAs<InjectedClassNameType>())
2497 Record = InjectedTy->getDecl();
2498 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002499 Result.AddTypedTextChunk(
2500 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002501 break;
2502 }
2503
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002504 Result.AddTypedTextChunk(
2505 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002506 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002507 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002508 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002509 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002510 }
2511 break;
2512 }
2513 }
2514}
2515
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002516CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002517 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002518 CodeCompletionTUInfo &CCTUInfo,
2519 bool IncludeBriefComments) {
2520 return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo,
2521 IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002522}
2523
Douglas Gregor3545ff42009-09-21 16:56:56 +00002524/// \brief If possible, create a new code completion string for the given
2525/// result.
2526///
2527/// \returns Either a new, heap-allocated code completion string describing
2528/// how to use this result, or NULL to indicate that the string or name of the
2529/// result is all that is needed.
2530CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002531CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2532 Preprocessor &PP,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002533 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002534 CodeCompletionTUInfo &CCTUInfo,
2535 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002536 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002537
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002538 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002539 if (Kind == RK_Pattern) {
2540 Pattern->Priority = Priority;
2541 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002542
2543 if (Declaration) {
2544 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002545 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002546 // Provide code completion comment for self.GetterName where
2547 // GetterName is the getter method for a property with name
2548 // different from the property name (declared via a property
2549 // getter attribute.
2550 const NamedDecl *ND = Declaration;
2551 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2552 if (M->isPropertyAccessor())
2553 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2554 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002555 PDecl->getIdentifier() != M->getIdentifier()) {
2556 if (const RawComment *RC =
2557 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002558 Result.addBriefComment(RC->getBriefText(Ctx));
2559 Pattern->BriefComment = Result.getBriefComment();
2560 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002561 else if (const RawComment *RC =
2562 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2563 Result.addBriefComment(RC->getBriefText(Ctx));
2564 Pattern->BriefComment = Result.getBriefComment();
2565 }
2566 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002567 }
2568
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002569 return Pattern;
2570 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002571
Douglas Gregorf09935f2009-12-01 05:55:20 +00002572 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002573 Result.AddTypedTextChunk(Keyword);
2574 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002575 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002576
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002577 if (Kind == RK_Macro) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002578 const MacroDirective *MD = PP.getMacroDirectiveHistory(Macro);
2579 assert(MD && "Not a macro?");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002580 const MacroInfo *MI = MD->getMacroInfo();
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002581 assert((!MD->isDefined() || MI) && "missing MacroInfo for define");
Douglas Gregorf09935f2009-12-01 05:55:20 +00002582
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002583 Result.AddTypedTextChunk(
2584 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002585
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002586 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002587 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002588
2589 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002590 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002591 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002592
2593 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2594 if (MI->isC99Varargs()) {
2595 --AEnd;
2596
2597 if (A == AEnd) {
2598 Result.AddPlaceholderChunk("...");
2599 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002600 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002601
Douglas Gregor0c505312011-07-30 08:17:44 +00002602 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002603 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002604 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002605
2606 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002607 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002608 if (MI->isC99Varargs())
2609 Arg += ", ...";
2610 else
2611 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002612 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002613 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002614 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002615
2616 // Non-variadic macros are simple.
2617 Result.AddPlaceholderChunk(
2618 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002619 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002620 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002621 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002622 }
2623
Douglas Gregorf64acca2010-05-25 21:41:55 +00002624 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002625 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002626 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002627
2628 if (IncludeBriefComments) {
2629 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002630 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002631 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002632 }
2633 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2634 if (OMD->isPropertyAccessor())
2635 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2636 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2637 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002638 }
2639
Douglas Gregor9eb77012009-11-07 00:00:49 +00002640 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002641 Result.AddTypedTextChunk(
2642 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002643 Result.AddTextChunk("::");
2644 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002645 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002646
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002647 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2648 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002649
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002650 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002651
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002652 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002653 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002654 Ctx, Policy);
2655 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002656 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002657 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002658 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002659 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002660 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002661 }
2662
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002663 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002664 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002665 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002666 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002667 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002668
Douglas Gregor3545ff42009-09-21 16:56:56 +00002669 // Figure out which template parameters are deduced (or have default
2670 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002671 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002672 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002673 unsigned LastDeducibleArgument;
2674 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2675 --LastDeducibleArgument) {
2676 if (!Deduced[LastDeducibleArgument - 1]) {
2677 // C++0x: Figure out if the template argument has a default. If so,
2678 // the user doesn't need to type this argument.
2679 // FIXME: We need to abstract template parameters better!
2680 bool HasDefaultArg = false;
2681 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002682 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002683 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2684 HasDefaultArg = TTP->hasDefaultArgument();
2685 else if (NonTypeTemplateParmDecl *NTTP
2686 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2687 HasDefaultArg = NTTP->hasDefaultArgument();
2688 else {
2689 assert(isa<TemplateTemplateParmDecl>(Param));
2690 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002691 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002692 }
2693
2694 if (!HasDefaultArg)
2695 break;
2696 }
2697 }
2698
2699 if (LastDeducibleArgument) {
2700 // Some of the function template arguments cannot be deduced from a
2701 // function call, so we introduce an explicit template argument list
2702 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002703 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002704 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002705 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002706 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002707 }
2708
2709 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002710 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002711 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002712 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002713 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002714 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002715 }
2716
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002717 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002718 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002719 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002720 Result.AddTypedTextChunk(
2721 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002722 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002723 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002724 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002725 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002726 }
2727
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002728 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002729 Selector Sel = Method->getSelector();
2730 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002731 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002732 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002733 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002734 }
2735
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002736 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002737 SelName += ':';
2738 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002739 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002740 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002741 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002742
2743 // If there is only one parameter, and we're past it, add an empty
2744 // typed-text chunk since there is nothing to type.
2745 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002746 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002747 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002748 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002749 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2750 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002751 P != PEnd; (void)++P, ++Idx) {
2752 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002753 std::string Keyword;
2754 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002755 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002756 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002757 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002758 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002759 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002760 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002761 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002762 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002763 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002764
2765 // If we're before the starting parameter, skip the placeholder.
2766 if (Idx < StartParameter)
2767 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002768
2769 std::string Arg;
Douglas Gregore90dd002010-08-24 16:15:59 +00002770
2771 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002772 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregore90dd002010-08-24 16:15:59 +00002773 else {
John McCall31168b02011-06-15 23:02:42 +00002774 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor8f08d742011-07-30 07:55:26 +00002775 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2776 + Arg + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002777 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002778 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002779 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002780 }
2781
Douglas Gregor400f5972010-08-31 05:13:43 +00002782 if (Method->isVariadic() && (P + 1) == PEnd)
2783 Arg += ", ...";
2784
Douglas Gregor95887f92010-07-08 23:20:03 +00002785 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002786 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002787 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002788 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002789 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002790 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002791 }
2792
Douglas Gregor04c5f972009-12-23 00:21:46 +00002793 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002794 if (Method->param_size() == 0) {
2795 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002796 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002797 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002798 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002799 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002800 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002801 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002802
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002803 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002804 }
2805
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002806 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002807 }
2808
Douglas Gregorf09935f2009-12-01 05:55:20 +00002809 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002810 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002811 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002812
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002813 Result.AddTypedTextChunk(
2814 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002815 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002816}
2817
Douglas Gregorf0f51982009-09-23 00:34:09 +00002818CodeCompletionString *
2819CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2820 unsigned CurrentArg,
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002821 Sema &S,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002822 CodeCompletionAllocator &Allocator,
2823 CodeCompletionTUInfo &CCTUInfo) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002824 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002825
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002826 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002827 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002828 FunctionDecl *FDecl = getFunction();
Douglas Gregor75acd922011-09-27 23:30:47 +00002829 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002830 const FunctionProtoType *Proto
2831 = dyn_cast<FunctionProtoType>(getFunctionType());
2832 if (!FDecl && !Proto) {
2833 // Function without a prototype. Just give the return type and a
2834 // highlighted ellipsis.
2835 const FunctionType *FT = getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00002836 Result.AddTextChunk(GetCompletionTypeString(FT->getReturnType(), S.Context,
2837 Policy, Result.getAllocator()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002838 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2839 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2840 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002841 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002842 }
2843
2844 if (FDecl)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002845 Result.AddTextChunk(
2846 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002847 else
Alp Toker314cc812014-01-25 16:55:45 +00002848 Result.AddTextChunk(Result.getAllocator().CopyString(
2849 Proto->getReturnType().getAsString(Policy)));
2850
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002851 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Alp Toker9cacbab2014-01-20 20:26:09 +00002852 unsigned NumParams = FDecl ? FDecl->getNumParams() : Proto->getNumParams();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002853 for (unsigned I = 0; I != NumParams; ++I) {
2854 if (I)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002855 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002856
2857 std::string ArgString;
2858 QualType ArgType;
2859
2860 if (FDecl) {
2861 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2862 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2863 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00002864 ArgType = Proto->getParamType(I);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002865 }
2866
John McCall31168b02011-06-15 23:02:42 +00002867 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002868
2869 if (I == CurrentArg)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002870 Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
2871 Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002872 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002873 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002874 }
2875
2876 if (Proto && Proto->isVariadic()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002877 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002878 if (CurrentArg < NumParams)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002879 Result.AddTextChunk("...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002880 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002881 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002882 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002883 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002884
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002885 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002886}
2887
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002888unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002889 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002890 bool PreferredTypeIsPointer) {
2891 unsigned Priority = CCP_Macro;
2892
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002893 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2894 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2895 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002896 Priority = CCP_Constant;
2897 if (PreferredTypeIsPointer)
2898 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002899 }
2900 // Treat "YES", "NO", "true", and "false" as constants.
2901 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2902 MacroName.equals("true") || MacroName.equals("false"))
2903 Priority = CCP_Constant;
2904 // Treat "bool" as a type.
2905 else if (MacroName.equals("bool"))
2906 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2907
Douglas Gregor6e240332010-08-16 16:18:59 +00002908
2909 return Priority;
2910}
2911
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00002912CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002913 if (!D)
2914 return CXCursor_UnexposedDecl;
2915
2916 switch (D->getKind()) {
2917 case Decl::Enum: return CXCursor_EnumDecl;
2918 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2919 case Decl::Field: return CXCursor_FieldDecl;
2920 case Decl::Function:
2921 return CXCursor_FunctionDecl;
2922 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2923 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002924 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002925
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002926 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002927 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2928 case Decl::ObjCMethod:
2929 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2930 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2931 case Decl::CXXMethod: return CXCursor_CXXMethod;
2932 case Decl::CXXConstructor: return CXCursor_Constructor;
2933 case Decl::CXXDestructor: return CXCursor_Destructor;
2934 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2935 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002936 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002937 case Decl::ParmVar: return CXCursor_ParmDecl;
2938 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00002939 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002940 case Decl::Var: return CXCursor_VarDecl;
2941 case Decl::Namespace: return CXCursor_Namespace;
2942 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2943 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2944 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2945 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2946 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2947 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00002948 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002949 case Decl::ClassTemplatePartialSpecialization:
2950 return CXCursor_ClassTemplatePartialSpecialization;
2951 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor3e653b32012-04-30 23:41:16 +00002952 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002953
2954 case Decl::Using:
2955 case Decl::UnresolvedUsingValue:
2956 case Decl::UnresolvedUsingTypename:
2957 return CXCursor_UsingDeclaration;
2958
Douglas Gregor4cd65962011-06-03 23:08:58 +00002959 case Decl::ObjCPropertyImpl:
2960 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2961 case ObjCPropertyImplDecl::Dynamic:
2962 return CXCursor_ObjCDynamicDecl;
2963
2964 case ObjCPropertyImplDecl::Synthesize:
2965 return CXCursor_ObjCSynthesizeDecl;
2966 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00002967
2968 case Decl::Import:
2969 return CXCursor_ModuleImportDecl;
Douglas Gregor4cd65962011-06-03 23:08:58 +00002970
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002971 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00002972 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002973 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00002974 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002975 case TTK_Struct: return CXCursor_StructDecl;
2976 case TTK_Class: return CXCursor_ClassDecl;
2977 case TTK_Union: return CXCursor_UnionDecl;
2978 case TTK_Enum: return CXCursor_EnumDecl;
2979 }
2980 }
2981 }
2982
2983 return CXCursor_UnexposedDecl;
2984}
2985
Douglas Gregor55b037b2010-07-08 20:55:51 +00002986static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00002987 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00002988 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00002989 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00002990
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002991 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002992
Douglas Gregor9eb77012009-11-07 00:00:49 +00002993 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2994 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00002995 M != MEnd; ++M) {
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002996 if (IncludeUndefined || M->first->hasMacroDefinition()) {
2997 if (MacroInfo *MI = M->second->getMacroInfo())
2998 if (MI->isUsedForHeaderGuard())
2999 continue;
3000
Douglas Gregor8cb17462012-10-09 16:01:50 +00003001 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003002 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003003 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003004 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003005 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003006 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003007
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003008 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003009
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003010}
3011
Douglas Gregorce0e8562010-08-23 21:54:33 +00003012static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3013 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003014 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003015
3016 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003017
Douglas Gregorce0e8562010-08-23 21:54:33 +00003018 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3019 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003020 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003021 Results.AddResult(Result("__func__", CCP_Constant));
3022 Results.ExitScope();
3023}
3024
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003025static void HandleCodeCompleteResults(Sema *S,
3026 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003027 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003028 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003029 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003030 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003031 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003032}
3033
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003034static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3035 Sema::ParserCompletionContext PCC) {
3036 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003037 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003038 return CodeCompletionContext::CCC_TopLevel;
3039
John McCallfaf5fb42010-08-26 23:41:50 +00003040 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003041 return CodeCompletionContext::CCC_ClassStructUnion;
3042
John McCallfaf5fb42010-08-26 23:41:50 +00003043 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003044 return CodeCompletionContext::CCC_ObjCInterface;
3045
John McCallfaf5fb42010-08-26 23:41:50 +00003046 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003047 return CodeCompletionContext::CCC_ObjCImplementation;
3048
John McCallfaf5fb42010-08-26 23:41:50 +00003049 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003050 return CodeCompletionContext::CCC_ObjCIvarList;
3051
John McCallfaf5fb42010-08-26 23:41:50 +00003052 case Sema::PCC_Template:
3053 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003054 if (S.CurContext->isFileContext())
3055 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003056 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003057 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003058 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003059
John McCallfaf5fb42010-08-26 23:41:50 +00003060 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003061 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003062
John McCallfaf5fb42010-08-26 23:41:50 +00003063 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003064 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3065 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003066 return CodeCompletionContext::CCC_ParenthesizedExpression;
3067 else
3068 return CodeCompletionContext::CCC_Expression;
3069
3070 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003071 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003072 return CodeCompletionContext::CCC_Expression;
3073
John McCallfaf5fb42010-08-26 23:41:50 +00003074 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003075 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003076
John McCallfaf5fb42010-08-26 23:41:50 +00003077 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003078 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003079
3080 case Sema::PCC_ParenthesizedExpression:
3081 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003082
3083 case Sema::PCC_LocalDeclarationSpecifiers:
3084 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003085 }
David Blaikie8a40f702012-01-17 06:56:22 +00003086
3087 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003088}
3089
Douglas Gregorac322ec2010-08-27 21:18:54 +00003090/// \brief If we're in a C++ virtual member function, add completion results
3091/// that invoke the functions we override, since it's common to invoke the
3092/// overridden function as well as adding new functionality.
3093///
3094/// \param S The semantic analysis object for which we are generating results.
3095///
3096/// \param InContext This context in which the nested-name-specifier preceding
3097/// the code-completion point
3098static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3099 ResultBuilder &Results) {
3100 // Look through blocks.
3101 DeclContext *CurContext = S.CurContext;
3102 while (isa<BlockDecl>(CurContext))
3103 CurContext = CurContext->getParent();
3104
3105
3106 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3107 if (!Method || !Method->isVirtual())
3108 return;
3109
3110 // We need to have names for all of the parameters, if we're going to
3111 // generate a forwarding call.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003112 for (auto P : Method->params())
3113 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003114 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003115
Douglas Gregor75acd922011-09-27 23:30:47 +00003116 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003117 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3118 MEnd = Method->end_overridden_methods();
3119 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003120 CodeCompletionBuilder Builder(Results.getAllocator(),
3121 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003122 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003123 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3124 continue;
3125
3126 // If we need a nested-name-specifier, add one now.
3127 if (!InContext) {
3128 NestedNameSpecifier *NNS
3129 = getRequiredQualification(S.Context, CurContext,
3130 Overridden->getDeclContext());
3131 if (NNS) {
3132 std::string Str;
3133 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003134 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003135 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003136 }
3137 } else if (!InContext->Equals(Overridden->getDeclContext()))
3138 continue;
3139
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003140 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003141 Overridden->getNameAsString()));
3142 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003143 bool FirstParam = true;
Aaron Ballman43b68be2014-03-07 17:50:17 +00003144 for (auto P : Method->params()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003145 if (FirstParam)
3146 FirstParam = false;
3147 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003148 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003149
Aaron Ballman43b68be2014-03-07 17:50:17 +00003150 Builder.AddPlaceholderChunk(
3151 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003152 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3154 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003155 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003156 CXCursor_CXXMethod,
3157 CXAvailability_Available,
3158 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003159 Results.Ignore(Overridden);
3160 }
3161}
3162
Douglas Gregor07f43572012-01-29 18:15:03 +00003163void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3164 ModuleIdPath Path) {
3165 typedef CodeCompletionResult Result;
3166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003167 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003168 CodeCompletionContext::CCC_Other);
3169 Results.EnterNewScope();
3170
3171 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003172 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003173 typedef CodeCompletionResult Result;
3174 if (Path.empty()) {
3175 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003176 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003177 PP.getHeaderSearchInfo().collectAllModules(Modules);
3178 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3179 Builder.AddTypedTextChunk(
3180 Builder.getAllocator().CopyString(Modules[I]->Name));
3181 Results.AddResult(Result(Builder.TakeString(),
3182 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003183 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003184 Modules[I]->isAvailable()
3185 ? CXAvailability_Available
3186 : CXAvailability_NotAvailable));
3187 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003188 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003189 // Load the named module.
3190 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3191 Module::AllVisible,
3192 /*IsInclusionDirective=*/false);
3193 // Enumerate submodules.
3194 if (Mod) {
3195 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3196 SubEnd = Mod->submodule_end();
3197 Sub != SubEnd; ++Sub) {
3198
3199 Builder.AddTypedTextChunk(
3200 Builder.getAllocator().CopyString((*Sub)->Name));
3201 Results.AddResult(Result(Builder.TakeString(),
3202 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003203 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003204 (*Sub)->isAvailable()
3205 ? CXAvailability_Available
3206 : CXAvailability_NotAvailable));
3207 }
3208 }
3209 }
3210 Results.ExitScope();
3211 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3212 Results.data(),Results.size());
3213}
3214
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003215void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003216 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003217 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003218 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003219 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003220 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003221
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003222 // Determine how to filter results, e.g., so that the names of
3223 // values (functions, enumerators, function templates, etc.) are
3224 // only allowed where we can have an expression.
3225 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003226 case PCC_Namespace:
3227 case PCC_Class:
3228 case PCC_ObjCInterface:
3229 case PCC_ObjCImplementation:
3230 case PCC_ObjCInstanceVariableList:
3231 case PCC_Template:
3232 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003233 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003234 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003235 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3236 break;
3237
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003238 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003239 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003240 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003241 case PCC_ForInit:
3242 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003243 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003244 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3245 else
3246 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003247
David Blaikiebbafb8a2012-03-11 07:00:24 +00003248 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003249 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003250 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003251
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003252 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003253 // Unfiltered
3254 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003255 }
3256
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003257 // If we are in a C++ non-static member function, check the qualifiers on
3258 // the member function to filter/prioritize the results list.
3259 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3260 if (CurMethod->isInstance())
3261 Results.setObjectTypeQualifiers(
3262 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3263
Douglas Gregorc580c522010-01-14 01:09:38 +00003264 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003265 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3266 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003267
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003268 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003269 Results.ExitScope();
3270
Douglas Gregorce0e8562010-08-23 21:54:33 +00003271 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003272 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003273 case PCC_Expression:
3274 case PCC_Statement:
3275 case PCC_RecoveryInFunction:
3276 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00003277 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003278 break;
3279
3280 case PCC_Namespace:
3281 case PCC_Class:
3282 case PCC_ObjCInterface:
3283 case PCC_ObjCImplementation:
3284 case PCC_ObjCInstanceVariableList:
3285 case PCC_Template:
3286 case PCC_MemberTemplate:
3287 case PCC_ForInit:
3288 case PCC_Condition:
3289 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003290 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003291 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003292 }
3293
Douglas Gregor9eb77012009-11-07 00:00:49 +00003294 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003295 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003296
Douglas Gregor50832e02010-09-20 22:39:41 +00003297 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003298 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003299}
3300
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003301static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3302 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003303 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003304 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003305 bool IsSuper,
3306 ResultBuilder &Results);
3307
3308void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3309 bool AllowNonIdentifiers,
3310 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003311 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003312 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003313 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003314 AllowNestedNameSpecifiers
3315 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3316 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003317 Results.EnterNewScope();
3318
3319 // Type qualifiers can come after names.
3320 Results.AddResult(Result("const"));
3321 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003322 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003323 Results.AddResult(Result("restrict"));
3324
David Blaikiebbafb8a2012-03-11 07:00:24 +00003325 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003326 if (AllowNonIdentifiers) {
3327 Results.AddResult(Result("operator"));
3328 }
3329
3330 // Add nested-name-specifiers.
3331 if (AllowNestedNameSpecifiers) {
3332 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003333 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003334 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3335 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3336 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003337 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003338 }
3339 }
3340 Results.ExitScope();
3341
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003342 // If we're in a context where we might have an expression (rather than a
3343 // declaration), and what we've seen so far is an Objective-C type that could
3344 // be a receiver of a class message, this may be a class message send with
3345 // the initial opening bracket '[' missing. Add appropriate completions.
3346 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003347 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003348 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003349 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3350 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003351 !DS.isTypeAltiVecVector() &&
3352 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003353 (S->getFlags() & Scope::DeclScope) != 0 &&
3354 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3355 Scope::FunctionPrototypeScope |
3356 Scope::AtCatchScope)) == 0) {
3357 ParsedType T = DS.getRepAsType();
3358 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003359 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003360 }
3361
Douglas Gregor56ccce02010-08-24 04:59:56 +00003362 // Note that we intentionally suppress macro results here, since we do not
3363 // encourage using macros to produce the names of entities.
3364
Douglas Gregor0ac41382010-09-23 23:01:17 +00003365 HandleCodeCompleteResults(this, CodeCompleter,
3366 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003367 Results.data(), Results.size());
3368}
3369
Douglas Gregor68762e72010-08-23 21:17:50 +00003370struct Sema::CodeCompleteExpressionData {
3371 CodeCompleteExpressionData(QualType PreferredType = QualType())
3372 : PreferredType(PreferredType), IntegralConstantExpression(false),
3373 ObjCCollection(false) { }
3374
3375 QualType PreferredType;
3376 bool IntegralConstantExpression;
3377 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003378 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003379};
3380
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003381/// \brief Perform code-completion in an expression context when we know what
3382/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003383void Sema::CodeCompleteExpression(Scope *S,
3384 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003385 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003386 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003387 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003388 if (Data.ObjCCollection)
3389 Results.setFilter(&ResultBuilder::IsObjCCollection);
3390 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003391 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003392 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003393 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3394 else
3395 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003396
3397 if (!Data.PreferredType.isNull())
3398 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3399
3400 // Ignore any declarations that we were told that we don't care about.
3401 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3402 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003403
3404 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003405 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3406 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003407
3408 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003409 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003410 Results.ExitScope();
3411
Douglas Gregor55b037b2010-07-08 20:55:51 +00003412 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003413 if (!Data.PreferredType.isNull())
3414 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3415 || Data.PreferredType->isMemberPointerType()
3416 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003417
Douglas Gregorce0e8562010-08-23 21:54:33 +00003418 if (S->getFnParent() &&
3419 !Data.ObjCCollection &&
3420 !Data.IntegralConstantExpression)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003421 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003422
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003423 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003424 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003425 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003426 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3427 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003428 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003429}
3430
Douglas Gregoreda7e542010-09-18 01:28:11 +00003431void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3432 if (E.isInvalid())
3433 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003434 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003435 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003436}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003437
Douglas Gregorb888acf2010-12-09 23:01:55 +00003438/// \brief The set of properties that have already been added, referenced by
3439/// property name.
3440typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3441
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003442/// \brief Retrieve the container definition, if any?
3443static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3444 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3445 if (Interface->hasDefinition())
3446 return Interface->getDefinition();
3447
3448 return Interface;
3449 }
3450
3451 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3452 if (Protocol->hasDefinition())
3453 return Protocol->getDefinition();
3454
3455 return Protocol;
3456 }
3457 return Container;
3458}
3459
3460static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003461 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003462 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003463 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003464 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003465 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003466 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003467
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003468 // Retrieve the definition.
3469 Container = getContainerDef(Container);
3470
Douglas Gregor9291bad2009-11-18 01:29:26 +00003471 // Add properties in this container.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003472 for (const auto *P : Container->properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003473 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003474 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003475 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003476
Douglas Gregor95147142011-05-05 15:50:42 +00003477 // Add nullary methods
3478 if (AllowNullaryMethods) {
3479 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003480 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003481 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003482 if (M->getSelector().isUnarySelector())
3483 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003484 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003485 CodeCompletionBuilder Builder(Results.getAllocator(),
3486 Results.getCodeCompletionTUInfo());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003487 AddResultTypeChunk(Context, Policy, M, Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003488 Builder.AddTypedTextChunk(
3489 Results.getAllocator().CopyString(Name->getName()));
3490
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003491 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003492 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003493 CurContext);
3494 }
3495 }
3496 }
3497
3498
Douglas Gregor9291bad2009-11-18 01:29:26 +00003499 // Add properties in referenced protocols.
3500 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003501 for (auto *P : Protocol->protocols())
3502 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003503 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003504 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003505 if (AllowCategories) {
3506 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003507 for (auto *Cat : IFace->known_categories())
3508 AddObjCProperties(Cat, AllowCategories, AllowNullaryMethods, CurContext,
3509 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003510 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003511
Douglas Gregor9291bad2009-11-18 01:29:26 +00003512 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003513 for (auto *I : IFace->all_referenced_protocols())
3514 AddObjCProperties(I, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003515 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003516
3517 // Look in the superclass.
3518 if (IFace->getSuperClass())
Douglas Gregor95147142011-05-05 15:50:42 +00003519 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3520 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003521 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003522 } else if (const ObjCCategoryDecl *Category
3523 = dyn_cast<ObjCCategoryDecl>(Container)) {
3524 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003525 for (auto *P : Category->protocols())
3526 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003527 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003528 }
3529}
3530
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003531void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003532 SourceLocation OpLoc,
3533 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003534 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003535 return;
3536
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003537 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3538 if (ConvertedBase.isInvalid())
3539 return;
3540 Base = ConvertedBase.get();
3541
John McCall276321a2010-08-25 06:19:51 +00003542 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003543
Douglas Gregor2436e712009-09-17 21:32:03 +00003544 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003545
3546 if (IsArrow) {
3547 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3548 BaseType = Ptr->getPointeeType();
3549 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003550 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003551 else
3552 return;
3553 }
3554
Douglas Gregor21325842011-07-07 16:03:39 +00003555 enum CodeCompletionContext::Kind contextKind;
3556
3557 if (IsArrow) {
3558 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3559 }
3560 else {
3561 if (BaseType->isObjCObjectPointerType() ||
3562 BaseType->isObjCObjectOrInterfaceType()) {
3563 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3564 }
3565 else {
3566 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3567 }
3568 }
3569
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003570 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003571 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00003572 CodeCompletionContext(contextKind,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003573 BaseType),
3574 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003575 Results.EnterNewScope();
3576 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003577 // Indicate that we are performing a member access, and the cv-qualifiers
3578 // for the base object type.
3579 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3580
Douglas Gregor9291bad2009-11-18 01:29:26 +00003581 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003582 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003583 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003584 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3585 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003586
David Blaikiebbafb8a2012-03-11 07:00:24 +00003587 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003588 if (!Results.empty()) {
3589 // The "template" keyword can follow "->" or "." in the grammar.
3590 // However, we only want to suggest the template keyword if something
3591 // is dependent.
3592 bool IsDependent = BaseType->isDependentType();
3593 if (!IsDependent) {
3594 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003595 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003596 IsDependent = Ctx->isDependentContext();
3597 break;
3598 }
3599 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003600
Douglas Gregor9291bad2009-11-18 01:29:26 +00003601 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003602 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003603 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003604 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003605 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3606 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003607 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003608
3609 // Add property results based on our interface.
3610 const ObjCObjectPointerType *ObjCPtr
3611 = BaseType->getAsObjCInterfacePointerType();
3612 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor95147142011-05-05 15:50:42 +00003613 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3614 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003615 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003616
3617 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003618 for (auto *I : ObjCPtr->quals())
3619 AddObjCProperties(I, true, /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003620 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003621 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003622 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003623 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003624 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003625 if (const ObjCObjectPointerType *ObjCPtr
3626 = BaseType->getAs<ObjCObjectPointerType>())
3627 Class = ObjCPtr->getInterfaceDecl();
3628 else
John McCall8b07ec22010-05-15 11:32:37 +00003629 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003630
3631 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003632 if (Class) {
3633 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3634 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003635 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3636 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003637 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003638 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003639
3640 // FIXME: How do we cope with isa?
3641
3642 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003643
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003644 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003645 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003646 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003647 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003648}
3649
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003650void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3651 if (!CodeCompleter)
3652 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003653
3654 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003655 enum CodeCompletionContext::Kind ContextKind
3656 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003657 switch ((DeclSpec::TST)TagSpec) {
3658 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003659 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003660 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003661 break;
3662
3663 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003664 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003665 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003666 break;
3667
3668 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003669 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003670 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003671 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003672 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003673 break;
3674
3675 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003676 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003677 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003678
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003679 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3680 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003681 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003682
3683 // First pass: look for tags.
3684 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003685 LookupVisibleDecls(S, LookupTagName, Consumer,
3686 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003687
Douglas Gregor39982192010-08-15 06:18:01 +00003688 if (CodeCompleter->includeGlobals()) {
3689 // Second pass: look for nested name specifiers.
3690 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3691 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3692 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003693
Douglas Gregor0ac41382010-09-23 23:01:17 +00003694 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003695 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003696}
3697
Douglas Gregor28c78432010-08-27 17:35:51 +00003698void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003699 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003700 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003701 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003702 Results.EnterNewScope();
3703 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3704 Results.AddResult("const");
3705 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3706 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003707 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003708 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3709 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003710 if (getLangOpts().C11 &&
3711 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3712 Results.AddResult("_Atomic");
Douglas Gregor28c78432010-08-27 17:35:51 +00003713 Results.ExitScope();
3714 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003715 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003716 Results.data(), Results.size());
3717}
3718
Douglas Gregord328d572009-09-21 18:10:23 +00003719void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003720 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003721 return;
John McCall5939b162011-08-06 07:30:58 +00003722
John McCallaab3e412010-08-25 08:40:02 +00003723 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003724 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3725 if (!type->isEnumeralType()) {
3726 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003727 Data.IntegralConstantExpression = true;
3728 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003729 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003730 }
Douglas Gregord328d572009-09-21 18:10:23 +00003731
3732 // Code-complete the cases of a switch statement over an enumeration type
3733 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003734 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003735 if (EnumDecl *Def = Enum->getDefinition())
3736 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003737
3738 // Determine which enumerators we have already seen in the switch statement.
3739 // FIXME: Ideally, we would also be able to look *past* the code-completion
3740 // token, in case we are code-completing in the middle of the switch and not
3741 // at the end. However, we aren't able to do so at the moment.
3742 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003743 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003744 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3745 SC = SC->getNextSwitchCase()) {
3746 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3747 if (!Case)
3748 continue;
3749
3750 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3751 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3752 if (EnumConstantDecl *Enumerator
3753 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3754 // We look into the AST of the case statement to determine which
3755 // enumerator was named. Alternatively, we could compute the value of
3756 // the integral constant expression, then compare it against the
3757 // values of each enumerator. However, value-based approach would not
3758 // work as well with C++ templates where enumerators declared within a
3759 // template are type- and value-dependent.
3760 EnumeratorsSeen.insert(Enumerator);
3761
Douglas Gregorf2510672009-09-21 19:57:38 +00003762 // If this is a qualified-id, keep track of the nested-name-specifier
3763 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003764 //
3765 // switch (TagD.getKind()) {
3766 // case TagDecl::TK_enum:
3767 // break;
3768 // case XXX
3769 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003770 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003771 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3772 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003773 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003774 }
3775 }
3776
David Blaikiebbafb8a2012-03-11 07:00:24 +00003777 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003778 // If there are no prior enumerators in C++, check whether we have to
3779 // qualify the names of the enumerators that we suggest, because they
3780 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003781 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003782 }
3783
Douglas Gregord328d572009-09-21 18:10:23 +00003784 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003785 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003786 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003787 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003788 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003789 for (auto *E : Enum->enumerators()) {
3790 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003791 continue;
3792
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003793 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003794 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003795 }
3796 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003797
Douglas Gregor21325842011-07-07 16:03:39 +00003798 //We need to make sure we're setting the right context,
3799 //so only say we include macros if the code completer says we do
3800 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3801 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003802 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003803 kind = CodeCompletionContext::CCC_OtherWithMacros;
3804 }
3805
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003806 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003807 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003808 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003809}
3810
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003811static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003812 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003813 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003814
3815 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003816 if (!Args[I])
3817 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003818
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003819 return false;
3820}
3821
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003822typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3823
3824void mergeCandidatesWithResults(Sema &SemaRef,
3825 SmallVectorImpl<ResultCandidate> &Results,
3826 OverloadCandidateSet &CandidateSet,
3827 SourceLocation Loc) {
3828 if (!CandidateSet.empty()) {
3829 // Sort the overload candidate set by placing the best overloads first.
3830 std::stable_sort(
3831 CandidateSet.begin(), CandidateSet.end(),
3832 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3833 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3834 });
3835
3836 // Add the remaining viable overload candidates as code-completion results.
3837 for (auto &Candidate : CandidateSet)
3838 if (Candidate.Viable)
3839 Results.push_back(ResultCandidate(Candidate.Function));
3840 }
3841}
3842
3843/// \brief Get the type of the Nth parameter from a given set of overload
3844/// candidates.
3845QualType getParamType(Sema &SemaRef, ArrayRef<ResultCandidate> Candidates,
3846 unsigned N) {
3847
3848 // Given the overloads 'Candidates' for a function call matching all arguments
3849 // up to N, return the type of the Nth parameter if it is the same for all
3850 // overload candidates.
3851 QualType ParamType;
3852 for (auto &Candidate : Candidates) {
3853 if (auto FType = Candidate.getFunctionType())
3854 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3855 if (N < Proto->getNumParams()) {
3856 if (ParamType.isNull())
3857 ParamType = Proto->getParamType(N);
3858 else if (!SemaRef.Context.hasSameUnqualifiedType(
3859 ParamType.getNonReferenceType(),
3860 Proto->getParamType(N).getNonReferenceType()))
3861 // Otherwise return a default-constructed QualType.
3862 return QualType();
3863 }
3864 }
3865
3866 return ParamType;
3867}
3868
3869void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3870 MutableArrayRef<ResultCandidate> Candidates,
3871 unsigned CurrentArg,
3872 bool CompleteExpressionWithCurrentArg = true) {
3873 QualType ParamType;
3874 if (CompleteExpressionWithCurrentArg)
3875 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3876
3877 if (ParamType.isNull())
3878 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3879 else
3880 SemaRef.CodeCompleteExpression(S, ParamType);
3881
3882 if (!Candidates.empty())
3883 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3884 Candidates.data(),
3885 Candidates.size());
3886}
3887
3888void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003889 if (!CodeCompleter)
3890 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003891
3892 // When we're code-completing for a call, we fall back to ordinary
3893 // name code-completion whenever we can't produce specific
3894 // results. We may want to revisit this strategy in the future,
3895 // e.g., by merging the two kinds of results.
3896
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003897 // FIXME: Provide support for highlighting optional parameters.
3898 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00003899
Douglas Gregorcabea402009-09-22 15:41:20 +00003900 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003901 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3902 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003903 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00003904 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003905 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003906
John McCall57500772009-12-16 12:17:52 +00003907 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00003908 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00003909 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00003910
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003911 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00003912
John McCall57500772009-12-16 12:17:52 +00003913 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003914 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003915 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003916 /*PartialOverloading=*/true);
3917 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3918 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
3919 if (UME->hasExplicitTemplateArgs()) {
3920 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
3921 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00003922 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003923 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
3924 ArgExprs.append(Args.begin(), Args.end());
3925 UnresolvedSet<8> Decls;
3926 Decls.append(UME->decls_begin(), UME->decls_end());
3927 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
3928 /*SuppressUsedConversions=*/false,
3929 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003930 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003931 FunctionDecl *FD = nullptr;
3932 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
3933 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
3934 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
3935 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003936 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003937 if (!getLangOpts().CPlusPlus ||
3938 !FD->getType()->getAs<FunctionProtoType>())
3939 Results.push_back(ResultCandidate(FD));
3940 else
3941 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
3942 Args, CandidateSet,
3943 /*SuppressUsedConversions=*/false,
3944 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003945
3946 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
3947 // If expression's type is CXXRecordDecl, it may overload the function
3948 // call operator, so we check if it does and add them as candidates.
3949 DeclarationName OpName = Context.DeclarationNames
3950 .getCXXOperatorName(OO_Call);
3951 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
3952 LookupQualifiedName(R, DC);
3953 R.suppressDiagnostics();
3954 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
3955 ArgExprs.append(Args.begin(), Args.end());
3956 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
3957 /*ExplicitArgs=*/nullptr,
3958 /*SuppressUsedConversions=*/false,
3959 /*PartialOverloading=*/true);
3960 } else {
3961 // Lastly we check whether expression's type is function pointer or
3962 // function.
3963 QualType T = NakedFn->getType();
3964 if (!T->getPointeeType().isNull())
3965 T = T->getPointeeType();
3966
3967 if (auto FP = T->getAs<FunctionProtoType>()) {
3968 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00003969 /*PartialOverloading=*/true) ||
3970 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003971 Results.push_back(ResultCandidate(FP));
3972 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00003973 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003974 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003975 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003976 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00003977
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003978 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
3979 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
3980 !CandidateSet.empty());
3981}
3982
3983void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
3984 ArrayRef<Expr *> Args) {
3985 if (!CodeCompleter)
3986 return;
3987
3988 // A complete type is needed to lookup for constructors.
3989 if (RequireCompleteType(Loc, Type, 0))
3990 return;
3991
3992 // FIXME: Provide support for member initializers.
3993 // FIXME: Provide support for variadic template constructors.
3994 // FIXME: Provide support for highlighting optional parameters.
3995
3996 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
3997
3998 for (auto C : LookupConstructors(Type->getAsCXXRecordDecl())) {
3999 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4000 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4001 Args, CandidateSet,
4002 /*SuppressUsedConversions=*/false,
4003 /*PartialOverloading=*/true);
4004 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4005 AddTemplateOverloadCandidate(FTD,
4006 DeclAccessPair::make(FTD, C->getAccess()),
4007 /*ExplicitTemplateArgs=*/nullptr,
4008 Args, CandidateSet,
4009 /*SuppressUsedConversions=*/false,
4010 /*PartialOverloading=*/true);
4011 }
4012 }
4013
4014 SmallVector<ResultCandidate, 8> Results;
4015 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4016 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004017}
4018
John McCall48871652010-08-21 09:40:31 +00004019void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4020 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004021 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004022 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004023 return;
4024 }
4025
4026 CodeCompleteExpression(S, VD->getType());
4027}
4028
4029void Sema::CodeCompleteReturn(Scope *S) {
4030 QualType ResultType;
4031 if (isa<BlockDecl>(CurContext)) {
4032 if (BlockScopeInfo *BSI = getCurBlock())
4033 ResultType = BSI->ReturnType;
4034 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004035 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004036 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004037 ResultType = Method->getReturnType();
4038
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004039 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004040 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004041 else
4042 CodeCompleteExpression(S, ResultType);
4043}
4044
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004045void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004046 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004047 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004048 mapCodeCompletionContext(*this, PCC_Statement));
4049 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4050 Results.EnterNewScope();
4051
4052 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4053 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4054 CodeCompleter->includeGlobals());
4055
4056 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4057
4058 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004059 CodeCompletionBuilder Builder(Results.getAllocator(),
4060 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004061 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004062 if (Results.includeCodePatterns()) {
4063 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4064 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4065 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4066 Builder.AddPlaceholderChunk("statements");
4067 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4068 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4069 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004070 Results.AddResult(Builder.TakeString());
4071
4072 // "else if" block
4073 Builder.AddTypedTextChunk("else");
4074 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4075 Builder.AddTextChunk("if");
4076 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004078 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004079 Builder.AddPlaceholderChunk("condition");
4080 else
4081 Builder.AddPlaceholderChunk("expression");
4082 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004083 if (Results.includeCodePatterns()) {
4084 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4085 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4086 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4087 Builder.AddPlaceholderChunk("statements");
4088 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4089 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4090 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004091 Results.AddResult(Builder.TakeString());
4092
4093 Results.ExitScope();
4094
4095 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004096 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004097
4098 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004099 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004100
4101 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4102 Results.data(),Results.size());
4103}
4104
Richard Trieu2bd04012011-09-09 02:00:50 +00004105void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004106 if (LHS)
4107 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4108 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004109 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004110}
4111
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004112void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004113 bool EnteringContext) {
4114 if (!SS.getScopeRep() || !CodeCompleter)
4115 return;
4116
Douglas Gregor3545ff42009-09-21 16:56:56 +00004117 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4118 if (!Ctx)
4119 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004120
4121 // Try to instantiate any non-dependent declaration contexts before
4122 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004123 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004124 return;
4125
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004126 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004127 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004128 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004129 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004130
Douglas Gregor3545ff42009-09-21 16:56:56 +00004131 // The "template" keyword can follow "::" in the grammar, but only
4132 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004133 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004134 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004135 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004136
4137 // Add calls to overridden virtual functions, if there are any.
4138 //
4139 // FIXME: This isn't wonderful, because we don't know whether we're actually
4140 // in a context that permits expressions. This is a general issue with
4141 // qualified-id completions.
4142 if (!EnteringContext)
4143 MaybeAddOverrideCalls(*this, Ctx, Results);
4144 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004145
Douglas Gregorac322ec2010-08-27 21:18:54 +00004146 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4147 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4148
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004149 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004150 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004151 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004152}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004153
4154void Sema::CodeCompleteUsing(Scope *S) {
4155 if (!CodeCompleter)
4156 return;
4157
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004158 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004159 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004160 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4161 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004162 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004163
4164 // If we aren't in class scope, we could see the "namespace" keyword.
4165 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004166 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004167
4168 // After "using", we can see anything that would start a
4169 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004170 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004171 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4172 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004173 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004174
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004175 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004176 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004177 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004178}
4179
4180void Sema::CodeCompleteUsingDirective(Scope *S) {
4181 if (!CodeCompleter)
4182 return;
4183
Douglas Gregor3545ff42009-09-21 16:56:56 +00004184 // After "using namespace", we expect to see a namespace name or namespace
4185 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004186 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004187 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004188 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004189 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004190 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004191 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004192 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4193 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004194 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004195 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004196 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004197 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004198}
4199
4200void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4201 if (!CodeCompleter)
4202 return;
4203
Ted Kremenekc37877d2013-10-08 17:08:03 +00004204 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004205 if (!S->getParent())
4206 Ctx = Context.getTranslationUnitDecl();
4207
Douglas Gregor0ac41382010-09-23 23:01:17 +00004208 bool SuppressedGlobalResults
4209 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4210
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004211 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004212 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004213 SuppressedGlobalResults
4214 ? CodeCompletionContext::CCC_Namespace
4215 : CodeCompletionContext::CCC_Other,
4216 &ResultBuilder::IsNamespace);
4217
4218 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004219 // We only want to see those namespaces that have already been defined
4220 // within this scope, because its likely that the user is creating an
4221 // extended namespace declaration. Keep track of the most recent
4222 // definition of each namespace.
4223 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4224 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4225 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4226 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004227 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004228
4229 // Add the most recent definition (or extended definition) of each
4230 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004231 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004232 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004233 NS = OrigToLatest.begin(),
4234 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004235 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004236 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004237 NS->second, Results.getBasePriority(NS->second),
4238 nullptr),
4239 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004240 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004241 }
4242
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004243 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004244 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004245 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004246}
4247
4248void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4249 if (!CodeCompleter)
4250 return;
4251
Douglas Gregor3545ff42009-09-21 16:56:56 +00004252 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004253 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004254 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004255 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004256 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004257 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004258 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4259 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004260 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004261 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004262 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004263}
4264
Douglas Gregorc811ede2009-09-18 20:05:18 +00004265void Sema::CodeCompleteOperatorName(Scope *S) {
4266 if (!CodeCompleter)
4267 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004268
John McCall276321a2010-08-25 06:19:51 +00004269 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004270 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004271 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004272 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004273 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004274 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004275
Douglas Gregor3545ff42009-09-21 16:56:56 +00004276 // Add the names of overloadable operators.
4277#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4278 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004279 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004280#include "clang/Basic/OperatorKinds.def"
4281
4282 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004283 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004284 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004285 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4286 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004287
4288 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004289 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004290 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004291
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004292 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004293 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004294 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004295}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004296
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004297void Sema::CodeCompleteConstructorInitializer(
4298 Decl *ConstructorD,
4299 ArrayRef <CXXCtorInitializer *> Initializers) {
Douglas Gregor75acd922011-09-27 23:30:47 +00004300 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004301 CXXConstructorDecl *Constructor
4302 = static_cast<CXXConstructorDecl *>(ConstructorD);
4303 if (!Constructor)
4304 return;
4305
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004306 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004307 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004308 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004309 Results.EnterNewScope();
4310
4311 // Fill in any already-initialized fields or base classes.
4312 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4313 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004314 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004315 if (Initializers[I]->isBaseInitializer())
4316 InitializedBases.insert(
4317 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4318 else
Francois Pichetd583da02010-12-04 09:14:42 +00004319 InitializedFields.insert(cast<FieldDecl>(
4320 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004321 }
4322
4323 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004324 CodeCompletionBuilder Builder(Results.getAllocator(),
4325 Results.getCodeCompletionTUInfo());
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004326 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004327 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004328 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004329 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4330 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004331 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004332 = !Initializers.empty() &&
4333 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004334 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004335 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004336 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004337 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004338
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004339 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004340 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004341 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004342 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4343 Builder.AddPlaceholderChunk("args");
4344 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4345 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004346 SawLastInitializer? CCP_NextInitializer
4347 : CCP_MemberDeclaration));
4348 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004349 }
4350
4351 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004352 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004353 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4354 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004355 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004356 = !Initializers.empty() &&
4357 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004358 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004359 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004360 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004361 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004362
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004363 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004364 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004365 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004366 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4367 Builder.AddPlaceholderChunk("args");
4368 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4369 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004370 SawLastInitializer? CCP_NextInitializer
4371 : CCP_MemberDeclaration));
4372 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004373 }
4374
4375 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004376 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004377 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4378 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004379 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004380 = !Initializers.empty() &&
4381 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004382 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004383 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004384 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004385
4386 if (!Field->getDeclName())
4387 continue;
4388
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004389 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004390 Field->getIdentifier()->getName()));
4391 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4392 Builder.AddPlaceholderChunk("args");
4393 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4394 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004395 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004396 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004397 CXCursor_MemberRef,
4398 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004399 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004400 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004401 }
4402 Results.ExitScope();
4403
Douglas Gregor0ac41382010-09-23 23:01:17 +00004404 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004405 Results.data(), Results.size());
4406}
4407
Douglas Gregord8c61782012-02-15 15:34:24 +00004408/// \brief Determine whether this scope denotes a namespace.
4409static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004410 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004411 if (!DC)
4412 return false;
4413
4414 return DC->isFileContext();
4415}
4416
4417void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4418 bool AfterAmpersand) {
4419 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004420 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004421 CodeCompletionContext::CCC_Other);
4422 Results.EnterNewScope();
4423
4424 // Note what has already been captured.
4425 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4426 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004427 for (const auto &C : Intro.Captures) {
4428 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004429 IncludedThis = true;
4430 continue;
4431 }
4432
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004433 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004434 }
4435
4436 // Look for other capturable variables.
4437 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004438 for (const auto *D : S->decls()) {
4439 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004440 if (!Var ||
4441 !Var->hasLocalStorage() ||
4442 Var->hasAttr<BlocksAttr>())
4443 continue;
4444
David Blaikie82e95a32014-11-19 07:49:47 +00004445 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004446 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004447 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004448 }
4449 }
4450
4451 // Add 'this', if it would be valid.
4452 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4453 addThisCompletion(*this, Results);
4454
4455 Results.ExitScope();
4456
4457 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4458 Results.data(), Results.size());
4459}
4460
James Dennett596e4752012-06-14 03:11:41 +00004461/// Macro that optionally prepends an "@" to the string literal passed in via
4462/// Keyword, depending on whether NeedAt is true or false.
4463#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4464
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004465static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004466 ResultBuilder &Results,
4467 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004468 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004469 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004470 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004471
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004472 CodeCompletionBuilder Builder(Results.getAllocator(),
4473 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004474 if (LangOpts.ObjC2) {
4475 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004476 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004477 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4478 Builder.AddPlaceholderChunk("property");
4479 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004480
4481 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004482 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004483 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4484 Builder.AddPlaceholderChunk("property");
4485 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004486 }
4487}
4488
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004489static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004490 ResultBuilder &Results,
4491 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004492 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004493
4494 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004495 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004496
4497 if (LangOpts.ObjC2) {
4498 // @property
James Dennett596e4752012-06-14 03:11:41 +00004499 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004500
4501 // @required
James Dennett596e4752012-06-14 03:11:41 +00004502 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004503
4504 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004505 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004506 }
4507}
4508
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004509static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004510 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004511 CodeCompletionBuilder Builder(Results.getAllocator(),
4512 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004513
4514 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004515 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004516 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4517 Builder.AddPlaceholderChunk("name");
4518 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004519
Douglas Gregorf4c33342010-05-28 00:22:41 +00004520 if (Results.includeCodePatterns()) {
4521 // @interface name
4522 // FIXME: Could introduce the whole pattern, including superclasses and
4523 // such.
James Dennett596e4752012-06-14 03:11:41 +00004524 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004525 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4526 Builder.AddPlaceholderChunk("class");
4527 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004528
Douglas Gregorf4c33342010-05-28 00:22:41 +00004529 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004530 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4532 Builder.AddPlaceholderChunk("protocol");
4533 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004534
4535 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004536 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004537 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4538 Builder.AddPlaceholderChunk("class");
4539 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004540 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004541
4542 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004543 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004544 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4545 Builder.AddPlaceholderChunk("alias");
4546 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4547 Builder.AddPlaceholderChunk("class");
4548 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004549
4550 if (Results.getSema().getLangOpts().Modules) {
4551 // @import name
4552 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4553 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4554 Builder.AddPlaceholderChunk("module");
4555 Results.AddResult(Result(Builder.TakeString()));
4556 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004557}
4558
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004559void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004560 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004561 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004562 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004563 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004564 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004565 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004566 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004567 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004568 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004569 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004570 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004571 HandleCodeCompleteResults(this, CodeCompleter,
4572 CodeCompletionContext::CCC_Other,
4573 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004574}
4575
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004576static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004577 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004578 CodeCompletionBuilder Builder(Results.getAllocator(),
4579 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004580
4581 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004582 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004583 if (Results.getSema().getLangOpts().CPlusPlus ||
4584 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004585 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004586 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004587 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004588 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4589 Builder.AddPlaceholderChunk("type-name");
4590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4591 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004592
4593 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004594 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004595 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004596 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4597 Builder.AddPlaceholderChunk("protocol-name");
4598 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004600
4601 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004602 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004603 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004604 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4605 Builder.AddPlaceholderChunk("selector");
4606 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4607 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004608
4609 // @"string"
4610 Builder.AddResultTypeChunk("NSString *");
4611 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4612 Builder.AddPlaceholderChunk("string");
4613 Builder.AddTextChunk("\"");
4614 Results.AddResult(Result(Builder.TakeString()));
4615
Douglas Gregor951de302012-07-17 23:24:47 +00004616 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004617 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004618 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004619 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004620 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4621 Results.AddResult(Result(Builder.TakeString()));
4622
Douglas Gregor951de302012-07-17 23:24:47 +00004623 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004624 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004625 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004626 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004627 Builder.AddChunk(CodeCompletionString::CK_Colon);
4628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4629 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004630 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4631 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004632
Douglas Gregor951de302012-07-17 23:24:47 +00004633 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004634 Builder.AddResultTypeChunk("id");
4635 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004636 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004637 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4638 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004639}
4640
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004641static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004642 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004643 CodeCompletionBuilder Builder(Results.getAllocator(),
4644 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004645
Douglas Gregorf4c33342010-05-28 00:22:41 +00004646 if (Results.includeCodePatterns()) {
4647 // @try { statements } @catch ( declaration ) { statements } @finally
4648 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004649 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004650 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4651 Builder.AddPlaceholderChunk("statements");
4652 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4653 Builder.AddTextChunk("@catch");
4654 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4655 Builder.AddPlaceholderChunk("parameter");
4656 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4657 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4658 Builder.AddPlaceholderChunk("statements");
4659 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4660 Builder.AddTextChunk("@finally");
4661 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4662 Builder.AddPlaceholderChunk("statements");
4663 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4664 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004665 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004666
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004667 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004668 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004669 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4670 Builder.AddPlaceholderChunk("expression");
4671 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004672
Douglas Gregorf4c33342010-05-28 00:22:41 +00004673 if (Results.includeCodePatterns()) {
4674 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004675 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004676 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4677 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4678 Builder.AddPlaceholderChunk("expression");
4679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4680 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4681 Builder.AddPlaceholderChunk("statements");
4682 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4683 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004684 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004685}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004686
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004687static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004688 ResultBuilder &Results,
4689 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004690 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004691 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4692 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4693 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004694 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004695 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004696}
4697
4698void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004699 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004700 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004701 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004702 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004703 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004704 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004705 HandleCodeCompleteResults(this, CodeCompleter,
4706 CodeCompletionContext::CCC_Other,
4707 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004708}
4709
4710void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004711 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004712 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004713 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004714 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004715 AddObjCStatementResults(Results, false);
4716 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004717 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004718 HandleCodeCompleteResults(this, CodeCompleter,
4719 CodeCompletionContext::CCC_Other,
4720 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004721}
4722
4723void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004724 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004725 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004726 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004727 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004728 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004729 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004730 HandleCodeCompleteResults(this, CodeCompleter,
4731 CodeCompletionContext::CCC_Other,
4732 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004733}
4734
Douglas Gregore6078da2009-11-19 00:14:45 +00004735/// \brief Determine whether the addition of the given flag to an Objective-C
4736/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004737static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004738 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004739 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004740 return true;
4741
Bill Wendling44426052012-12-20 19:22:21 +00004742 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004743
4744 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004745 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4746 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004747 return true;
4748
Jordan Rose53cb2f32012-08-20 20:01:13 +00004749 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004750 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004751 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004752 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004753 ObjCDeclSpec::DQ_PR_retain |
4754 ObjCDeclSpec::DQ_PR_strong |
4755 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004756 if (AssignCopyRetMask &&
4757 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004758 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004759 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004760 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004761 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4762 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004763 return true;
4764
4765 return false;
4766}
4767
Douglas Gregor36029f42009-11-18 23:08:07 +00004768void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004769 if (!CodeCompleter)
4770 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004771
Bill Wendling44426052012-12-20 19:22:21 +00004772 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004773
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004774 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004775 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004776 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004777 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004778 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004779 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004780 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004781 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004782 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004783 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4784 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004785 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004786 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004787 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004788 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004789 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004790 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004791 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004792 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004793 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004794 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004795 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004796 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004797
4798 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall3deb1ad2012-08-21 02:47:43 +00004799 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004800 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004801 Results.AddResult(CodeCompletionResult("weak"));
4802
Bill Wendling44426052012-12-20 19:22:21 +00004803 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004804 CodeCompletionBuilder Setter(Results.getAllocator(),
4805 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004806 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004807 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004808 Setter.AddPlaceholderChunk("method");
4809 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004810 }
Bill Wendling44426052012-12-20 19:22:21 +00004811 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004812 CodeCompletionBuilder Getter(Results.getAllocator(),
4813 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004814 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004815 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004816 Getter.AddPlaceholderChunk("method");
4817 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004818 }
Steve Naroff936354c2009-10-08 21:55:05 +00004819 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004820 HandleCodeCompleteResults(this, CodeCompleter,
4821 CodeCompletionContext::CCC_Other,
4822 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004823}
Steve Naroffeae65032009-11-07 02:08:14 +00004824
James Dennettf1243872012-06-17 05:33:25 +00004825/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004826/// via code completion.
4827enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004828 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4829 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4830 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004831};
4832
Douglas Gregor67c692c2010-08-26 15:07:07 +00004833static bool isAcceptableObjCSelector(Selector Sel,
4834 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004835 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004836 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004837 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004838 if (NumSelIdents > Sel.getNumArgs())
4839 return false;
4840
4841 switch (WantKind) {
4842 case MK_Any: break;
4843 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4844 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4845 }
4846
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004847 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4848 return false;
4849
Douglas Gregor67c692c2010-08-26 15:07:07 +00004850 for (unsigned I = 0; I != NumSelIdents; ++I)
4851 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4852 return false;
4853
4854 return true;
4855}
4856
Douglas Gregorc8537c52009-11-19 07:41:15 +00004857static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4858 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004859 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004860 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004861 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004862 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004863}
Douglas Gregor1154e272010-09-16 16:06:31 +00004864
4865namespace {
4866 /// \brief A set of selectors, which is used to avoid introducing multiple
4867 /// completions with the same selector into the result set.
4868 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4869}
4870
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004871/// \brief Add all of the Objective-C methods in the given Objective-C
4872/// container to the set of results.
4873///
4874/// The container will be a class, protocol, category, or implementation of
4875/// any of the above. This mether will recurse to include methods from
4876/// the superclasses of classes along with their categories, protocols, and
4877/// implementations.
4878///
4879/// \param Container the container in which we'll look to find methods.
4880///
James Dennett596e4752012-06-14 03:11:41 +00004881/// \param WantInstanceMethods Whether to add instance methods (only); if
4882/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004883///
4884/// \param CurContext the context in which we're performing the lookup that
4885/// finds methods.
4886///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004887/// \param AllowSameLength Whether we allow a method to be added to the list
4888/// when it has the same number of parameters as we have selector identifiers.
4889///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004890/// \param Results the structure into which we'll add results.
4891static void AddObjCMethods(ObjCContainerDecl *Container,
4892 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00004893 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004894 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004895 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00004896 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004897 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00004898 ResultBuilder &Results,
4899 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00004900 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004901 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00004902 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4903 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004904 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00004905 // The instance methods on the root class can be messaged via the
4906 // metaclass.
4907 if (M->isInstanceMethod() == WantInstanceMethods ||
4908 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00004909 // Check whether the selector identifiers we've been given are a
4910 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004911 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00004912 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004913
David Blaikie82e95a32014-11-19 07:49:47 +00004914 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00004915 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00004916
4917 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004918 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00004919 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00004920 if (!InOriginalClass)
4921 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004922 Results.MaybeAddResult(R, CurContext);
4923 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004924 }
4925
Douglas Gregorf37c9492010-09-16 15:34:59 +00004926 // Visit the protocols of protocols.
4927 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004928 if (Protocol->hasDefinition()) {
4929 const ObjCList<ObjCProtocolDecl> &Protocols
4930 = Protocol->getReferencedProtocols();
4931 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4932 E = Protocols.end();
4933 I != E; ++I)
4934 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004935 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00004936 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00004937 }
4938
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004939 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004940 return;
4941
4942 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00004943 for (auto *I : IFace->protocols())
4944 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004945 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004946
4947 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00004948 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004949 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004950 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004951 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004952
4953 // Add a categories protocol methods.
4954 const ObjCList<ObjCProtocolDecl> &Protocols
4955 = CatDecl->getReferencedProtocols();
4956 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4957 E = Protocols.end();
4958 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004959 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004960 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004961 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004962
4963 // Add methods in category implementations.
4964 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004965 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004966 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004967 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004968 }
4969
4970 // Add methods in superclass.
4971 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004972 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004973 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004974 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004975
4976 // Add methods in our implementation, if any.
4977 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004978 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004979 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004980 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004981}
4982
4983
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004984void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00004985 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004986 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004987 if (!Class) {
4988 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004989 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004990 Class = Category->getClassInterface();
4991
4992 if (!Class)
4993 return;
4994 }
4995
4996 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004997 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004998 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004999 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005000 Results.EnterNewScope();
5001
Douglas Gregor1154e272010-09-16 16:06:31 +00005002 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005003 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005004 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005005 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005006 HandleCodeCompleteResults(this, CodeCompleter,
5007 CodeCompletionContext::CCC_Other,
5008 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005009}
5010
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005011void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005012 // Try to find the interface where setters might live.
5013 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005014 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005015 if (!Class) {
5016 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005017 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005018 Class = Category->getClassInterface();
5019
5020 if (!Class)
5021 return;
5022 }
5023
5024 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005025 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005026 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005027 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005028 Results.EnterNewScope();
5029
Douglas Gregor1154e272010-09-16 16:06:31 +00005030 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005031 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005032 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005033
5034 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005035 HandleCodeCompleteResults(this, CodeCompleter,
5036 CodeCompletionContext::CCC_Other,
5037 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005038}
5039
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005040void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5041 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005042 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005043 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005044 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005045 Results.EnterNewScope();
5046
5047 // Add context-sensitive, Objective-C parameter-passing keywords.
5048 bool AddedInOut = false;
5049 if ((DS.getObjCDeclQualifier() &
5050 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5051 Results.AddResult("in");
5052 Results.AddResult("inout");
5053 AddedInOut = true;
5054 }
5055 if ((DS.getObjCDeclQualifier() &
5056 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5057 Results.AddResult("out");
5058 if (!AddedInOut)
5059 Results.AddResult("inout");
5060 }
5061 if ((DS.getObjCDeclQualifier() &
5062 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5063 ObjCDeclSpec::DQ_Oneway)) == 0) {
5064 Results.AddResult("bycopy");
5065 Results.AddResult("byref");
5066 Results.AddResult("oneway");
5067 }
5068
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005069 // If we're completing the return type of an Objective-C method and the
5070 // identifier IBAction refers to a macro, provide a completion item for
5071 // an action, e.g.,
5072 // IBAction)<#selector#>:(id)sender
5073 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5074 Context.Idents.get("IBAction").hasMacroDefinition()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005075 CodeCompletionBuilder Builder(Results.getAllocator(),
5076 Results.getCodeCompletionTUInfo(),
5077 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005078 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005080 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005081 Builder.AddChunk(CodeCompletionString::CK_Colon);
5082 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005083 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005084 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005085 Builder.AddTextChunk("sender");
5086 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5087 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005088
5089 // If we're completing the return type, provide 'instancetype'.
5090 if (!IsParameter) {
5091 Results.AddResult(CodeCompletionResult("instancetype"));
5092 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005093
Douglas Gregor99fa2642010-08-24 01:06:58 +00005094 // Add various builtin type names and specifiers.
5095 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5096 Results.ExitScope();
5097
5098 // Add the various type names
5099 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5100 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5101 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5102 CodeCompleter->includeGlobals());
5103
5104 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005105 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005106
5107 HandleCodeCompleteResults(this, CodeCompleter,
5108 CodeCompletionContext::CCC_Type,
5109 Results.data(), Results.size());
5110}
5111
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005112/// \brief When we have an expression with type "id", we may assume
5113/// that it has some more-specific class type based on knowledge of
5114/// common uses of Objective-C. This routine returns that class type,
5115/// or NULL if no better result could be determined.
5116static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005117 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005118 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005119 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005120
5121 Selector Sel = Msg->getSelector();
5122 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005123 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005124
5125 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5126 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005127 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005128
5129 ObjCMethodDecl *Method = Msg->getMethodDecl();
5130 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005131 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005132
5133 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005134 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005135 switch (Msg->getReceiverKind()) {
5136 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005137 if (const ObjCObjectType *ObjType
5138 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5139 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005140 break;
5141
5142 case ObjCMessageExpr::Instance: {
5143 QualType T = Msg->getInstanceReceiver()->getType();
5144 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5145 IFace = Ptr->getInterfaceDecl();
5146 break;
5147 }
5148
5149 case ObjCMessageExpr::SuperInstance:
5150 case ObjCMessageExpr::SuperClass:
5151 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005152 }
5153
5154 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005156
5157 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5158 if (Method->isInstanceMethod())
5159 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5160 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005161 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005162 .Case("autorelease", IFace)
5163 .Case("copy", IFace)
5164 .Case("copyWithZone", IFace)
5165 .Case("mutableCopy", IFace)
5166 .Case("mutableCopyWithZone", IFace)
5167 .Case("awakeFromCoder", IFace)
5168 .Case("replacementObjectFromCoder", IFace)
5169 .Case("class", IFace)
5170 .Case("classForCoder", IFace)
5171 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005172 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005173
5174 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5175 .Case("new", IFace)
5176 .Case("alloc", IFace)
5177 .Case("allocWithZone", IFace)
5178 .Case("class", IFace)
5179 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005180 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005181}
5182
Douglas Gregor6fc04132010-08-27 15:10:57 +00005183// Add a special completion for a message send to "super", which fills in the
5184// most likely case of forwarding all of our arguments to the superclass
5185// function.
5186///
5187/// \param S The semantic analysis object.
5188///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005189/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005190/// the "super" keyword. Otherwise, we just need to provide the arguments.
5191///
5192/// \param SelIdents The identifiers in the selector that have already been
5193/// provided as arguments for a send to "super".
5194///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005195/// \param Results The set of results to augment.
5196///
5197/// \returns the Objective-C method declaration that would be invoked by
5198/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005199static ObjCMethodDecl *AddSuperSendCompletion(
5200 Sema &S, bool NeedSuperKeyword,
5201 ArrayRef<IdentifierInfo *> SelIdents,
5202 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005203 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5204 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005205 return nullptr;
5206
Douglas Gregor6fc04132010-08-27 15:10:57 +00005207 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5208 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005209 return nullptr;
5210
Douglas Gregor6fc04132010-08-27 15:10:57 +00005211 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005212 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005213 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5214 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005215 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5216 CurMethod->isInstanceMethod());
5217
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005218 // Check in categories or class extensions.
5219 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005220 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005221 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005222 CurMethod->isInstanceMethod())))
5223 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005224 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005225 }
5226 }
5227
Douglas Gregor6fc04132010-08-27 15:10:57 +00005228 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005229 return nullptr;
5230
Douglas Gregor6fc04132010-08-27 15:10:57 +00005231 // Check whether the superclass method has the same signature.
5232 if (CurMethod->param_size() != SuperMethod->param_size() ||
5233 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005234 return nullptr;
5235
Douglas Gregor6fc04132010-08-27 15:10:57 +00005236 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5237 CurPEnd = CurMethod->param_end(),
5238 SuperP = SuperMethod->param_begin();
5239 CurP != CurPEnd; ++CurP, ++SuperP) {
5240 // Make sure the parameter types are compatible.
5241 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5242 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005243 return nullptr;
5244
Douglas Gregor6fc04132010-08-27 15:10:57 +00005245 // Make sure we have a parameter name to forward!
5246 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005247 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005248 }
5249
5250 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005251 CodeCompletionBuilder Builder(Results.getAllocator(),
5252 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005253
5254 // Give this completion a return type.
Douglas Gregor75acd922011-09-27 23:30:47 +00005255 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5256 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005257
5258 // If we need the "super" keyword, add it (plus some spacing).
5259 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005260 Builder.AddTypedTextChunk("super");
5261 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005262 }
5263
5264 Selector Sel = CurMethod->getSelector();
5265 if (Sel.isUnarySelector()) {
5266 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005267 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005268 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005269 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005270 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005271 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005272 } else {
5273 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5274 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005275 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005276 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005277
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005278 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005279 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005280 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005281 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005282 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005283 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005284 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005285 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005286 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005287 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005288 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005289 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005290 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005291 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005292 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005293 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005294 }
5295 }
5296 }
5297
Douglas Gregor78254c82012-03-27 23:34:16 +00005298 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5299 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005300 return SuperMethod;
5301}
5302
Douglas Gregora817a192010-05-27 23:06:34 +00005303void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005304 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005305 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005306 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005307 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005308 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005309 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5310 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005311
Douglas Gregora817a192010-05-27 23:06:34 +00005312 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5313 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005314 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5315 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005316
5317 // If we are in an Objective-C method inside a class that has a superclass,
5318 // add "super" as an option.
5319 if (ObjCMethodDecl *Method = getCurMethodDecl())
5320 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005321 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005322 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005323
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005324 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005325 }
Douglas Gregora817a192010-05-27 23:06:34 +00005326
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005327 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005328 addThisCompletion(*this, Results);
5329
Douglas Gregora817a192010-05-27 23:06:34 +00005330 Results.ExitScope();
5331
5332 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005333 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005334 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005335 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005336
5337}
5338
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005339void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005340 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005341 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005342 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005343 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5344 // Figure out which interface we're in.
5345 CDecl = CurMethod->getClassInterface();
5346 if (!CDecl)
5347 return;
5348
5349 // Find the superclass of this class.
5350 CDecl = CDecl->getSuperClass();
5351 if (!CDecl)
5352 return;
5353
5354 if (CurMethod->isInstanceMethod()) {
5355 // We are inside an instance method, which means that the message
5356 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005357 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005358 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005359 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005360 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005361 }
5362
5363 // Fall through to send to the superclass in CDecl.
5364 } else {
5365 // "super" may be the name of a type or variable. Figure out which
5366 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005367 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005368 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5369 LookupOrdinaryName);
5370 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5371 // "super" names an interface. Use it.
5372 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005373 if (const ObjCObjectType *Iface
5374 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5375 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005376 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5377 // "super" names an unresolved type; we can't be more specific.
5378 } else {
5379 // Assume that "super" names some kind of value and parse that way.
5380 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005381 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005382 UnqualifiedId id;
5383 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005384 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5385 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005386 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005387 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005388 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005389 }
5390
5391 // Fall through
5392 }
5393
John McCallba7bf592010-08-24 05:47:05 +00005394 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005395 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005396 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005397 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005398 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005399 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005400}
5401
Douglas Gregor74661272010-09-21 00:03:25 +00005402/// \brief Given a set of code-completion results for the argument of a message
5403/// send, determine the preferred type (if any) for that argument expression.
5404static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5405 unsigned NumSelIdents) {
5406 typedef CodeCompletionResult Result;
5407 ASTContext &Context = Results.getSema().Context;
5408
5409 QualType PreferredType;
5410 unsigned BestPriority = CCP_Unlikely * 2;
5411 Result *ResultsData = Results.data();
5412 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5413 Result &R = ResultsData[I];
5414 if (R.Kind == Result::RK_Declaration &&
5415 isa<ObjCMethodDecl>(R.Declaration)) {
5416 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005417 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005418 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005419 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005420 ->getType();
5421 if (R.Priority < BestPriority || PreferredType.isNull()) {
5422 BestPriority = R.Priority;
5423 PreferredType = MyPreferredType;
5424 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5425 MyPreferredType)) {
5426 PreferredType = QualType();
5427 }
5428 }
5429 }
5430 }
5431 }
5432
5433 return PreferredType;
5434}
5435
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005436static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5437 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005438 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005439 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005440 bool IsSuper,
5441 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005442 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005443 ObjCInterfaceDecl *CDecl = nullptr;
5444
Douglas Gregor8ce33212009-11-17 17:59:40 +00005445 // If the given name refers to an interface type, retrieve the
5446 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005447 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005448 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005449 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005450 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5451 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005452 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005453
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005454 // Add all of the factory methods in this Objective-C class, its protocols,
5455 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005456 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005457
Douglas Gregor6fc04132010-08-27 15:10:57 +00005458 // If this is a send-to-super, try to add the special "super" send
5459 // completion.
5460 if (IsSuper) {
5461 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005462 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005463 Results.Ignore(SuperMethod);
5464 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005465
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005466 // If we're inside an Objective-C method definition, prefer its selector to
5467 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005468 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005469 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005470
Douglas Gregor1154e272010-09-16 16:06:31 +00005471 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005472 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005473 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005474 SemaRef.CurContext, Selectors, AtArgumentExpression,
5475 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005476 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005477 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005478
Douglas Gregord720daf2010-04-06 17:30:22 +00005479 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005480 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005481 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005482 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005483 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005484 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005485 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005486 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005487 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005488
5489 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005490 }
5491 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005492
5493 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5494 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005495 M != MEnd; ++M) {
5496 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005497 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005498 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005499 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005500 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005501
Nico Weber2e0c8f72014-12-27 03:58:08 +00005502 Result R(MethList->getMethod(),
5503 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005504 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005505 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005506 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005507 }
5508 }
5509 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005510
5511 Results.ExitScope();
5512}
Douglas Gregor6285f752010-04-06 16:40:00 +00005513
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005514void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005515 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005516 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005517 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005518
5519 QualType T = this->GetTypeFromParser(Receiver);
5520
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005521 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005522 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005523 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005524 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005525
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005526 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005527 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005528
5529 // If we're actually at the argument expression (rather than prior to the
5530 // selector), we're actually performing code completion for an expression.
5531 // Determine whether we have a single, best method. If so, we can
5532 // code-complete the expression using the corresponding parameter type as
5533 // our preferred type, improving completion results.
5534 if (AtArgumentExpression) {
5535 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005536 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005537 if (PreferredType.isNull())
5538 CodeCompleteOrdinaryName(S, PCC_Expression);
5539 else
5540 CodeCompleteExpression(S, PreferredType);
5541 return;
5542 }
5543
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005544 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005545 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005546 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005547}
5548
Richard Trieu2bd04012011-09-09 02:00:50 +00005549void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005550 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005551 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005552 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005553 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005554
5555 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005556
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005557 // If necessary, apply function/array conversion to the receiver.
5558 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005559 if (RecExpr) {
5560 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5561 if (Conv.isInvalid()) // conversion failed. bail.
5562 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005563 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005564 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005565 QualType ReceiverType = RecExpr? RecExpr->getType()
5566 : Super? Context.getObjCObjectPointerType(
5567 Context.getObjCInterfaceType(Super))
5568 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005569
Douglas Gregordc520b02010-11-08 21:12:30 +00005570 // If we're messaging an expression with type "id" or "Class", check
5571 // whether we know something special about the receiver that allows
5572 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005573 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005574 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5575 if (ReceiverType->isObjCClassType())
5576 return CodeCompleteObjCClassMessage(S,
5577 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005578 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005579 AtArgumentExpression, Super);
5580
5581 ReceiverType = Context.getObjCObjectPointerType(
5582 Context.getObjCInterfaceType(IFace));
5583 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005584 } else if (RecExpr && getLangOpts().CPlusPlus) {
5585 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5586 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005587 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005588 ReceiverType = RecExpr->getType();
5589 }
5590 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005591
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005592 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005593 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005594 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005595 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005596 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005597
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005598 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005599
Douglas Gregor6fc04132010-08-27 15:10:57 +00005600 // If this is a send-to-super, try to add the special "super" send
5601 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005602 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005603 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005604 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005605 Results.Ignore(SuperMethod);
5606 }
5607
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005608 // If we're inside an Objective-C method definition, prefer its selector to
5609 // others.
5610 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5611 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005612
Douglas Gregor1154e272010-09-16 16:06:31 +00005613 // Keep track of the selectors we've already added.
5614 VisitedSelectorSet Selectors;
5615
Douglas Gregora3329fa2009-11-18 00:06:18 +00005616 // Handle messages to Class. This really isn't a message to an instance
5617 // method, so we treat it the same way we would treat a message send to a
5618 // class method.
5619 if (ReceiverType->isObjCClassType() ||
5620 ReceiverType->isObjCQualifiedClassType()) {
5621 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5622 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005623 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005624 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005625 }
5626 }
5627 // Handle messages to a qualified ID ("id<foo>").
5628 else if (const ObjCObjectPointerType *QualID
5629 = ReceiverType->getAsObjCQualifiedIdType()) {
5630 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005631 for (auto *I : QualID->quals())
5632 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005633 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005634 }
5635 // Handle messages to a pointer to interface type.
5636 else if (const ObjCObjectPointerType *IFacePtr
5637 = ReceiverType->getAsObjCInterfacePointerType()) {
5638 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005639 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005640 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005641 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005642
5643 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005644 for (auto *I : IFacePtr->quals())
5645 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005646 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005647 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005648 // Handle messages to "id".
5649 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005650 // We're messaging "id", so provide all instance methods we know
5651 // about as code-completion results.
5652
5653 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005654 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005655 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005656 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5657 I != N; ++I) {
5658 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005659 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005660 continue;
5661
Sebastian Redl75d8a322010-08-02 23:18:59 +00005662 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005663 }
5664 }
5665
Sebastian Redl75d8a322010-08-02 23:18:59 +00005666 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5667 MEnd = MethodPool.end();
5668 M != MEnd; ++M) {
5669 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005670 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005671 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005672 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005673 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005674
Nico Weber2e0c8f72014-12-27 03:58:08 +00005675 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005676 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005677
Nico Weber2e0c8f72014-12-27 03:58:08 +00005678 Result R(MethList->getMethod(),
5679 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005680 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005681 R.AllParametersAreInformative = false;
5682 Results.MaybeAddResult(R, CurContext);
5683 }
5684 }
5685 }
Steve Naroffeae65032009-11-07 02:08:14 +00005686 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005687
5688
5689 // If we're actually at the argument expression (rather than prior to the
5690 // selector), we're actually performing code completion for an expression.
5691 // Determine whether we have a single, best method. If so, we can
5692 // code-complete the expression using the corresponding parameter type as
5693 // our preferred type, improving completion results.
5694 if (AtArgumentExpression) {
5695 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005696 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005697 if (PreferredType.isNull())
5698 CodeCompleteOrdinaryName(S, PCC_Expression);
5699 else
5700 CodeCompleteExpression(S, PreferredType);
5701 return;
5702 }
5703
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005704 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005705 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005706 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005707}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005708
Douglas Gregor68762e72010-08-23 21:17:50 +00005709void Sema::CodeCompleteObjCForCollection(Scope *S,
5710 DeclGroupPtrTy IterationVar) {
5711 CodeCompleteExpressionData Data;
5712 Data.ObjCCollection = true;
5713
5714 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005715 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005716 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5717 if (*I)
5718 Data.IgnoreDecls.push_back(*I);
5719 }
5720 }
5721
5722 CodeCompleteExpression(S, Data);
5723}
5724
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005725void Sema::CodeCompleteObjCSelector(Scope *S,
5726 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005727 // If we have an external source, load the entire class method
5728 // pool from the AST file.
5729 if (ExternalSource) {
5730 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5731 I != N; ++I) {
5732 Selector Sel = ExternalSource->GetExternalSelector(I);
5733 if (Sel.isNull() || MethodPool.count(Sel))
5734 continue;
5735
5736 ReadMethodPool(Sel);
5737 }
5738 }
5739
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005740 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005741 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005742 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005743 Results.EnterNewScope();
5744 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5745 MEnd = MethodPool.end();
5746 M != MEnd; ++M) {
5747
5748 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005749 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005750 continue;
5751
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005752 CodeCompletionBuilder Builder(Results.getAllocator(),
5753 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005754 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005755 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005756 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005757 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005758 continue;
5759 }
5760
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005761 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005762 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005763 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005764 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005765 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005766 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005767 Accumulator.clear();
5768 }
5769 }
5770
Benjamin Kramer632500c2011-07-26 16:59:25 +00005771 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005772 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005773 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005774 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005775 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005776 }
5777 Results.ExitScope();
5778
5779 HandleCodeCompleteResults(this, CodeCompleter,
5780 CodeCompletionContext::CCC_SelectorName,
5781 Results.data(), Results.size());
5782}
5783
Douglas Gregorbaf69612009-11-18 04:19:12 +00005784/// \brief Add all of the protocol declarations that we find in the given
5785/// (translation unit) context.
5786static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005787 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005788 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005789 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005790
Aaron Ballman629afae2014-03-07 19:56:05 +00005791 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005792 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005793 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005794 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005795 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5796 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005797 }
5798}
5799
5800void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5801 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005802 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005803 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005804 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005805
Douglas Gregora3b23b02010-12-09 21:44:02 +00005806 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5807 Results.EnterNewScope();
5808
5809 // Tell the result set to ignore all of the protocols we have
5810 // already seen.
5811 // FIXME: This doesn't work when caching code-completion results.
5812 for (unsigned I = 0; I != NumProtocols; ++I)
5813 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5814 Protocols[I].second))
5815 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005816
Douglas Gregora3b23b02010-12-09 21:44:02 +00005817 // Add all protocols.
5818 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5819 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005820
Douglas Gregora3b23b02010-12-09 21:44:02 +00005821 Results.ExitScope();
5822 }
5823
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005824 HandleCodeCompleteResults(this, CodeCompleter,
5825 CodeCompletionContext::CCC_ObjCProtocolName,
5826 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005827}
5828
5829void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005830 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005831 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005832 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005833
Douglas Gregora3b23b02010-12-09 21:44:02 +00005834 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5835 Results.EnterNewScope();
5836
5837 // Add all protocols.
5838 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5839 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005840
Douglas Gregora3b23b02010-12-09 21:44:02 +00005841 Results.ExitScope();
5842 }
5843
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005844 HandleCodeCompleteResults(this, CodeCompleter,
5845 CodeCompletionContext::CCC_ObjCProtocolName,
5846 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005847}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005848
5849/// \brief Add all of the Objective-C interface declarations that we find in
5850/// the given (translation unit) context.
5851static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5852 bool OnlyForwardDeclarations,
5853 bool OnlyUnimplemented,
5854 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005855 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005856
Aaron Ballman629afae2014-03-07 19:56:05 +00005857 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005858 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005859 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005860 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005861 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005862 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5863 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005864 }
5865}
5866
5867void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005868 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005869 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005870 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005871 Results.EnterNewScope();
5872
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005873 if (CodeCompleter->includeGlobals()) {
5874 // Add all classes.
5875 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5876 false, Results);
5877 }
5878
Douglas Gregor49c22a72009-11-18 16:26:39 +00005879 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005880
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005881 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005882 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005883 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005884}
5885
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005886void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5887 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005888 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005889 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005890 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005891 Results.EnterNewScope();
5892
5893 // Make sure that we ignore the class we're currently defining.
5894 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005895 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005896 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00005897 Results.Ignore(CurClass);
5898
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005899 if (CodeCompleter->includeGlobals()) {
5900 // Add all classes.
5901 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5902 false, Results);
5903 }
5904
Douglas Gregor49c22a72009-11-18 16:26:39 +00005905 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005906
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005907 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005908 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005909 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005910}
5911
5912void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005913 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005914 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005915 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005916 Results.EnterNewScope();
5917
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005918 if (CodeCompleter->includeGlobals()) {
5919 // Add all unimplemented classes.
5920 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5921 true, Results);
5922 }
5923
Douglas Gregor49c22a72009-11-18 16:26:39 +00005924 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005925
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005926 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005927 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005928 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005929}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005930
5931void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005932 IdentifierInfo *ClassName,
5933 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005934 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005935
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005936 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005937 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00005938 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005939
5940 // Ignore any categories we find that have already been implemented by this
5941 // interface.
5942 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5943 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005944 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005945 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00005946 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005947 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005948 }
5949
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005950 // Add all of the categories we know about.
5951 Results.EnterNewScope();
5952 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00005953 for (const auto *D : TU->decls())
5954 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00005955 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00005956 Results.AddResult(Result(Category, Results.getBasePriority(Category),
5957 nullptr),
5958 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005959 Results.ExitScope();
5960
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005961 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005962 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005963 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005964}
5965
5966void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005967 IdentifierInfo *ClassName,
5968 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005969 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005970
5971 // Find the corresponding interface. If we couldn't find the interface, the
5972 // program itself is ill-formed. However, we'll try to be helpful still by
5973 // providing the list of all of the categories we know about.
5974 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005975 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005976 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5977 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005978 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005979
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005980 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005981 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00005982 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005983
5984 // Add all of the categories that have have corresponding interface
5985 // declarations in this class and any of its superclasses, except for
5986 // already-implemented categories in the class itself.
5987 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5988 Results.EnterNewScope();
5989 bool IgnoreImplemented = true;
5990 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00005991 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005992 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00005993 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00005994 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
5995 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005996 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005997
5998 Class = Class->getSuperClass();
5999 IgnoreImplemented = false;
6000 }
6001 Results.ExitScope();
6002
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006003 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006004 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006005 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006006}
Douglas Gregor5d649882009-11-18 22:32:06 +00006007
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006008void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006009 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006010 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006011 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006012
6013 // Figure out where this @synthesize lives.
6014 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006015 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006016 if (!Container ||
6017 (!isa<ObjCImplementationDecl>(Container) &&
6018 !isa<ObjCCategoryImplDecl>(Container)))
6019 return;
6020
6021 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006022 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006023 for (const auto *D : Container->decls())
6024 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006025 Results.Ignore(PropertyImpl->getPropertyDecl());
6026
6027 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006028 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006029 Results.EnterNewScope();
6030 if (ObjCImplementationDecl *ClassImpl
6031 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor95147142011-05-05 15:50:42 +00006032 AddObjCProperties(ClassImpl->getClassInterface(), false,
6033 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006034 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006035 else
6036 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006037 false, /*AllowNullaryMethods=*/false, CurContext,
6038 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006039 Results.ExitScope();
6040
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006041 HandleCodeCompleteResults(this, CodeCompleter,
6042 CodeCompletionContext::CCC_Other,
6043 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006044}
6045
6046void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006047 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006048 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006049 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006050 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006051 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006052
6053 // Figure out where this @synthesize lives.
6054 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006055 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006056 if (!Container ||
6057 (!isa<ObjCImplementationDecl>(Container) &&
6058 !isa<ObjCCategoryImplDecl>(Container)))
6059 return;
6060
6061 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006062 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006063 if (ObjCImplementationDecl *ClassImpl
6064 = dyn_cast<ObjCImplementationDecl>(Container))
6065 Class = ClassImpl->getClassInterface();
6066 else
6067 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6068 ->getClassInterface();
6069
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006070 // Determine the type of the property we're synthesizing.
6071 QualType PropertyType = Context.getObjCIdType();
6072 if (Class) {
6073 if (ObjCPropertyDecl *Property
6074 = Class->FindPropertyDeclaration(PropertyName)) {
6075 PropertyType
6076 = Property->getType().getNonReferenceType().getUnqualifiedType();
6077
6078 // Give preference to ivars
6079 Results.setPreferredType(PropertyType);
6080 }
6081 }
6082
Douglas Gregor5d649882009-11-18 22:32:06 +00006083 // Add all of the instance variables in this class and its superclasses.
6084 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006085 bool SawSimilarlyNamedIvar = false;
6086 std::string NameWithPrefix;
6087 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006088 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006089 std::string NameWithSuffix = PropertyName->getName().str();
6090 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006091 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006092 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6093 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006094 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6095 CurContext, nullptr, false);
6096
Douglas Gregor331faa02011-04-18 14:13:53 +00006097 // Determine whether we've seen an ivar with a name similar to the
6098 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006099 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006100 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006101 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006102 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006103
6104 // Reduce the priority of this result by one, to give it a slight
6105 // advantage over other results whose names don't match so closely.
6106 if (Results.size() &&
6107 Results.data()[Results.size() - 1].Kind
6108 == CodeCompletionResult::RK_Declaration &&
6109 Results.data()[Results.size() - 1].Declaration == Ivar)
6110 Results.data()[Results.size() - 1].Priority--;
6111 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006112 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006113 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006114
6115 if (!SawSimilarlyNamedIvar) {
6116 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006117 // an ivar of the appropriate type.
6118 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006119 typedef CodeCompletionResult Result;
6120 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006121 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6122 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006123
Douglas Gregor75acd922011-09-27 23:30:47 +00006124 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006125 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006126 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006127 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6128 Results.AddResult(Result(Builder.TakeString(), Priority,
6129 CXCursor_ObjCIvarDecl));
6130 }
6131
Douglas Gregor5d649882009-11-18 22:32:06 +00006132 Results.ExitScope();
6133
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006134 HandleCodeCompleteResults(this, CodeCompleter,
6135 CodeCompletionContext::CCC_Other,
6136 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006137}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006138
Douglas Gregor416b5752010-08-25 01:08:01 +00006139// Mapping from selectors to the methods that implement that selector, along
6140// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006141typedef llvm::DenseMap<
6142 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006143
6144/// \brief Find all of the methods that reside in the given container
6145/// (and its superclasses, protocols, etc.) that meet the given
6146/// criteria. Insert those methods into the map of known methods,
6147/// indexed by selector so they can be easily found.
6148static void FindImplementableMethods(ASTContext &Context,
6149 ObjCContainerDecl *Container,
6150 bool WantInstanceMethods,
6151 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006152 KnownMethodsMap &KnownMethods,
6153 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006154 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006155 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006156 if (!IFace->hasDefinition())
6157 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006158
6159 IFace = IFace->getDefinition();
6160 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006161
Douglas Gregor636a61e2010-04-07 00:21:17 +00006162 const ObjCList<ObjCProtocolDecl> &Protocols
6163 = IFace->getReferencedProtocols();
6164 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006165 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006166 I != E; ++I)
6167 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006168 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006169
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006170 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006171 for (auto *Cat : IFace->visible_categories()) {
6172 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006173 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006174 }
6175
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006176 // Visit the superclass.
6177 if (IFace->getSuperClass())
6178 FindImplementableMethods(Context, IFace->getSuperClass(),
6179 WantInstanceMethods, ReturnType,
6180 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006181 }
6182
6183 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6184 // Recurse into protocols.
6185 const ObjCList<ObjCProtocolDecl> &Protocols
6186 = Category->getReferencedProtocols();
6187 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006188 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006189 I != E; ++I)
6190 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006191 KnownMethods, InOriginalClass);
6192
6193 // If this category is the original class, jump to the interface.
6194 if (InOriginalClass && Category->getClassInterface())
6195 FindImplementableMethods(Context, Category->getClassInterface(),
6196 WantInstanceMethods, ReturnType, KnownMethods,
6197 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006198 }
6199
6200 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006201 // Make sure we have a definition; that's what we'll walk.
6202 if (!Protocol->hasDefinition())
6203 return;
6204 Protocol = Protocol->getDefinition();
6205 Container = Protocol;
6206
6207 // Recurse into protocols.
6208 const ObjCList<ObjCProtocolDecl> &Protocols
6209 = Protocol->getReferencedProtocols();
6210 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6211 E = Protocols.end();
6212 I != E; ++I)
6213 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6214 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006215 }
6216
6217 // Add methods in this container. This operation occurs last because
6218 // we want the methods from this container to override any methods
6219 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006220 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006221 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006222 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006223 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006224 continue;
6225
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006226 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006227 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006228 }
6229 }
6230}
6231
Douglas Gregor669a25a2011-02-17 00:22:45 +00006232/// \brief Add the parenthesized return or parameter type chunk to a code
6233/// completion string.
6234static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006235 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006236 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006237 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006238 CodeCompletionBuilder &Builder) {
6239 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor29979142012-04-10 18:35:07 +00006240 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6241 if (!Quals.empty())
6242 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006243 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006244 Builder.getAllocator()));
6245 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6246}
6247
6248/// \brief Determine whether the given class is or inherits from a class by
6249/// the given name.
6250static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006251 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006252 if (!Class)
6253 return false;
6254
6255 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6256 return true;
6257
6258 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6259}
6260
6261/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6262/// Key-Value Observing (KVO).
6263static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6264 bool IsInstanceMethod,
6265 QualType ReturnType,
6266 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006267 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006268 ResultBuilder &Results) {
6269 IdentifierInfo *PropName = Property->getIdentifier();
6270 if (!PropName || PropName->getLength() == 0)
6271 return;
6272
Douglas Gregor75acd922011-09-27 23:30:47 +00006273 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6274
Douglas Gregor669a25a2011-02-17 00:22:45 +00006275 // Builder that will create each code completion.
6276 typedef CodeCompletionResult Result;
6277 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006278 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006279
6280 // The selector table.
6281 SelectorTable &Selectors = Context.Selectors;
6282
6283 // The property name, copied into the code completion allocation region
6284 // on demand.
6285 struct KeyHolder {
6286 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006287 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006288 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006289
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006290 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006291 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6292
Douglas Gregor669a25a2011-02-17 00:22:45 +00006293 operator const char *() {
6294 if (CopiedKey)
6295 return CopiedKey;
6296
6297 return CopiedKey = Allocator.CopyString(Key);
6298 }
6299 } Key(Allocator, PropName->getName());
6300
6301 // The uppercased name of the property name.
6302 std::string UpperKey = PropName->getName();
6303 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006304 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006305
6306 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6307 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6308 Property->getType());
6309 bool ReturnTypeMatchesVoid
6310 = ReturnType.isNull() || ReturnType->isVoidType();
6311
6312 // Add the normal accessor -(type)key.
6313 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006314 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006315 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6316 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006317 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6318 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006319
6320 Builder.AddTypedTextChunk(Key);
6321 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6322 CXCursor_ObjCInstanceMethodDecl));
6323 }
6324
6325 // If we have an integral or boolean property (or the user has provided
6326 // an integral or boolean return type), add the accessor -(type)isKey.
6327 if (IsInstanceMethod &&
6328 ((!ReturnType.isNull() &&
6329 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6330 (ReturnType.isNull() &&
6331 (Property->getType()->isIntegerType() ||
6332 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006333 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006334 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006335 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6336 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006337 if (ReturnType.isNull()) {
6338 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6339 Builder.AddTextChunk("BOOL");
6340 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6341 }
6342
6343 Builder.AddTypedTextChunk(
6344 Allocator.CopyString(SelectorId->getName()));
6345 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6346 CXCursor_ObjCInstanceMethodDecl));
6347 }
6348 }
6349
6350 // Add the normal mutator.
6351 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6352 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006353 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006354 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006355 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006356 if (ReturnType.isNull()) {
6357 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6358 Builder.AddTextChunk("void");
6359 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6360 }
6361
6362 Builder.AddTypedTextChunk(
6363 Allocator.CopyString(SelectorId->getName()));
6364 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006365 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6366 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006367 Builder.AddTextChunk(Key);
6368 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6369 CXCursor_ObjCInstanceMethodDecl));
6370 }
6371 }
6372
6373 // Indexed and unordered accessors
6374 unsigned IndexedGetterPriority = CCP_CodePattern;
6375 unsigned IndexedSetterPriority = CCP_CodePattern;
6376 unsigned UnorderedGetterPriority = CCP_CodePattern;
6377 unsigned UnorderedSetterPriority = CCP_CodePattern;
6378 if (const ObjCObjectPointerType *ObjCPointer
6379 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6380 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6381 // If this interface type is not provably derived from a known
6382 // collection, penalize the corresponding completions.
6383 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6384 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6385 if (!InheritsFromClassNamed(IFace, "NSArray"))
6386 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6387 }
6388
6389 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6390 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6391 if (!InheritsFromClassNamed(IFace, "NSSet"))
6392 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6393 }
6394 }
6395 } else {
6396 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6397 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6398 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6399 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6400 }
6401
6402 // Add -(NSUInteger)countOf<key>
6403 if (IsInstanceMethod &&
6404 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006405 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006406 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006407 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6408 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006409 if (ReturnType.isNull()) {
6410 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6411 Builder.AddTextChunk("NSUInteger");
6412 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6413 }
6414
6415 Builder.AddTypedTextChunk(
6416 Allocator.CopyString(SelectorId->getName()));
6417 Results.AddResult(Result(Builder.TakeString(),
6418 std::min(IndexedGetterPriority,
6419 UnorderedGetterPriority),
6420 CXCursor_ObjCInstanceMethodDecl));
6421 }
6422 }
6423
6424 // Indexed getters
6425 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6426 if (IsInstanceMethod &&
6427 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006428 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006429 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006430 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006431 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006432 if (ReturnType.isNull()) {
6433 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6434 Builder.AddTextChunk("id");
6435 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6436 }
6437
6438 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6439 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6440 Builder.AddTextChunk("NSUInteger");
6441 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6442 Builder.AddTextChunk("index");
6443 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6444 CXCursor_ObjCInstanceMethodDecl));
6445 }
6446 }
6447
6448 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6449 if (IsInstanceMethod &&
6450 (ReturnType.isNull() ||
6451 (ReturnType->isObjCObjectPointerType() &&
6452 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6453 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6454 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006455 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006456 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006457 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006458 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006459 if (ReturnType.isNull()) {
6460 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6461 Builder.AddTextChunk("NSArray *");
6462 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6463 }
6464
6465 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6466 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6467 Builder.AddTextChunk("NSIndexSet *");
6468 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6469 Builder.AddTextChunk("indexes");
6470 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6471 CXCursor_ObjCInstanceMethodDecl));
6472 }
6473 }
6474
6475 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6476 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006477 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006478 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006479 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006480 &Context.Idents.get("range")
6481 };
6482
David Blaikie82e95a32014-11-19 07:49:47 +00006483 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006484 if (ReturnType.isNull()) {
6485 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6486 Builder.AddTextChunk("void");
6487 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6488 }
6489
6490 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6491 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6492 Builder.AddPlaceholderChunk("object-type");
6493 Builder.AddTextChunk(" **");
6494 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6495 Builder.AddTextChunk("buffer");
6496 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6497 Builder.AddTypedTextChunk("range:");
6498 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6499 Builder.AddTextChunk("NSRange");
6500 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6501 Builder.AddTextChunk("inRange");
6502 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6503 CXCursor_ObjCInstanceMethodDecl));
6504 }
6505 }
6506
6507 // Mutable indexed accessors
6508
6509 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6510 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006511 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006512 IdentifierInfo *SelectorIds[2] = {
6513 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006514 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006515 };
6516
David Blaikie82e95a32014-11-19 07:49:47 +00006517 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006518 if (ReturnType.isNull()) {
6519 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6520 Builder.AddTextChunk("void");
6521 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6522 }
6523
6524 Builder.AddTypedTextChunk("insertObject:");
6525 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6526 Builder.AddPlaceholderChunk("object-type");
6527 Builder.AddTextChunk(" *");
6528 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6529 Builder.AddTextChunk("object");
6530 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6531 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6532 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6533 Builder.AddPlaceholderChunk("NSUInteger");
6534 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6535 Builder.AddTextChunk("index");
6536 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6537 CXCursor_ObjCInstanceMethodDecl));
6538 }
6539 }
6540
6541 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6542 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006543 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006544 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006545 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006546 &Context.Idents.get("atIndexes")
6547 };
6548
David Blaikie82e95a32014-11-19 07:49:47 +00006549 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006550 if (ReturnType.isNull()) {
6551 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6552 Builder.AddTextChunk("void");
6553 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6554 }
6555
6556 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6558 Builder.AddTextChunk("NSArray *");
6559 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6560 Builder.AddTextChunk("array");
6561 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6562 Builder.AddTypedTextChunk("atIndexes:");
6563 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564 Builder.AddPlaceholderChunk("NSIndexSet *");
6565 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6566 Builder.AddTextChunk("indexes");
6567 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6568 CXCursor_ObjCInstanceMethodDecl));
6569 }
6570 }
6571
6572 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6573 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006574 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006575 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006576 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006577 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006578 if (ReturnType.isNull()) {
6579 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6580 Builder.AddTextChunk("void");
6581 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6582 }
6583
6584 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6586 Builder.AddTextChunk("NSUInteger");
6587 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6588 Builder.AddTextChunk("index");
6589 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6590 CXCursor_ObjCInstanceMethodDecl));
6591 }
6592 }
6593
6594 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6595 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006596 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006597 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006598 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006599 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006600 if (ReturnType.isNull()) {
6601 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6602 Builder.AddTextChunk("void");
6603 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6604 }
6605
6606 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6608 Builder.AddTextChunk("NSIndexSet *");
6609 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6610 Builder.AddTextChunk("indexes");
6611 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6612 CXCursor_ObjCInstanceMethodDecl));
6613 }
6614 }
6615
6616 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6617 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006618 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006619 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006620 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006621 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006622 &Context.Idents.get("withObject")
6623 };
6624
David Blaikie82e95a32014-11-19 07:49:47 +00006625 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006626 if (ReturnType.isNull()) {
6627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6628 Builder.AddTextChunk("void");
6629 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6630 }
6631
6632 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6633 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6634 Builder.AddPlaceholderChunk("NSUInteger");
6635 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6636 Builder.AddTextChunk("index");
6637 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6638 Builder.AddTypedTextChunk("withObject:");
6639 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6640 Builder.AddTextChunk("id");
6641 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6642 Builder.AddTextChunk("object");
6643 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6644 CXCursor_ObjCInstanceMethodDecl));
6645 }
6646 }
6647
6648 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6649 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006650 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006651 = (Twine("replace") + UpperKey + "AtIndexes").str();
6652 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006653 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006654 &Context.Idents.get(SelectorName1),
6655 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006656 };
6657
David Blaikie82e95a32014-11-19 07:49:47 +00006658 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006659 if (ReturnType.isNull()) {
6660 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6661 Builder.AddTextChunk("void");
6662 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6663 }
6664
6665 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6667 Builder.AddPlaceholderChunk("NSIndexSet *");
6668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6669 Builder.AddTextChunk("indexes");
6670 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6671 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6672 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6673 Builder.AddTextChunk("NSArray *");
6674 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6675 Builder.AddTextChunk("array");
6676 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6677 CXCursor_ObjCInstanceMethodDecl));
6678 }
6679 }
6680
6681 // Unordered getters
6682 // - (NSEnumerator *)enumeratorOfKey
6683 if (IsInstanceMethod &&
6684 (ReturnType.isNull() ||
6685 (ReturnType->isObjCObjectPointerType() &&
6686 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6687 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6688 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006689 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006690 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006691 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6692 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006693 if (ReturnType.isNull()) {
6694 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6695 Builder.AddTextChunk("NSEnumerator *");
6696 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6697 }
6698
6699 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6700 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6701 CXCursor_ObjCInstanceMethodDecl));
6702 }
6703 }
6704
6705 // - (type *)memberOfKey:(type *)object
6706 if (IsInstanceMethod &&
6707 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006708 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006709 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006710 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006711 if (ReturnType.isNull()) {
6712 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6713 Builder.AddPlaceholderChunk("object-type");
6714 Builder.AddTextChunk(" *");
6715 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6716 }
6717
6718 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6719 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6720 if (ReturnType.isNull()) {
6721 Builder.AddPlaceholderChunk("object-type");
6722 Builder.AddTextChunk(" *");
6723 } else {
6724 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006725 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006726 Builder.getAllocator()));
6727 }
6728 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6729 Builder.AddTextChunk("object");
6730 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6731 CXCursor_ObjCInstanceMethodDecl));
6732 }
6733 }
6734
6735 // Mutable unordered accessors
6736 // - (void)addKeyObject:(type *)object
6737 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006738 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006739 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006740 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006741 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006742 if (ReturnType.isNull()) {
6743 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6744 Builder.AddTextChunk("void");
6745 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6746 }
6747
6748 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6749 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6750 Builder.AddPlaceholderChunk("object-type");
6751 Builder.AddTextChunk(" *");
6752 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6753 Builder.AddTextChunk("object");
6754 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6755 CXCursor_ObjCInstanceMethodDecl));
6756 }
6757 }
6758
6759 // - (void)addKey:(NSSet *)objects
6760 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006761 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006762 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006763 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006764 if (ReturnType.isNull()) {
6765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6766 Builder.AddTextChunk("void");
6767 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6768 }
6769
6770 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6771 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6772 Builder.AddTextChunk("NSSet *");
6773 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6774 Builder.AddTextChunk("objects");
6775 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6776 CXCursor_ObjCInstanceMethodDecl));
6777 }
6778 }
6779
6780 // - (void)removeKeyObject:(type *)object
6781 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006782 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006783 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006784 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006785 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006786 if (ReturnType.isNull()) {
6787 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6788 Builder.AddTextChunk("void");
6789 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6790 }
6791
6792 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6793 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6794 Builder.AddPlaceholderChunk("object-type");
6795 Builder.AddTextChunk(" *");
6796 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6797 Builder.AddTextChunk("object");
6798 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6799 CXCursor_ObjCInstanceMethodDecl));
6800 }
6801 }
6802
6803 // - (void)removeKey:(NSSet *)objects
6804 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006805 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006806 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006807 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006808 if (ReturnType.isNull()) {
6809 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6810 Builder.AddTextChunk("void");
6811 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6812 }
6813
6814 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6815 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6816 Builder.AddTextChunk("NSSet *");
6817 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6818 Builder.AddTextChunk("objects");
6819 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6820 CXCursor_ObjCInstanceMethodDecl));
6821 }
6822 }
6823
6824 // - (void)intersectKey:(NSSet *)objects
6825 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006826 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006827 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006828 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006829 if (ReturnType.isNull()) {
6830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6831 Builder.AddTextChunk("void");
6832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6833 }
6834
6835 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6836 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6837 Builder.AddTextChunk("NSSet *");
6838 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6839 Builder.AddTextChunk("objects");
6840 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6841 CXCursor_ObjCInstanceMethodDecl));
6842 }
6843 }
6844
6845 // Key-Value Observing
6846 // + (NSSet *)keyPathsForValuesAffectingKey
6847 if (!IsInstanceMethod &&
6848 (ReturnType.isNull() ||
6849 (ReturnType->isObjCObjectPointerType() &&
6850 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6851 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6852 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006853 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006854 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006855 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006856 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6857 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006858 if (ReturnType.isNull()) {
6859 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6860 Builder.AddTextChunk("NSSet *");
6861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6862 }
6863
6864 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6865 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006866 CXCursor_ObjCClassMethodDecl));
6867 }
6868 }
6869
6870 // + (BOOL)automaticallyNotifiesObserversForKey
6871 if (!IsInstanceMethod &&
6872 (ReturnType.isNull() ||
6873 ReturnType->isIntegerType() ||
6874 ReturnType->isBooleanType())) {
6875 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006876 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00006877 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006878 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6879 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00006880 if (ReturnType.isNull()) {
6881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6882 Builder.AddTextChunk("BOOL");
6883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6884 }
6885
6886 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6887 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6888 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00006889 }
6890 }
6891}
6892
Douglas Gregor636a61e2010-04-07 00:21:17 +00006893void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6894 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006895 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006896 // Determine the return type of the method we're declaring, if
6897 // provided.
6898 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00006899 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006900 if (CurContext->isObjCContainer()) {
6901 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6902 IDecl = cast<Decl>(OCD);
6903 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006904 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00006905 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006906 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00006907 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006908 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6909 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006910 IsInImplementation = true;
6911 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006912 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006913 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006914 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006915 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00006916 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006917 }
6918
6919 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00006920 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00006921 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006922 }
6923
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006924 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006925 HandleCodeCompleteResults(this, CodeCompleter,
6926 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00006927 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006928 return;
6929 }
6930
6931 // Find all of the methods that we could declare/implement here.
6932 KnownMethodsMap KnownMethods;
6933 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006934 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006935
Douglas Gregor636a61e2010-04-07 00:21:17 +00006936 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00006937 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006938 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006939 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006940 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006941 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00006942 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006943 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6944 MEnd = KnownMethods.end();
6945 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006946 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006947 CodeCompletionBuilder Builder(Results.getAllocator(),
6948 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006949
6950 // If the result type was not already provided, add it to the
6951 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00006952 if (ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00006953 AddObjCPassingTypeChunk(Method->getReturnType(),
6954 Method->getObjCDeclQualifier(), Context, Policy,
6955 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006956
6957 Selector Sel = Method->getSelector();
6958
6959 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006960 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006961 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006962
6963 // Add parameters to the pattern.
6964 unsigned I = 0;
6965 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6966 PEnd = Method->param_end();
6967 P != PEnd; (void)++P, ++I) {
6968 // Add the part of the selector name.
6969 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006970 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006971 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006972 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6973 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006974 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006975 } else
6976 break;
6977
6978 // Add the parameter type.
Douglas Gregor29979142012-04-10 18:35:07 +00006979 AddObjCPassingTypeChunk((*P)->getOriginalType(),
6980 (*P)->getObjCDeclQualifier(),
6981 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00006982 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006983
6984 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006985 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006986 }
6987
6988 if (Method->isVariadic()) {
6989 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006990 Builder.AddChunk(CodeCompletionString::CK_Comma);
6991 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00006992 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00006993
Douglas Gregord37c59d2010-05-28 00:57:46 +00006994 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006995 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6997 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6998 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00006999 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007000 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007001 Builder.AddTextChunk("return");
7002 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7003 Builder.AddPlaceholderChunk("expression");
7004 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007005 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007006 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007007
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007008 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7009 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007010 }
7011
Douglas Gregor416b5752010-08-25 01:08:01 +00007012 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007013 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007014 Priority += CCD_InBaseClass;
7015
Douglas Gregor78254c82012-03-27 23:34:16 +00007016 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007017 }
7018
Douglas Gregor669a25a2011-02-17 00:22:45 +00007019 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7020 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007021 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007022 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007023 Containers.push_back(SearchDecl);
7024
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007025 VisitedSelectorSet KnownSelectors;
7026 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7027 MEnd = KnownMethods.end();
7028 M != MEnd; ++M)
7029 KnownSelectors.insert(M->first);
7030
7031
Douglas Gregor669a25a2011-02-17 00:22:45 +00007032 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7033 if (!IFace)
7034 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7035 IFace = Category->getClassInterface();
7036
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007037 if (IFace)
7038 for (auto *Cat : IFace->visible_categories())
7039 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007040
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007041 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Aaron Ballmand174edf2014-03-13 19:11:50 +00007042 for (auto *P : Containers[I]->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007043 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007044 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007045 }
7046
Douglas Gregor636a61e2010-04-07 00:21:17 +00007047 Results.ExitScope();
7048
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007049 HandleCodeCompleteResults(this, CodeCompleter,
7050 CodeCompletionContext::CCC_Other,
7051 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007052}
Douglas Gregor95887f92010-07-08 23:20:03 +00007053
7054void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7055 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007056 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007057 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007058 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007059 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007060 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007061 if (ExternalSource) {
7062 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7063 I != N; ++I) {
7064 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007065 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007066 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007067
7068 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007069 }
7070 }
7071
7072 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007073 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007074 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007075 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007076 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007077
7078 if (ReturnTy)
7079 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007080
Douglas Gregor95887f92010-07-08 23:20:03 +00007081 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007082 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7083 MEnd = MethodPool.end();
7084 M != MEnd; ++M) {
7085 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7086 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007087 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007088 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007089 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007090 continue;
7091
Douglas Gregor45879692010-07-08 23:37:41 +00007092 if (AtParameterName) {
7093 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007094 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007095 if (NumSelIdents &&
7096 NumSelIdents <= MethList->getMethod()->param_size()) {
7097 ParmVarDecl *Param =
7098 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007099 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007100 CodeCompletionBuilder Builder(Results.getAllocator(),
7101 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007102 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007103 Param->getIdentifier()->getName()));
7104 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007105 }
7106 }
7107
7108 continue;
7109 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007110
Nico Weber2e0c8f72014-12-27 03:58:08 +00007111 Result R(MethList->getMethod(),
7112 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007113 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007114 R.AllParametersAreInformative = false;
7115 R.DeclaringEntity = true;
7116 Results.MaybeAddResult(R, CurContext);
7117 }
7118 }
7119
7120 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007121 HandleCodeCompleteResults(this, CodeCompleter,
7122 CodeCompletionContext::CCC_Other,
7123 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007124}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007125
Douglas Gregorec00a262010-08-24 22:20:20 +00007126void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007127 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007128 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007129 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007130 Results.EnterNewScope();
7131
7132 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007133 CodeCompletionBuilder Builder(Results.getAllocator(),
7134 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007135 Builder.AddTypedTextChunk("if");
7136 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7137 Builder.AddPlaceholderChunk("condition");
7138 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007139
7140 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007141 Builder.AddTypedTextChunk("ifdef");
7142 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7143 Builder.AddPlaceholderChunk("macro");
7144 Results.AddResult(Builder.TakeString());
7145
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007146 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007147 Builder.AddTypedTextChunk("ifndef");
7148 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7149 Builder.AddPlaceholderChunk("macro");
7150 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007151
7152 if (InConditional) {
7153 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007154 Builder.AddTypedTextChunk("elif");
7155 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7156 Builder.AddPlaceholderChunk("condition");
7157 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007158
7159 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007160 Builder.AddTypedTextChunk("else");
7161 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007162
7163 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007164 Builder.AddTypedTextChunk("endif");
7165 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007166 }
7167
7168 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007169 Builder.AddTypedTextChunk("include");
7170 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7171 Builder.AddTextChunk("\"");
7172 Builder.AddPlaceholderChunk("header");
7173 Builder.AddTextChunk("\"");
7174 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007175
7176 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007177 Builder.AddTypedTextChunk("include");
7178 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7179 Builder.AddTextChunk("<");
7180 Builder.AddPlaceholderChunk("header");
7181 Builder.AddTextChunk(">");
7182 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007183
7184 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007185 Builder.AddTypedTextChunk("define");
7186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7187 Builder.AddPlaceholderChunk("macro");
7188 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007189
7190 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007191 Builder.AddTypedTextChunk("define");
7192 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7193 Builder.AddPlaceholderChunk("macro");
7194 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7195 Builder.AddPlaceholderChunk("args");
7196 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7197 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007198
7199 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007200 Builder.AddTypedTextChunk("undef");
7201 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7202 Builder.AddPlaceholderChunk("macro");
7203 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007204
7205 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007206 Builder.AddTypedTextChunk("line");
7207 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7208 Builder.AddPlaceholderChunk("number");
7209 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007210
7211 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007212 Builder.AddTypedTextChunk("line");
7213 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7214 Builder.AddPlaceholderChunk("number");
7215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7216 Builder.AddTextChunk("\"");
7217 Builder.AddPlaceholderChunk("filename");
7218 Builder.AddTextChunk("\"");
7219 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007220
7221 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007222 Builder.AddTypedTextChunk("error");
7223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7224 Builder.AddPlaceholderChunk("message");
7225 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007226
7227 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007228 Builder.AddTypedTextChunk("pragma");
7229 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7230 Builder.AddPlaceholderChunk("arguments");
7231 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007232
David Blaikiebbafb8a2012-03-11 07:00:24 +00007233 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007234 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007235 Builder.AddTypedTextChunk("import");
7236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7237 Builder.AddTextChunk("\"");
7238 Builder.AddPlaceholderChunk("header");
7239 Builder.AddTextChunk("\"");
7240 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007241
7242 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007243 Builder.AddTypedTextChunk("import");
7244 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7245 Builder.AddTextChunk("<");
7246 Builder.AddPlaceholderChunk("header");
7247 Builder.AddTextChunk(">");
7248 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007249 }
7250
7251 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007252 Builder.AddTypedTextChunk("include_next");
7253 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7254 Builder.AddTextChunk("\"");
7255 Builder.AddPlaceholderChunk("header");
7256 Builder.AddTextChunk("\"");
7257 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007258
7259 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007260 Builder.AddTypedTextChunk("include_next");
7261 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7262 Builder.AddTextChunk("<");
7263 Builder.AddPlaceholderChunk("header");
7264 Builder.AddTextChunk(">");
7265 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007266
7267 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007268 Builder.AddTypedTextChunk("warning");
7269 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7270 Builder.AddPlaceholderChunk("message");
7271 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007272
7273 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7274 // completions for them. And __include_macros is a Clang-internal extension
7275 // that we don't want to encourage anyone to use.
7276
7277 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7278 Results.ExitScope();
7279
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007280 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007281 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007282 Results.data(), Results.size());
7283}
7284
7285void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007286 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007287 S->getFnParent()? Sema::PCC_RecoveryInFunction
7288 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007289}
7290
Douglas Gregorec00a262010-08-24 22:20:20 +00007291void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007292 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007293 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007294 IsDefinition? CodeCompletionContext::CCC_MacroName
7295 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007296 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7297 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007298 CodeCompletionBuilder Builder(Results.getAllocator(),
7299 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007300 Results.EnterNewScope();
7301 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7302 MEnd = PP.macro_end();
7303 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007304 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007305 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007306 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7307 CCP_CodePattern,
7308 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007309 }
7310 Results.ExitScope();
7311 } else if (IsDefinition) {
7312 // FIXME: Can we detect when the user just wrote an include guard above?
7313 }
7314
Douglas Gregor0ac41382010-09-23 23:01:17 +00007315 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007316 Results.data(), Results.size());
7317}
7318
Douglas Gregorec00a262010-08-24 22:20:20 +00007319void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007320 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007321 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007322 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007323
7324 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007325 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007326
7327 // defined (<macro>)
7328 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007329 CodeCompletionBuilder Builder(Results.getAllocator(),
7330 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007331 Builder.AddTypedTextChunk("defined");
7332 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7333 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7334 Builder.AddPlaceholderChunk("macro");
7335 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7336 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007337 Results.ExitScope();
7338
7339 HandleCodeCompleteResults(this, CodeCompleter,
7340 CodeCompletionContext::CCC_PreprocessorExpression,
7341 Results.data(), Results.size());
7342}
7343
7344void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7345 IdentifierInfo *Macro,
7346 MacroInfo *MacroInfo,
7347 unsigned Argument) {
7348 // FIXME: In the future, we could provide "overload" results, much like we
7349 // do for function calls.
7350
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007351 // Now just ignore this. There will be another code-completion callback
7352 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007353}
7354
Douglas Gregor11583702010-08-25 17:04:25 +00007355void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007356 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007357 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007358 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007359}
7360
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007361void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007362 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007363 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007364 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7365 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007366 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7367 CodeCompletionDeclConsumer Consumer(Builder,
7368 Context.getTranslationUnitDecl());
7369 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7370 Consumer);
7371 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007372
7373 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007374 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007375
7376 Results.clear();
7377 Results.insert(Results.end(),
7378 Builder.data(), Builder.data() + Builder.size());
7379}