blob: 5aa28cdc6c435ec6086a536b88003b1c9cde9fad [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
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002818/// \brief Add function overload parameter chunks to the given code completion
2819/// string.
2820static void AddOverloadParameterChunks(ASTContext &Context,
2821 const PrintingPolicy &Policy,
2822 const FunctionDecl *Function,
2823 const FunctionProtoType *Prototype,
2824 CodeCompletionBuilder &Result,
2825 unsigned CurrentArg,
2826 unsigned Start = 0,
2827 bool InOptional = false) {
2828 bool FirstParameter = true;
2829 unsigned NumParams = Function ? Function->getNumParams()
2830 : Prototype->getNumParams();
2831
2832 for (unsigned P = Start; P != NumParams; ++P) {
2833 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2834 // When we see an optional default argument, put that argument and
2835 // the remaining default arguments into a new, optional string.
2836 CodeCompletionBuilder Opt(Result.getAllocator(),
2837 Result.getCodeCompletionTUInfo());
2838 if (!FirstParameter)
2839 Opt.AddChunk(CodeCompletionString::CK_Comma);
2840 // Optional sections are nested.
2841 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2842 CurrentArg, P, /*InOptional=*/true);
2843 Result.AddOptionalChunk(Opt.TakeString());
2844 return;
2845 }
2846
2847 if (FirstParameter)
2848 FirstParameter = false;
2849 else
2850 Result.AddChunk(CodeCompletionString::CK_Comma);
2851
2852 InOptional = false;
2853
2854 // Format the placeholder string.
2855 std::string Placeholder;
2856 if (Function)
2857 Placeholder = FormatFunctionParameter(Context, Policy,
2858 Function->getParamDecl(P));
2859 else
2860 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2861
2862 if (P == CurrentArg)
2863 Result.AddCurrentParameterChunk(
2864 Result.getAllocator().CopyString(Placeholder));
2865 else
2866 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2867 }
2868
2869 if (Prototype && Prototype->isVariadic()) {
2870 CodeCompletionBuilder Opt(Result.getAllocator(),
2871 Result.getCodeCompletionTUInfo());
2872 if (!FirstParameter)
2873 Opt.AddChunk(CodeCompletionString::CK_Comma);
2874
2875 if (CurrentArg < NumParams)
2876 Opt.AddPlaceholderChunk("...");
2877 else
2878 Opt.AddCurrentParameterChunk("...");
2879
2880 Result.AddOptionalChunk(Opt.TakeString());
2881 }
2882}
2883
Douglas Gregorf0f51982009-09-23 00:34:09 +00002884CodeCompletionString *
2885CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002886 unsigned CurrentArg, Sema &S,
2887 CodeCompletionAllocator &Allocator,
2888 CodeCompletionTUInfo &CCTUInfo,
2889 bool IncludeBriefComments) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002890 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002891
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002892 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002893 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002894 FunctionDecl *FDecl = getFunction();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002895 const FunctionProtoType *Proto
Douglas Gregorf0f51982009-09-23 00:34:09 +00002896 = dyn_cast<FunctionProtoType>(getFunctionType());
2897 if (!FDecl && !Proto) {
2898 // Function without a prototype. Just give the return type and a
2899 // highlighted ellipsis.
2900 const FunctionType *FT = getFunctionType();
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002901 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
2902 FT->getReturnType().getAsString(Policy)));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002903 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2904 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2905 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002906 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002907 }
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002908
2909 if (FDecl) {
2910 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
2911 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
2912 FDecl->getParamDecl(CurrentArg)))
2913 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
2914 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002915 Result.AddTextChunk(
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002916 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2917 } else {
2918 Result.AddResultTypeChunk(
2919 Result.getAllocator().CopyString(
Alp Toker314cc812014-01-25 16:55:45 +00002920 Proto->getReturnType().getAsString(Policy)));
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002921 }
Alp Toker314cc812014-01-25 16:55:45 +00002922
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002923 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002924 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
2925 CurrentArg);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002926 Result.AddChunk(CodeCompletionString::CK_RightParen);
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00002927
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002928 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002929}
2930
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002931unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002932 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002933 bool PreferredTypeIsPointer) {
2934 unsigned Priority = CCP_Macro;
2935
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002936 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2937 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2938 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002939 Priority = CCP_Constant;
2940 if (PreferredTypeIsPointer)
2941 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002942 }
2943 // Treat "YES", "NO", "true", and "false" as constants.
2944 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2945 MacroName.equals("true") || MacroName.equals("false"))
2946 Priority = CCP_Constant;
2947 // Treat "bool" as a type.
2948 else if (MacroName.equals("bool"))
2949 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2950
Douglas Gregor6e240332010-08-16 16:18:59 +00002951
2952 return Priority;
2953}
2954
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00002955CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002956 if (!D)
2957 return CXCursor_UnexposedDecl;
2958
2959 switch (D->getKind()) {
2960 case Decl::Enum: return CXCursor_EnumDecl;
2961 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2962 case Decl::Field: return CXCursor_FieldDecl;
2963 case Decl::Function:
2964 return CXCursor_FunctionDecl;
2965 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2966 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002967 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002968
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002969 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002970 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2971 case Decl::ObjCMethod:
2972 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2973 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2974 case Decl::CXXMethod: return CXCursor_CXXMethod;
2975 case Decl::CXXConstructor: return CXCursor_Constructor;
2976 case Decl::CXXDestructor: return CXCursor_Destructor;
2977 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2978 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002979 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002980 case Decl::ParmVar: return CXCursor_ParmDecl;
2981 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00002982 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002983 case Decl::Var: return CXCursor_VarDecl;
2984 case Decl::Namespace: return CXCursor_Namespace;
2985 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2986 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2987 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2988 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2989 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2990 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00002991 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002992 case Decl::ClassTemplatePartialSpecialization:
2993 return CXCursor_ClassTemplatePartialSpecialization;
2994 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor3e653b32012-04-30 23:41:16 +00002995 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002996
2997 case Decl::Using:
2998 case Decl::UnresolvedUsingValue:
2999 case Decl::UnresolvedUsingTypename:
3000 return CXCursor_UsingDeclaration;
3001
Douglas Gregor4cd65962011-06-03 23:08:58 +00003002 case Decl::ObjCPropertyImpl:
3003 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3004 case ObjCPropertyImplDecl::Dynamic:
3005 return CXCursor_ObjCDynamicDecl;
3006
3007 case ObjCPropertyImplDecl::Synthesize:
3008 return CXCursor_ObjCSynthesizeDecl;
3009 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00003010
3011 case Decl::Import:
3012 return CXCursor_ModuleImportDecl;
Douglas Gregor4cd65962011-06-03 23:08:58 +00003013
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003014 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00003015 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003016 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00003017 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00003018 case TTK_Struct: return CXCursor_StructDecl;
3019 case TTK_Class: return CXCursor_ClassDecl;
3020 case TTK_Union: return CXCursor_UnionDecl;
3021 case TTK_Enum: return CXCursor_EnumDecl;
3022 }
3023 }
3024 }
3025
3026 return CXCursor_UnexposedDecl;
3027}
3028
Douglas Gregor55b037b2010-07-08 20:55:51 +00003029static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00003030 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00003031 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00003032 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00003033
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003034 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003035
Douglas Gregor9eb77012009-11-07 00:00:49 +00003036 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3037 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003038 M != MEnd; ++M) {
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003039 if (IncludeUndefined || M->first->hasMacroDefinition()) {
3040 if (MacroInfo *MI = M->second->getMacroInfo())
3041 if (MI->isUsedForHeaderGuard())
3042 continue;
3043
Douglas Gregor8cb17462012-10-09 16:01:50 +00003044 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003045 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003046 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003047 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003048 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003049 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003050
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003051 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003052
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003053}
3054
Douglas Gregorce0e8562010-08-23 21:54:33 +00003055static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3056 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003057 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003058
3059 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003060
Douglas Gregorce0e8562010-08-23 21:54:33 +00003061 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3062 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003063 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003064 Results.AddResult(Result("__func__", CCP_Constant));
3065 Results.ExitScope();
3066}
3067
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003068static void HandleCodeCompleteResults(Sema *S,
3069 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003070 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003071 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003072 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003073 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003074 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003075}
3076
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003077static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3078 Sema::ParserCompletionContext PCC) {
3079 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003080 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003081 return CodeCompletionContext::CCC_TopLevel;
3082
John McCallfaf5fb42010-08-26 23:41:50 +00003083 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003084 return CodeCompletionContext::CCC_ClassStructUnion;
3085
John McCallfaf5fb42010-08-26 23:41:50 +00003086 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003087 return CodeCompletionContext::CCC_ObjCInterface;
3088
John McCallfaf5fb42010-08-26 23:41:50 +00003089 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003090 return CodeCompletionContext::CCC_ObjCImplementation;
3091
John McCallfaf5fb42010-08-26 23:41:50 +00003092 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003093 return CodeCompletionContext::CCC_ObjCIvarList;
3094
John McCallfaf5fb42010-08-26 23:41:50 +00003095 case Sema::PCC_Template:
3096 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003097 if (S.CurContext->isFileContext())
3098 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003099 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003100 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003101 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003102
John McCallfaf5fb42010-08-26 23:41:50 +00003103 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003104 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003105
John McCallfaf5fb42010-08-26 23:41:50 +00003106 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003107 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3108 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003109 return CodeCompletionContext::CCC_ParenthesizedExpression;
3110 else
3111 return CodeCompletionContext::CCC_Expression;
3112
3113 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003114 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003115 return CodeCompletionContext::CCC_Expression;
3116
John McCallfaf5fb42010-08-26 23:41:50 +00003117 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003118 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003119
John McCallfaf5fb42010-08-26 23:41:50 +00003120 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003121 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003122
3123 case Sema::PCC_ParenthesizedExpression:
3124 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003125
3126 case Sema::PCC_LocalDeclarationSpecifiers:
3127 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003128 }
David Blaikie8a40f702012-01-17 06:56:22 +00003129
3130 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003131}
3132
Douglas Gregorac322ec2010-08-27 21:18:54 +00003133/// \brief If we're in a C++ virtual member function, add completion results
3134/// that invoke the functions we override, since it's common to invoke the
3135/// overridden function as well as adding new functionality.
3136///
3137/// \param S The semantic analysis object for which we are generating results.
3138///
3139/// \param InContext This context in which the nested-name-specifier preceding
3140/// the code-completion point
3141static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3142 ResultBuilder &Results) {
3143 // Look through blocks.
3144 DeclContext *CurContext = S.CurContext;
3145 while (isa<BlockDecl>(CurContext))
3146 CurContext = CurContext->getParent();
3147
3148
3149 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3150 if (!Method || !Method->isVirtual())
3151 return;
3152
3153 // We need to have names for all of the parameters, if we're going to
3154 // generate a forwarding call.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003155 for (auto P : Method->params())
3156 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003157 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003158
Douglas Gregor75acd922011-09-27 23:30:47 +00003159 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003160 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3161 MEnd = Method->end_overridden_methods();
3162 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003163 CodeCompletionBuilder Builder(Results.getAllocator(),
3164 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003165 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003166 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3167 continue;
3168
3169 // If we need a nested-name-specifier, add one now.
3170 if (!InContext) {
3171 NestedNameSpecifier *NNS
3172 = getRequiredQualification(S.Context, CurContext,
3173 Overridden->getDeclContext());
3174 if (NNS) {
3175 std::string Str;
3176 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003177 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003178 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003179 }
3180 } else if (!InContext->Equals(Overridden->getDeclContext()))
3181 continue;
3182
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003183 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003184 Overridden->getNameAsString()));
3185 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003186 bool FirstParam = true;
Aaron Ballman43b68be2014-03-07 17:50:17 +00003187 for (auto P : Method->params()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003188 if (FirstParam)
3189 FirstParam = false;
3190 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003191 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003192
Aaron Ballman43b68be2014-03-07 17:50:17 +00003193 Builder.AddPlaceholderChunk(
3194 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003195 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003196 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3197 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003198 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003199 CXCursor_CXXMethod,
3200 CXAvailability_Available,
3201 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003202 Results.Ignore(Overridden);
3203 }
3204}
3205
Douglas Gregor07f43572012-01-29 18:15:03 +00003206void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3207 ModuleIdPath Path) {
3208 typedef CodeCompletionResult Result;
3209 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003210 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003211 CodeCompletionContext::CCC_Other);
3212 Results.EnterNewScope();
3213
3214 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003215 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003216 typedef CodeCompletionResult Result;
3217 if (Path.empty()) {
3218 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003219 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003220 PP.getHeaderSearchInfo().collectAllModules(Modules);
3221 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3222 Builder.AddTypedTextChunk(
3223 Builder.getAllocator().CopyString(Modules[I]->Name));
3224 Results.AddResult(Result(Builder.TakeString(),
3225 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003226 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003227 Modules[I]->isAvailable()
3228 ? CXAvailability_Available
3229 : CXAvailability_NotAvailable));
3230 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003231 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003232 // Load the named module.
3233 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3234 Module::AllVisible,
3235 /*IsInclusionDirective=*/false);
3236 // Enumerate submodules.
3237 if (Mod) {
3238 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3239 SubEnd = Mod->submodule_end();
3240 Sub != SubEnd; ++Sub) {
3241
3242 Builder.AddTypedTextChunk(
3243 Builder.getAllocator().CopyString((*Sub)->Name));
3244 Results.AddResult(Result(Builder.TakeString(),
3245 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003246 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003247 (*Sub)->isAvailable()
3248 ? CXAvailability_Available
3249 : CXAvailability_NotAvailable));
3250 }
3251 }
3252 }
3253 Results.ExitScope();
3254 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3255 Results.data(),Results.size());
3256}
3257
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003258void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003259 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003260 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003261 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003262 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003263 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003264
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003265 // Determine how to filter results, e.g., so that the names of
3266 // values (functions, enumerators, function templates, etc.) are
3267 // only allowed where we can have an expression.
3268 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003269 case PCC_Namespace:
3270 case PCC_Class:
3271 case PCC_ObjCInterface:
3272 case PCC_ObjCImplementation:
3273 case PCC_ObjCInstanceVariableList:
3274 case PCC_Template:
3275 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003276 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003277 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003278 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3279 break;
3280
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003281 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003282 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003283 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003284 case PCC_ForInit:
3285 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003286 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003287 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3288 else
3289 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003290
David Blaikiebbafb8a2012-03-11 07:00:24 +00003291 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003292 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003293 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003294
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003295 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003296 // Unfiltered
3297 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003298 }
3299
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003300 // If we are in a C++ non-static member function, check the qualifiers on
3301 // the member function to filter/prioritize the results list.
3302 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3303 if (CurMethod->isInstance())
3304 Results.setObjectTypeQualifiers(
3305 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3306
Douglas Gregorc580c522010-01-14 01:09:38 +00003307 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003308 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3309 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003310
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003311 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003312 Results.ExitScope();
3313
Douglas Gregorce0e8562010-08-23 21:54:33 +00003314 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003315 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003316 case PCC_Expression:
3317 case PCC_Statement:
3318 case PCC_RecoveryInFunction:
3319 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00003320 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003321 break;
3322
3323 case PCC_Namespace:
3324 case PCC_Class:
3325 case PCC_ObjCInterface:
3326 case PCC_ObjCImplementation:
3327 case PCC_ObjCInstanceVariableList:
3328 case PCC_Template:
3329 case PCC_MemberTemplate:
3330 case PCC_ForInit:
3331 case PCC_Condition:
3332 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003333 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003334 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003335 }
3336
Douglas Gregor9eb77012009-11-07 00:00:49 +00003337 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003338 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003339
Douglas Gregor50832e02010-09-20 22:39:41 +00003340 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003341 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003342}
3343
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003344static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3345 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003346 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003347 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003348 bool IsSuper,
3349 ResultBuilder &Results);
3350
3351void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3352 bool AllowNonIdentifiers,
3353 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003354 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003355 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003356 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003357 AllowNestedNameSpecifiers
3358 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3359 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003360 Results.EnterNewScope();
3361
3362 // Type qualifiers can come after names.
3363 Results.AddResult(Result("const"));
3364 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003365 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003366 Results.AddResult(Result("restrict"));
3367
David Blaikiebbafb8a2012-03-11 07:00:24 +00003368 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003369 if (AllowNonIdentifiers) {
3370 Results.AddResult(Result("operator"));
3371 }
3372
3373 // Add nested-name-specifiers.
3374 if (AllowNestedNameSpecifiers) {
3375 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003376 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003377 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3378 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3379 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003380 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003381 }
3382 }
3383 Results.ExitScope();
3384
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003385 // If we're in a context where we might have an expression (rather than a
3386 // declaration), and what we've seen so far is an Objective-C type that could
3387 // be a receiver of a class message, this may be a class message send with
3388 // the initial opening bracket '[' missing. Add appropriate completions.
3389 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003390 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003391 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003392 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3393 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003394 !DS.isTypeAltiVecVector() &&
3395 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003396 (S->getFlags() & Scope::DeclScope) != 0 &&
3397 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3398 Scope::FunctionPrototypeScope |
3399 Scope::AtCatchScope)) == 0) {
3400 ParsedType T = DS.getRepAsType();
3401 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003402 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003403 }
3404
Douglas Gregor56ccce02010-08-24 04:59:56 +00003405 // Note that we intentionally suppress macro results here, since we do not
3406 // encourage using macros to produce the names of entities.
3407
Douglas Gregor0ac41382010-09-23 23:01:17 +00003408 HandleCodeCompleteResults(this, CodeCompleter,
3409 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003410 Results.data(), Results.size());
3411}
3412
Douglas Gregor68762e72010-08-23 21:17:50 +00003413struct Sema::CodeCompleteExpressionData {
3414 CodeCompleteExpressionData(QualType PreferredType = QualType())
3415 : PreferredType(PreferredType), IntegralConstantExpression(false),
3416 ObjCCollection(false) { }
3417
3418 QualType PreferredType;
3419 bool IntegralConstantExpression;
3420 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003421 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003422};
3423
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003424/// \brief Perform code-completion in an expression context when we know what
3425/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003426void Sema::CodeCompleteExpression(Scope *S,
3427 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003428 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003429 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003430 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003431 if (Data.ObjCCollection)
3432 Results.setFilter(&ResultBuilder::IsObjCCollection);
3433 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003434 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003435 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003436 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3437 else
3438 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003439
3440 if (!Data.PreferredType.isNull())
3441 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3442
3443 // Ignore any declarations that we were told that we don't care about.
3444 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3445 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003446
3447 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003448 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3449 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003450
3451 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003452 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003453 Results.ExitScope();
3454
Douglas Gregor55b037b2010-07-08 20:55:51 +00003455 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003456 if (!Data.PreferredType.isNull())
3457 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3458 || Data.PreferredType->isMemberPointerType()
3459 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003460
Douglas Gregorce0e8562010-08-23 21:54:33 +00003461 if (S->getFnParent() &&
3462 !Data.ObjCCollection &&
3463 !Data.IntegralConstantExpression)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003464 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003465
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003466 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003467 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003468 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003469 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3470 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003471 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003472}
3473
Douglas Gregoreda7e542010-09-18 01:28:11 +00003474void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3475 if (E.isInvalid())
3476 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003477 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003478 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003479}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003480
Douglas Gregorb888acf2010-12-09 23:01:55 +00003481/// \brief The set of properties that have already been added, referenced by
3482/// property name.
3483typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3484
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003485/// \brief Retrieve the container definition, if any?
3486static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3487 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3488 if (Interface->hasDefinition())
3489 return Interface->getDefinition();
3490
3491 return Interface;
3492 }
3493
3494 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3495 if (Protocol->hasDefinition())
3496 return Protocol->getDefinition();
3497
3498 return Protocol;
3499 }
3500 return Container;
3501}
3502
3503static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003504 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003505 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003506 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003507 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003508 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003509 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003510
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003511 // Retrieve the definition.
3512 Container = getContainerDef(Container);
3513
Douglas Gregor9291bad2009-11-18 01:29:26 +00003514 // Add properties in this container.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003515 for (const auto *P : Container->properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003516 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003517 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003518 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003519
Douglas Gregor95147142011-05-05 15:50:42 +00003520 // Add nullary methods
3521 if (AllowNullaryMethods) {
3522 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003523 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003524 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003525 if (M->getSelector().isUnarySelector())
3526 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003527 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003528 CodeCompletionBuilder Builder(Results.getAllocator(),
3529 Results.getCodeCompletionTUInfo());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003530 AddResultTypeChunk(Context, Policy, M, Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003531 Builder.AddTypedTextChunk(
3532 Results.getAllocator().CopyString(Name->getName()));
3533
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003534 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003535 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003536 CurContext);
3537 }
3538 }
3539 }
3540
3541
Douglas Gregor9291bad2009-11-18 01:29:26 +00003542 // Add properties in referenced protocols.
3543 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003544 for (auto *P : Protocol->protocols())
3545 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003546 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003547 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003548 if (AllowCategories) {
3549 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003550 for (auto *Cat : IFace->known_categories())
3551 AddObjCProperties(Cat, AllowCategories, AllowNullaryMethods, CurContext,
3552 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003553 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003554
Douglas Gregor9291bad2009-11-18 01:29:26 +00003555 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003556 for (auto *I : IFace->all_referenced_protocols())
3557 AddObjCProperties(I, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003558 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003559
3560 // Look in the superclass.
3561 if (IFace->getSuperClass())
Douglas Gregor95147142011-05-05 15:50:42 +00003562 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3563 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003564 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003565 } else if (const ObjCCategoryDecl *Category
3566 = dyn_cast<ObjCCategoryDecl>(Container)) {
3567 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003568 for (auto *P : Category->protocols())
3569 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003570 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003571 }
3572}
3573
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003574void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003575 SourceLocation OpLoc,
3576 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003577 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003578 return;
3579
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003580 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3581 if (ConvertedBase.isInvalid())
3582 return;
3583 Base = ConvertedBase.get();
3584
John McCall276321a2010-08-25 06:19:51 +00003585 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003586
Douglas Gregor2436e712009-09-17 21:32:03 +00003587 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003588
3589 if (IsArrow) {
3590 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3591 BaseType = Ptr->getPointeeType();
3592 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003593 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003594 else
3595 return;
3596 }
3597
Douglas Gregor21325842011-07-07 16:03:39 +00003598 enum CodeCompletionContext::Kind contextKind;
3599
3600 if (IsArrow) {
3601 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3602 }
3603 else {
3604 if (BaseType->isObjCObjectPointerType() ||
3605 BaseType->isObjCObjectOrInterfaceType()) {
3606 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3607 }
3608 else {
3609 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3610 }
3611 }
3612
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003613 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003614 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00003615 CodeCompletionContext(contextKind,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003616 BaseType),
3617 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003618 Results.EnterNewScope();
3619 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003620 // Indicate that we are performing a member access, and the cv-qualifiers
3621 // for the base object type.
3622 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3623
Douglas Gregor9291bad2009-11-18 01:29:26 +00003624 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003625 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003626 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003627 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3628 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003629
David Blaikiebbafb8a2012-03-11 07:00:24 +00003630 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003631 if (!Results.empty()) {
3632 // The "template" keyword can follow "->" or "." in the grammar.
3633 // However, we only want to suggest the template keyword if something
3634 // is dependent.
3635 bool IsDependent = BaseType->isDependentType();
3636 if (!IsDependent) {
3637 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003638 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003639 IsDependent = Ctx->isDependentContext();
3640 break;
3641 }
3642 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003643
Douglas Gregor9291bad2009-11-18 01:29:26 +00003644 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003645 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003646 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003647 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003648 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3649 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003650 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003651
3652 // Add property results based on our interface.
3653 const ObjCObjectPointerType *ObjCPtr
3654 = BaseType->getAsObjCInterfacePointerType();
3655 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor95147142011-05-05 15:50:42 +00003656 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3657 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003658 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003659
3660 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003661 for (auto *I : ObjCPtr->quals())
3662 AddObjCProperties(I, true, /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003663 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003664 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003665 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003666 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003667 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003668 if (const ObjCObjectPointerType *ObjCPtr
3669 = BaseType->getAs<ObjCObjectPointerType>())
3670 Class = ObjCPtr->getInterfaceDecl();
3671 else
John McCall8b07ec22010-05-15 11:32:37 +00003672 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003673
3674 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003675 if (Class) {
3676 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3677 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003678 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3679 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003680 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003681 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003682
3683 // FIXME: How do we cope with isa?
3684
3685 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003686
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003687 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003688 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003689 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003690 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003691}
3692
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003693void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3694 if (!CodeCompleter)
3695 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003696
3697 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003698 enum CodeCompletionContext::Kind ContextKind
3699 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003700 switch ((DeclSpec::TST)TagSpec) {
3701 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003702 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003703 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003704 break;
3705
3706 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003707 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003708 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003709 break;
3710
3711 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003712 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003713 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003714 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003715 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003716 break;
3717
3718 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003719 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003720 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003721
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003722 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3723 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003724 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003725
3726 // First pass: look for tags.
3727 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003728 LookupVisibleDecls(S, LookupTagName, Consumer,
3729 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003730
Douglas Gregor39982192010-08-15 06:18:01 +00003731 if (CodeCompleter->includeGlobals()) {
3732 // Second pass: look for nested name specifiers.
3733 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3734 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3735 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003736
Douglas Gregor0ac41382010-09-23 23:01:17 +00003737 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003738 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003739}
3740
Douglas Gregor28c78432010-08-27 17:35:51 +00003741void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003742 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003743 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003744 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003745 Results.EnterNewScope();
3746 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3747 Results.AddResult("const");
3748 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3749 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003750 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003751 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3752 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003753 if (getLangOpts().C11 &&
3754 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3755 Results.AddResult("_Atomic");
Douglas Gregor28c78432010-08-27 17:35:51 +00003756 Results.ExitScope();
3757 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003758 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003759 Results.data(), Results.size());
3760}
3761
Douglas Gregord328d572009-09-21 18:10:23 +00003762void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003763 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003764 return;
John McCall5939b162011-08-06 07:30:58 +00003765
John McCallaab3e412010-08-25 08:40:02 +00003766 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003767 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3768 if (!type->isEnumeralType()) {
3769 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003770 Data.IntegralConstantExpression = true;
3771 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003772 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003773 }
Douglas Gregord328d572009-09-21 18:10:23 +00003774
3775 // Code-complete the cases of a switch statement over an enumeration type
3776 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003777 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003778 if (EnumDecl *Def = Enum->getDefinition())
3779 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003780
3781 // Determine which enumerators we have already seen in the switch statement.
3782 // FIXME: Ideally, we would also be able to look *past* the code-completion
3783 // token, in case we are code-completing in the middle of the switch and not
3784 // at the end. However, we aren't able to do so at the moment.
3785 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003786 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003787 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3788 SC = SC->getNextSwitchCase()) {
3789 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3790 if (!Case)
3791 continue;
3792
3793 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3794 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3795 if (EnumConstantDecl *Enumerator
3796 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3797 // We look into the AST of the case statement to determine which
3798 // enumerator was named. Alternatively, we could compute the value of
3799 // the integral constant expression, then compare it against the
3800 // values of each enumerator. However, value-based approach would not
3801 // work as well with C++ templates where enumerators declared within a
3802 // template are type- and value-dependent.
3803 EnumeratorsSeen.insert(Enumerator);
3804
Douglas Gregorf2510672009-09-21 19:57:38 +00003805 // If this is a qualified-id, keep track of the nested-name-specifier
3806 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003807 //
3808 // switch (TagD.getKind()) {
3809 // case TagDecl::TK_enum:
3810 // break;
3811 // case XXX
3812 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003813 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003814 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3815 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003816 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003817 }
3818 }
3819
David Blaikiebbafb8a2012-03-11 07:00:24 +00003820 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003821 // If there are no prior enumerators in C++, check whether we have to
3822 // qualify the names of the enumerators that we suggest, because they
3823 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003824 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003825 }
3826
Douglas Gregord328d572009-09-21 18:10:23 +00003827 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003828 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003829 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003830 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003831 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003832 for (auto *E : Enum->enumerators()) {
3833 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003834 continue;
3835
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003836 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003837 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003838 }
3839 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003840
Douglas Gregor21325842011-07-07 16:03:39 +00003841 //We need to make sure we're setting the right context,
3842 //so only say we include macros if the code completer says we do
3843 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3844 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003845 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003846 kind = CodeCompletionContext::CCC_OtherWithMacros;
3847 }
3848
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003849 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003850 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003851 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003852}
3853
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003854static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003855 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003856 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003857
3858 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003859 if (!Args[I])
3860 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003861
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003862 return false;
3863}
3864
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003865typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3866
3867void mergeCandidatesWithResults(Sema &SemaRef,
3868 SmallVectorImpl<ResultCandidate> &Results,
3869 OverloadCandidateSet &CandidateSet,
3870 SourceLocation Loc) {
3871 if (!CandidateSet.empty()) {
3872 // Sort the overload candidate set by placing the best overloads first.
3873 std::stable_sort(
3874 CandidateSet.begin(), CandidateSet.end(),
3875 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3876 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3877 });
3878
3879 // Add the remaining viable overload candidates as code-completion results.
3880 for (auto &Candidate : CandidateSet)
3881 if (Candidate.Viable)
3882 Results.push_back(ResultCandidate(Candidate.Function));
3883 }
3884}
3885
3886/// \brief Get the type of the Nth parameter from a given set of overload
3887/// candidates.
3888QualType getParamType(Sema &SemaRef, ArrayRef<ResultCandidate> Candidates,
3889 unsigned N) {
3890
3891 // Given the overloads 'Candidates' for a function call matching all arguments
3892 // up to N, return the type of the Nth parameter if it is the same for all
3893 // overload candidates.
3894 QualType ParamType;
3895 for (auto &Candidate : Candidates) {
3896 if (auto FType = Candidate.getFunctionType())
3897 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3898 if (N < Proto->getNumParams()) {
3899 if (ParamType.isNull())
3900 ParamType = Proto->getParamType(N);
3901 else if (!SemaRef.Context.hasSameUnqualifiedType(
3902 ParamType.getNonReferenceType(),
3903 Proto->getParamType(N).getNonReferenceType()))
3904 // Otherwise return a default-constructed QualType.
3905 return QualType();
3906 }
3907 }
3908
3909 return ParamType;
3910}
3911
3912void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3913 MutableArrayRef<ResultCandidate> Candidates,
3914 unsigned CurrentArg,
3915 bool CompleteExpressionWithCurrentArg = true) {
3916 QualType ParamType;
3917 if (CompleteExpressionWithCurrentArg)
3918 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3919
3920 if (ParamType.isNull())
3921 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3922 else
3923 SemaRef.CodeCompleteExpression(S, ParamType);
3924
3925 if (!Candidates.empty())
3926 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3927 Candidates.data(),
3928 Candidates.size());
3929}
3930
3931void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003932 if (!CodeCompleter)
3933 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003934
3935 // When we're code-completing for a call, we fall back to ordinary
3936 // name code-completion whenever we can't produce specific
3937 // results. We may want to revisit this strategy in the future,
3938 // e.g., by merging the two kinds of results.
3939
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003940 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00003941
Douglas Gregorcabea402009-09-22 15:41:20 +00003942 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003943 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3944 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003945 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00003946 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003947 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003948
John McCall57500772009-12-16 12:17:52 +00003949 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00003950 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00003951 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00003952
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003953 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00003954
John McCall57500772009-12-16 12:17:52 +00003955 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003956 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003957 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003958 /*PartialOverloading=*/true);
3959 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3960 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
3961 if (UME->hasExplicitTemplateArgs()) {
3962 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
3963 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00003964 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003965 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
3966 ArgExprs.append(Args.begin(), Args.end());
3967 UnresolvedSet<8> Decls;
3968 Decls.append(UME->decls_begin(), UME->decls_end());
3969 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
3970 /*SuppressUsedConversions=*/false,
3971 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003972 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003973 FunctionDecl *FD = nullptr;
3974 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
3975 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
3976 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
3977 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003978 if (FD) { // We check whether it's a resolved function declaration.
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +00003979 if (!getLangOpts().CPlusPlus ||
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003980 !FD->getType()->getAs<FunctionProtoType>())
3981 Results.push_back(ResultCandidate(FD));
3982 else
3983 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
3984 Args, CandidateSet,
3985 /*SuppressUsedConversions=*/false,
3986 /*PartialOverloading=*/true);
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00003987
3988 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
3989 // If expression's type is CXXRecordDecl, it may overload the function
3990 // call operator, so we check if it does and add them as candidates.
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00003991 // A complete type is needed to lookup for member function call operators.
Francisco Lopes da Silva1a4f8552015-01-25 17:00:47 +00003992 if (!RequireCompleteType(Loc, NakedFn->getType(), 0)) {
Francisco Lopes da Silvaa349a8a2015-01-25 08:47:59 +00003993 DeclarationName OpName = Context.DeclarationNames
3994 .getCXXOperatorName(OO_Call);
3995 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
3996 LookupQualifiedName(R, DC);
3997 R.suppressDiagnostics();
3998 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
3999 ArgExprs.append(Args.begin(), Args.end());
4000 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4001 /*ExplicitArgs=*/nullptr,
4002 /*SuppressUsedConversions=*/false,
4003 /*PartialOverloading=*/true);
4004 }
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004005 } else {
4006 // Lastly we check whether expression's type is function pointer or
4007 // function.
4008 QualType T = NakedFn->getType();
4009 if (!T->getPointeeType().isNull())
4010 T = T->getPointeeType();
4011
4012 if (auto FP = T->getAs<FunctionProtoType>()) {
4013 if (!TooManyArguments(FP->getNumParams(), Args.size(),
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004014 /*PartialOverloading=*/true) ||
4015 FP->isVariadic())
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004016 Results.push_back(ResultCandidate(FP));
4017 } else if (auto FT = T->getAs<FunctionType>())
Francisco Lopes da Silva62a9a4f2015-01-23 13:17:51 +00004018 // No prototype and declaration, it may be a K & R style function.
Francisco Lopes da Silvac6ccc4f2015-01-22 21:14:08 +00004019 Results.push_back(ResultCandidate(FT));
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004020 }
Douglas Gregorcabea402009-09-22 15:41:20 +00004021 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00004022
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004023 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4024 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4025 !CandidateSet.empty());
4026}
4027
4028void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4029 ArrayRef<Expr *> Args) {
4030 if (!CodeCompleter)
4031 return;
4032
4033 // A complete type is needed to lookup for constructors.
4034 if (RequireCompleteType(Loc, Type, 0))
4035 return;
4036
4037 // FIXME: Provide support for member initializers.
4038 // FIXME: Provide support for variadic template constructors.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00004039
4040 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4041
4042 for (auto C : LookupConstructors(Type->getAsCXXRecordDecl())) {
4043 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4044 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4045 Args, CandidateSet,
4046 /*SuppressUsedConversions=*/false,
4047 /*PartialOverloading=*/true);
4048 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4049 AddTemplateOverloadCandidate(FTD,
4050 DeclAccessPair::make(FTD, C->getAccess()),
4051 /*ExplicitTemplateArgs=*/nullptr,
4052 Args, CandidateSet,
4053 /*SuppressUsedConversions=*/false,
4054 /*PartialOverloading=*/true);
4055 }
4056 }
4057
4058 SmallVector<ResultCandidate, 8> Results;
4059 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4060 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004061}
4062
John McCall48871652010-08-21 09:40:31 +00004063void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4064 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004065 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004066 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004067 return;
4068 }
4069
4070 CodeCompleteExpression(S, VD->getType());
4071}
4072
4073void Sema::CodeCompleteReturn(Scope *S) {
4074 QualType ResultType;
4075 if (isa<BlockDecl>(CurContext)) {
4076 if (BlockScopeInfo *BSI = getCurBlock())
4077 ResultType = BSI->ReturnType;
4078 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004079 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004080 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004081 ResultType = Method->getReturnType();
4082
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004083 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004084 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004085 else
4086 CodeCompleteExpression(S, ResultType);
4087}
4088
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004089void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004090 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004091 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004092 mapCodeCompletionContext(*this, PCC_Statement));
4093 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4094 Results.EnterNewScope();
4095
4096 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4097 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4098 CodeCompleter->includeGlobals());
4099
4100 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4101
4102 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004103 CodeCompletionBuilder Builder(Results.getAllocator(),
4104 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004105 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004106 if (Results.includeCodePatterns()) {
4107 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4108 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4109 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4110 Builder.AddPlaceholderChunk("statements");
4111 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4112 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4113 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004114 Results.AddResult(Builder.TakeString());
4115
4116 // "else if" block
4117 Builder.AddTypedTextChunk("else");
4118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4119 Builder.AddTextChunk("if");
4120 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4121 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004122 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004123 Builder.AddPlaceholderChunk("condition");
4124 else
4125 Builder.AddPlaceholderChunk("expression");
4126 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004127 if (Results.includeCodePatterns()) {
4128 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4129 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4130 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4131 Builder.AddPlaceholderChunk("statements");
4132 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4133 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4134 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004135 Results.AddResult(Builder.TakeString());
4136
4137 Results.ExitScope();
4138
4139 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004140 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004141
4142 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004143 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004144
4145 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4146 Results.data(),Results.size());
4147}
4148
Richard Trieu2bd04012011-09-09 02:00:50 +00004149void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004150 if (LHS)
4151 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4152 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004153 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004154}
4155
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004156void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004157 bool EnteringContext) {
4158 if (!SS.getScopeRep() || !CodeCompleter)
4159 return;
4160
Douglas Gregor3545ff42009-09-21 16:56:56 +00004161 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4162 if (!Ctx)
4163 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004164
4165 // Try to instantiate any non-dependent declaration contexts before
4166 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004167 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004168 return;
4169
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004170 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004171 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004172 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004173 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004174
Douglas Gregor3545ff42009-09-21 16:56:56 +00004175 // The "template" keyword can follow "::" in the grammar, but only
4176 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004177 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004178 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004179 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004180
4181 // Add calls to overridden virtual functions, if there are any.
4182 //
4183 // FIXME: This isn't wonderful, because we don't know whether we're actually
4184 // in a context that permits expressions. This is a general issue with
4185 // qualified-id completions.
4186 if (!EnteringContext)
4187 MaybeAddOverrideCalls(*this, Ctx, Results);
4188 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004189
Douglas Gregorac322ec2010-08-27 21:18:54 +00004190 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4191 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4192
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004193 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004194 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004195 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004196}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004197
4198void Sema::CodeCompleteUsing(Scope *S) {
4199 if (!CodeCompleter)
4200 return;
4201
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004202 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004203 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004204 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4205 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004206 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004207
4208 // If we aren't in class scope, we could see the "namespace" keyword.
4209 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004210 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004211
4212 // After "using", we can see anything that would start a
4213 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004214 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004215 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4216 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004217 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004218
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004219 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004220 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004221 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004222}
4223
4224void Sema::CodeCompleteUsingDirective(Scope *S) {
4225 if (!CodeCompleter)
4226 return;
4227
Douglas Gregor3545ff42009-09-21 16:56:56 +00004228 // After "using namespace", we expect to see a namespace name or namespace
4229 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004230 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004231 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004232 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004233 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004234 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004235 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004236 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4237 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004238 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004239 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004240 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004241 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004242}
4243
4244void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4245 if (!CodeCompleter)
4246 return;
4247
Ted Kremenekc37877d2013-10-08 17:08:03 +00004248 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004249 if (!S->getParent())
4250 Ctx = Context.getTranslationUnitDecl();
4251
Douglas Gregor0ac41382010-09-23 23:01:17 +00004252 bool SuppressedGlobalResults
4253 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4254
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004255 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004256 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004257 SuppressedGlobalResults
4258 ? CodeCompletionContext::CCC_Namespace
4259 : CodeCompletionContext::CCC_Other,
4260 &ResultBuilder::IsNamespace);
4261
4262 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004263 // We only want to see those namespaces that have already been defined
4264 // within this scope, because its likely that the user is creating an
4265 // extended namespace declaration. Keep track of the most recent
4266 // definition of each namespace.
4267 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4268 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4269 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4270 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004271 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004272
4273 // Add the most recent definition (or extended definition) of each
4274 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004275 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004276 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004277 NS = OrigToLatest.begin(),
4278 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004279 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004280 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004281 NS->second, Results.getBasePriority(NS->second),
4282 nullptr),
4283 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004284 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004285 }
4286
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004287 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004288 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004289 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004290}
4291
4292void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4293 if (!CodeCompleter)
4294 return;
4295
Douglas Gregor3545ff42009-09-21 16:56:56 +00004296 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004297 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004298 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004299 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004300 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004301 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004302 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4303 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004304 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004305 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004306 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004307}
4308
Douglas Gregorc811ede2009-09-18 20:05:18 +00004309void Sema::CodeCompleteOperatorName(Scope *S) {
4310 if (!CodeCompleter)
4311 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004312
John McCall276321a2010-08-25 06:19:51 +00004313 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004314 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004315 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004316 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004317 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004318 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004319
Douglas Gregor3545ff42009-09-21 16:56:56 +00004320 // Add the names of overloadable operators.
4321#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4322 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004323 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004324#include "clang/Basic/OperatorKinds.def"
4325
4326 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004327 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004328 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004329 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4330 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004331
4332 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004333 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004334 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004335
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004336 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004337 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004338 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004339}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004340
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004341void Sema::CodeCompleteConstructorInitializer(
4342 Decl *ConstructorD,
4343 ArrayRef <CXXCtorInitializer *> Initializers) {
Douglas Gregor75acd922011-09-27 23:30:47 +00004344 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004345 CXXConstructorDecl *Constructor
4346 = static_cast<CXXConstructorDecl *>(ConstructorD);
4347 if (!Constructor)
4348 return;
4349
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004350 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004351 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004352 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004353 Results.EnterNewScope();
4354
4355 // Fill in any already-initialized fields or base classes.
4356 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4357 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004358 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004359 if (Initializers[I]->isBaseInitializer())
4360 InitializedBases.insert(
4361 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4362 else
Francois Pichetd583da02010-12-04 09:14:42 +00004363 InitializedFields.insert(cast<FieldDecl>(
4364 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004365 }
4366
4367 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004368 CodeCompletionBuilder Builder(Results.getAllocator(),
4369 Results.getCodeCompletionTUInfo());
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004370 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004371 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004372 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004373 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4374 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004375 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004376 = !Initializers.empty() &&
4377 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004378 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004379 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004380 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004381 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004382
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004383 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004384 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004385 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004386 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4387 Builder.AddPlaceholderChunk("args");
4388 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4389 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004390 SawLastInitializer? CCP_NextInitializer
4391 : CCP_MemberDeclaration));
4392 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004393 }
4394
4395 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004396 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004397 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4398 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004399 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004400 = !Initializers.empty() &&
4401 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004402 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004403 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004404 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004405 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004406
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004407 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004408 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004409 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004410 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4411 Builder.AddPlaceholderChunk("args");
4412 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4413 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004414 SawLastInitializer? CCP_NextInitializer
4415 : CCP_MemberDeclaration));
4416 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004417 }
4418
4419 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004420 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004421 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4422 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004423 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004424 = !Initializers.empty() &&
4425 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004426 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004427 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004428 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004429
4430 if (!Field->getDeclName())
4431 continue;
4432
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004433 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004434 Field->getIdentifier()->getName()));
4435 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4436 Builder.AddPlaceholderChunk("args");
4437 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4438 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004439 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004440 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004441 CXCursor_MemberRef,
4442 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004443 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004444 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004445 }
4446 Results.ExitScope();
4447
Douglas Gregor0ac41382010-09-23 23:01:17 +00004448 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004449 Results.data(), Results.size());
4450}
4451
Douglas Gregord8c61782012-02-15 15:34:24 +00004452/// \brief Determine whether this scope denotes a namespace.
4453static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004454 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004455 if (!DC)
4456 return false;
4457
4458 return DC->isFileContext();
4459}
4460
4461void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4462 bool AfterAmpersand) {
4463 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004464 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004465 CodeCompletionContext::CCC_Other);
4466 Results.EnterNewScope();
4467
4468 // Note what has already been captured.
4469 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4470 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004471 for (const auto &C : Intro.Captures) {
4472 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004473 IncludedThis = true;
4474 continue;
4475 }
4476
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004477 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004478 }
4479
4480 // Look for other capturable variables.
4481 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004482 for (const auto *D : S->decls()) {
4483 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004484 if (!Var ||
4485 !Var->hasLocalStorage() ||
4486 Var->hasAttr<BlocksAttr>())
4487 continue;
4488
David Blaikie82e95a32014-11-19 07:49:47 +00004489 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004490 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004491 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004492 }
4493 }
4494
4495 // Add 'this', if it would be valid.
4496 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4497 addThisCompletion(*this, Results);
4498
4499 Results.ExitScope();
4500
4501 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4502 Results.data(), Results.size());
4503}
4504
James Dennett596e4752012-06-14 03:11:41 +00004505/// Macro that optionally prepends an "@" to the string literal passed in via
4506/// Keyword, depending on whether NeedAt is true or false.
4507#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4508
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004509static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004510 ResultBuilder &Results,
4511 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004512 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004513 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004514 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004515
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004516 CodeCompletionBuilder Builder(Results.getAllocator(),
4517 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004518 if (LangOpts.ObjC2) {
4519 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004520 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004521 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4522 Builder.AddPlaceholderChunk("property");
4523 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004524
4525 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004526 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004527 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4528 Builder.AddPlaceholderChunk("property");
4529 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004530 }
4531}
4532
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004533static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004534 ResultBuilder &Results,
4535 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004536 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004537
4538 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004539 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004540
4541 if (LangOpts.ObjC2) {
4542 // @property
James Dennett596e4752012-06-14 03:11:41 +00004543 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004544
4545 // @required
James Dennett596e4752012-06-14 03:11:41 +00004546 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004547
4548 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004549 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004550 }
4551}
4552
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004553static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004554 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004555 CodeCompletionBuilder Builder(Results.getAllocator(),
4556 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004557
4558 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004559 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004560 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4561 Builder.AddPlaceholderChunk("name");
4562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004563
Douglas Gregorf4c33342010-05-28 00:22:41 +00004564 if (Results.includeCodePatterns()) {
4565 // @interface name
4566 // FIXME: Could introduce the whole pattern, including superclasses and
4567 // such.
James Dennett596e4752012-06-14 03:11:41 +00004568 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004569 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4570 Builder.AddPlaceholderChunk("class");
4571 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004572
Douglas Gregorf4c33342010-05-28 00:22:41 +00004573 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004574 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004575 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4576 Builder.AddPlaceholderChunk("protocol");
4577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004578
4579 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004580 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004581 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4582 Builder.AddPlaceholderChunk("class");
4583 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004584 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004585
4586 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004587 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004588 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4589 Builder.AddPlaceholderChunk("alias");
4590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4591 Builder.AddPlaceholderChunk("class");
4592 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004593
4594 if (Results.getSema().getLangOpts().Modules) {
4595 // @import name
4596 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4598 Builder.AddPlaceholderChunk("module");
4599 Results.AddResult(Result(Builder.TakeString()));
4600 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004601}
4602
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004603void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004604 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004605 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004606 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004607 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004608 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004609 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004610 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004611 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004612 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004613 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004614 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004615 HandleCodeCompleteResults(this, CodeCompleter,
4616 CodeCompletionContext::CCC_Other,
4617 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004618}
4619
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004620static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004621 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004622 CodeCompletionBuilder Builder(Results.getAllocator(),
4623 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004624
4625 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004626 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004627 if (Results.getSema().getLangOpts().CPlusPlus ||
4628 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004629 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004630 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004631 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004632 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4633 Builder.AddPlaceholderChunk("type-name");
4634 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4635 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004636
4637 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004638 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004639 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004640 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4641 Builder.AddPlaceholderChunk("protocol-name");
4642 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4643 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004644
4645 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004646 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004647 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004648 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4649 Builder.AddPlaceholderChunk("selector");
4650 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4651 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004652
4653 // @"string"
4654 Builder.AddResultTypeChunk("NSString *");
4655 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4656 Builder.AddPlaceholderChunk("string");
4657 Builder.AddTextChunk("\"");
4658 Results.AddResult(Result(Builder.TakeString()));
4659
Douglas Gregor951de302012-07-17 23:24:47 +00004660 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004661 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004662 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004663 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004664 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4665 Results.AddResult(Result(Builder.TakeString()));
4666
Douglas Gregor951de302012-07-17 23:24:47 +00004667 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004668 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004669 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004670 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004671 Builder.AddChunk(CodeCompletionString::CK_Colon);
4672 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4673 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004674 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4675 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004676
Douglas Gregor951de302012-07-17 23:24:47 +00004677 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004678 Builder.AddResultTypeChunk("id");
4679 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004680 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004681 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4682 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004683}
4684
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004685static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004686 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004687 CodeCompletionBuilder Builder(Results.getAllocator(),
4688 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004689
Douglas Gregorf4c33342010-05-28 00:22:41 +00004690 if (Results.includeCodePatterns()) {
4691 // @try { statements } @catch ( declaration ) { statements } @finally
4692 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004693 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004694 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4695 Builder.AddPlaceholderChunk("statements");
4696 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4697 Builder.AddTextChunk("@catch");
4698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4699 Builder.AddPlaceholderChunk("parameter");
4700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4701 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4702 Builder.AddPlaceholderChunk("statements");
4703 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4704 Builder.AddTextChunk("@finally");
4705 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4706 Builder.AddPlaceholderChunk("statements");
4707 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4708 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004709 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004710
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004711 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004712 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4714 Builder.AddPlaceholderChunk("expression");
4715 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004716
Douglas Gregorf4c33342010-05-28 00:22:41 +00004717 if (Results.includeCodePatterns()) {
4718 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004719 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004720 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4721 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4722 Builder.AddPlaceholderChunk("expression");
4723 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4724 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4725 Builder.AddPlaceholderChunk("statements");
4726 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4727 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004728 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004729}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004730
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004731static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004732 ResultBuilder &Results,
4733 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004734 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004735 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4736 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4737 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004738 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004739 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004740}
4741
4742void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004743 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004744 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004745 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004746 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004747 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004748 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004749 HandleCodeCompleteResults(this, CodeCompleter,
4750 CodeCompletionContext::CCC_Other,
4751 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004752}
4753
4754void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004755 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004756 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004757 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004758 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004759 AddObjCStatementResults(Results, false);
4760 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004761 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004762 HandleCodeCompleteResults(this, CodeCompleter,
4763 CodeCompletionContext::CCC_Other,
4764 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004765}
4766
4767void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004768 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004769 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004770 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004771 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004772 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004773 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004774 HandleCodeCompleteResults(this, CodeCompleter,
4775 CodeCompletionContext::CCC_Other,
4776 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004777}
4778
Douglas Gregore6078da2009-11-19 00:14:45 +00004779/// \brief Determine whether the addition of the given flag to an Objective-C
4780/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004781static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004782 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004783 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004784 return true;
4785
Bill Wendling44426052012-12-20 19:22:21 +00004786 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004787
4788 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004789 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4790 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004791 return true;
4792
Jordan Rose53cb2f32012-08-20 20:01:13 +00004793 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004794 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004795 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004796 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004797 ObjCDeclSpec::DQ_PR_retain |
4798 ObjCDeclSpec::DQ_PR_strong |
4799 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004800 if (AssignCopyRetMask &&
4801 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004802 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004803 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004804 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004805 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4806 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004807 return true;
4808
4809 return false;
4810}
4811
Douglas Gregor36029f42009-11-18 23:08:07 +00004812void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004813 if (!CodeCompleter)
4814 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004815
Bill Wendling44426052012-12-20 19:22:21 +00004816 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004817
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004818 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004819 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004820 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004821 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004822 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004823 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004824 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004825 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004826 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004827 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4828 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004829 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004830 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004831 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004832 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004833 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004834 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004835 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004836 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004837 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004838 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004839 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004840 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004841
4842 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall3deb1ad2012-08-21 02:47:43 +00004843 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004844 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004845 Results.AddResult(CodeCompletionResult("weak"));
4846
Bill Wendling44426052012-12-20 19:22:21 +00004847 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004848 CodeCompletionBuilder Setter(Results.getAllocator(),
4849 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004850 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004851 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004852 Setter.AddPlaceholderChunk("method");
4853 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004854 }
Bill Wendling44426052012-12-20 19:22:21 +00004855 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004856 CodeCompletionBuilder Getter(Results.getAllocator(),
4857 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004858 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004859 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004860 Getter.AddPlaceholderChunk("method");
4861 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004862 }
Steve Naroff936354c2009-10-08 21:55:05 +00004863 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004864 HandleCodeCompleteResults(this, CodeCompleter,
4865 CodeCompletionContext::CCC_Other,
4866 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004867}
Steve Naroffeae65032009-11-07 02:08:14 +00004868
James Dennettf1243872012-06-17 05:33:25 +00004869/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004870/// via code completion.
4871enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004872 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4873 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4874 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004875};
4876
Douglas Gregor67c692c2010-08-26 15:07:07 +00004877static bool isAcceptableObjCSelector(Selector Sel,
4878 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004879 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004880 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004881 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004882 if (NumSelIdents > Sel.getNumArgs())
4883 return false;
4884
4885 switch (WantKind) {
4886 case MK_Any: break;
4887 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4888 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4889 }
4890
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004891 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4892 return false;
4893
Douglas Gregor67c692c2010-08-26 15:07:07 +00004894 for (unsigned I = 0; I != NumSelIdents; ++I)
4895 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4896 return false;
4897
4898 return true;
4899}
4900
Douglas Gregorc8537c52009-11-19 07:41:15 +00004901static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4902 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004903 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004904 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004905 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004906 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004907}
Douglas Gregor1154e272010-09-16 16:06:31 +00004908
4909namespace {
4910 /// \brief A set of selectors, which is used to avoid introducing multiple
4911 /// completions with the same selector into the result set.
4912 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4913}
4914
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004915/// \brief Add all of the Objective-C methods in the given Objective-C
4916/// container to the set of results.
4917///
4918/// The container will be a class, protocol, category, or implementation of
4919/// any of the above. This mether will recurse to include methods from
4920/// the superclasses of classes along with their categories, protocols, and
4921/// implementations.
4922///
4923/// \param Container the container in which we'll look to find methods.
4924///
James Dennett596e4752012-06-14 03:11:41 +00004925/// \param WantInstanceMethods Whether to add instance methods (only); if
4926/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004927///
4928/// \param CurContext the context in which we're performing the lookup that
4929/// finds methods.
4930///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004931/// \param AllowSameLength Whether we allow a method to be added to the list
4932/// when it has the same number of parameters as we have selector identifiers.
4933///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004934/// \param Results the structure into which we'll add results.
4935static void AddObjCMethods(ObjCContainerDecl *Container,
4936 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00004937 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004938 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004939 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00004940 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004941 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00004942 ResultBuilder &Results,
4943 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00004944 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004945 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00004946 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4947 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004948 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00004949 // The instance methods on the root class can be messaged via the
4950 // metaclass.
4951 if (M->isInstanceMethod() == WantInstanceMethods ||
4952 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00004953 // Check whether the selector identifiers we've been given are a
4954 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004955 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00004956 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004957
David Blaikie82e95a32014-11-19 07:49:47 +00004958 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00004959 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00004960
4961 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004962 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00004963 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00004964 if (!InOriginalClass)
4965 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004966 Results.MaybeAddResult(R, CurContext);
4967 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004968 }
4969
Douglas Gregorf37c9492010-09-16 15:34:59 +00004970 // Visit the protocols of protocols.
4971 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004972 if (Protocol->hasDefinition()) {
4973 const ObjCList<ObjCProtocolDecl> &Protocols
4974 = Protocol->getReferencedProtocols();
4975 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4976 E = Protocols.end();
4977 I != E; ++I)
4978 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004979 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00004980 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00004981 }
4982
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004983 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004984 return;
4985
4986 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00004987 for (auto *I : IFace->protocols())
4988 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004989 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004990
4991 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00004992 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004993 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004994 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004995 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004996
4997 // Add a categories protocol methods.
4998 const ObjCList<ObjCProtocolDecl> &Protocols
4999 = CatDecl->getReferencedProtocols();
5000 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5001 E = Protocols.end();
5002 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00005003 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005004 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005005 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005006
5007 // Add methods in category implementations.
5008 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005009 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005010 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005011 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005012 }
5013
5014 // Add methods in superclass.
5015 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005016 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005017 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005018 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005019
5020 // Add methods in our implementation, if any.
5021 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00005022 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005023 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005024 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005025}
5026
5027
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005028void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005029 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005030 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005031 if (!Class) {
5032 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005033 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005034 Class = Category->getClassInterface();
5035
5036 if (!Class)
5037 return;
5038 }
5039
5040 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005041 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005042 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005043 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005044 Results.EnterNewScope();
5045
Douglas Gregor1154e272010-09-16 16:06:31 +00005046 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005047 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005048 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005049 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005050 HandleCodeCompleteResults(this, CodeCompleter,
5051 CodeCompletionContext::CCC_Other,
5052 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00005053}
5054
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005055void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00005056 // Try to find the interface where setters might live.
5057 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005058 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005059 if (!Class) {
5060 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005061 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005062 Class = Category->getClassInterface();
5063
5064 if (!Class)
5065 return;
5066 }
5067
5068 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005069 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005070 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005071 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005072 Results.EnterNewScope();
5073
Douglas Gregor1154e272010-09-16 16:06:31 +00005074 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005075 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005076 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005077
5078 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005079 HandleCodeCompleteResults(this, CodeCompleter,
5080 CodeCompletionContext::CCC_Other,
5081 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005082}
5083
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005084void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5085 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005086 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005087 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005088 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005089 Results.EnterNewScope();
5090
5091 // Add context-sensitive, Objective-C parameter-passing keywords.
5092 bool AddedInOut = false;
5093 if ((DS.getObjCDeclQualifier() &
5094 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5095 Results.AddResult("in");
5096 Results.AddResult("inout");
5097 AddedInOut = true;
5098 }
5099 if ((DS.getObjCDeclQualifier() &
5100 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5101 Results.AddResult("out");
5102 if (!AddedInOut)
5103 Results.AddResult("inout");
5104 }
5105 if ((DS.getObjCDeclQualifier() &
5106 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5107 ObjCDeclSpec::DQ_Oneway)) == 0) {
5108 Results.AddResult("bycopy");
5109 Results.AddResult("byref");
5110 Results.AddResult("oneway");
5111 }
5112
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005113 // If we're completing the return type of an Objective-C method and the
5114 // identifier IBAction refers to a macro, provide a completion item for
5115 // an action, e.g.,
5116 // IBAction)<#selector#>:(id)sender
5117 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5118 Context.Idents.get("IBAction").hasMacroDefinition()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005119 CodeCompletionBuilder Builder(Results.getAllocator(),
5120 Results.getCodeCompletionTUInfo(),
5121 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005122 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005123 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005124 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005125 Builder.AddChunk(CodeCompletionString::CK_Colon);
5126 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005127 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005128 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005129 Builder.AddTextChunk("sender");
5130 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5131 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005132
5133 // If we're completing the return type, provide 'instancetype'.
5134 if (!IsParameter) {
5135 Results.AddResult(CodeCompletionResult("instancetype"));
5136 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005137
Douglas Gregor99fa2642010-08-24 01:06:58 +00005138 // Add various builtin type names and specifiers.
5139 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5140 Results.ExitScope();
5141
5142 // Add the various type names
5143 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5144 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5145 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5146 CodeCompleter->includeGlobals());
5147
5148 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005149 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005150
5151 HandleCodeCompleteResults(this, CodeCompleter,
5152 CodeCompletionContext::CCC_Type,
5153 Results.data(), Results.size());
5154}
5155
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005156/// \brief When we have an expression with type "id", we may assume
5157/// that it has some more-specific class type based on knowledge of
5158/// common uses of Objective-C. This routine returns that class type,
5159/// or NULL if no better result could be determined.
5160static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005161 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005162 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005163 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005164
5165 Selector Sel = Msg->getSelector();
5166 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005167 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005168
5169 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5170 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005171 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005172
5173 ObjCMethodDecl *Method = Msg->getMethodDecl();
5174 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005175 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005176
5177 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005178 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005179 switch (Msg->getReceiverKind()) {
5180 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005181 if (const ObjCObjectType *ObjType
5182 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5183 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005184 break;
5185
5186 case ObjCMessageExpr::Instance: {
5187 QualType T = Msg->getInstanceReceiver()->getType();
5188 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5189 IFace = Ptr->getInterfaceDecl();
5190 break;
5191 }
5192
5193 case ObjCMessageExpr::SuperInstance:
5194 case ObjCMessageExpr::SuperClass:
5195 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005196 }
5197
5198 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005199 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005200
5201 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5202 if (Method->isInstanceMethod())
5203 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5204 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005205 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005206 .Case("autorelease", IFace)
5207 .Case("copy", IFace)
5208 .Case("copyWithZone", IFace)
5209 .Case("mutableCopy", IFace)
5210 .Case("mutableCopyWithZone", IFace)
5211 .Case("awakeFromCoder", IFace)
5212 .Case("replacementObjectFromCoder", IFace)
5213 .Case("class", IFace)
5214 .Case("classForCoder", IFace)
5215 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005216 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005217
5218 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5219 .Case("new", IFace)
5220 .Case("alloc", IFace)
5221 .Case("allocWithZone", IFace)
5222 .Case("class", IFace)
5223 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005224 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005225}
5226
Douglas Gregor6fc04132010-08-27 15:10:57 +00005227// Add a special completion for a message send to "super", which fills in the
5228// most likely case of forwarding all of our arguments to the superclass
5229// function.
5230///
5231/// \param S The semantic analysis object.
5232///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005233/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005234/// the "super" keyword. Otherwise, we just need to provide the arguments.
5235///
5236/// \param SelIdents The identifiers in the selector that have already been
5237/// provided as arguments for a send to "super".
5238///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005239/// \param Results The set of results to augment.
5240///
5241/// \returns the Objective-C method declaration that would be invoked by
5242/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005243static ObjCMethodDecl *AddSuperSendCompletion(
5244 Sema &S, bool NeedSuperKeyword,
5245 ArrayRef<IdentifierInfo *> SelIdents,
5246 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005247 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5248 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005249 return nullptr;
5250
Douglas Gregor6fc04132010-08-27 15:10:57 +00005251 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5252 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005253 return nullptr;
5254
Douglas Gregor6fc04132010-08-27 15:10:57 +00005255 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005256 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005257 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5258 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005259 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5260 CurMethod->isInstanceMethod());
5261
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005262 // Check in categories or class extensions.
5263 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005264 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005265 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005266 CurMethod->isInstanceMethod())))
5267 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005268 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005269 }
5270 }
5271
Douglas Gregor6fc04132010-08-27 15:10:57 +00005272 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005273 return nullptr;
5274
Douglas Gregor6fc04132010-08-27 15:10:57 +00005275 // Check whether the superclass method has the same signature.
5276 if (CurMethod->param_size() != SuperMethod->param_size() ||
5277 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005278 return nullptr;
5279
Douglas Gregor6fc04132010-08-27 15:10:57 +00005280 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5281 CurPEnd = CurMethod->param_end(),
5282 SuperP = SuperMethod->param_begin();
5283 CurP != CurPEnd; ++CurP, ++SuperP) {
5284 // Make sure the parameter types are compatible.
5285 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5286 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005287 return nullptr;
5288
Douglas Gregor6fc04132010-08-27 15:10:57 +00005289 // Make sure we have a parameter name to forward!
5290 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005291 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005292 }
5293
5294 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005295 CodeCompletionBuilder Builder(Results.getAllocator(),
5296 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005297
5298 // Give this completion a return type.
Douglas Gregor75acd922011-09-27 23:30:47 +00005299 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5300 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005301
5302 // If we need the "super" keyword, add it (plus some spacing).
5303 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005304 Builder.AddTypedTextChunk("super");
5305 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005306 }
5307
5308 Selector Sel = CurMethod->getSelector();
5309 if (Sel.isUnarySelector()) {
5310 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005311 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005312 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005313 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005314 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005315 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005316 } else {
5317 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5318 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005319 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005321
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005322 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005323 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005324 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005325 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005326 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005327 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005328 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005329 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005330 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005331 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005332 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005333 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005334 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005335 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005336 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005337 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005338 }
5339 }
5340 }
5341
Douglas Gregor78254c82012-03-27 23:34:16 +00005342 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5343 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005344 return SuperMethod;
5345}
5346
Douglas Gregora817a192010-05-27 23:06:34 +00005347void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005348 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005349 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005350 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005351 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005352 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005353 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5354 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005355
Douglas Gregora817a192010-05-27 23:06:34 +00005356 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5357 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005358 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5359 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005360
5361 // If we are in an Objective-C method inside a class that has a superclass,
5362 // add "super" as an option.
5363 if (ObjCMethodDecl *Method = getCurMethodDecl())
5364 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005365 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005366 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005367
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005368 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005369 }
Douglas Gregora817a192010-05-27 23:06:34 +00005370
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005371 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005372 addThisCompletion(*this, Results);
5373
Douglas Gregora817a192010-05-27 23:06:34 +00005374 Results.ExitScope();
5375
5376 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005377 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005378 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005379 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005380
5381}
5382
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005383void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005384 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005385 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005386 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005387 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5388 // Figure out which interface we're in.
5389 CDecl = CurMethod->getClassInterface();
5390 if (!CDecl)
5391 return;
5392
5393 // Find the superclass of this class.
5394 CDecl = CDecl->getSuperClass();
5395 if (!CDecl)
5396 return;
5397
5398 if (CurMethod->isInstanceMethod()) {
5399 // We are inside an instance method, which means that the message
5400 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005401 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005402 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005403 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005404 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005405 }
5406
5407 // Fall through to send to the superclass in CDecl.
5408 } else {
5409 // "super" may be the name of a type or variable. Figure out which
5410 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005411 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005412 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5413 LookupOrdinaryName);
5414 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5415 // "super" names an interface. Use it.
5416 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005417 if (const ObjCObjectType *Iface
5418 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5419 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005420 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5421 // "super" names an unresolved type; we can't be more specific.
5422 } else {
5423 // Assume that "super" names some kind of value and parse that way.
5424 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005425 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005426 UnqualifiedId id;
5427 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005428 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5429 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005430 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005431 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005432 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005433 }
5434
5435 // Fall through
5436 }
5437
John McCallba7bf592010-08-24 05:47:05 +00005438 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005439 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005440 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005441 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005442 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005443 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005444}
5445
Douglas Gregor74661272010-09-21 00:03:25 +00005446/// \brief Given a set of code-completion results for the argument of a message
5447/// send, determine the preferred type (if any) for that argument expression.
5448static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5449 unsigned NumSelIdents) {
5450 typedef CodeCompletionResult Result;
5451 ASTContext &Context = Results.getSema().Context;
5452
5453 QualType PreferredType;
5454 unsigned BestPriority = CCP_Unlikely * 2;
5455 Result *ResultsData = Results.data();
5456 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5457 Result &R = ResultsData[I];
5458 if (R.Kind == Result::RK_Declaration &&
5459 isa<ObjCMethodDecl>(R.Declaration)) {
5460 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005461 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005462 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005463 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005464 ->getType();
5465 if (R.Priority < BestPriority || PreferredType.isNull()) {
5466 BestPriority = R.Priority;
5467 PreferredType = MyPreferredType;
5468 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5469 MyPreferredType)) {
5470 PreferredType = QualType();
5471 }
5472 }
5473 }
5474 }
5475 }
5476
5477 return PreferredType;
5478}
5479
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005480static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5481 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005482 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005483 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005484 bool IsSuper,
5485 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005486 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005487 ObjCInterfaceDecl *CDecl = nullptr;
5488
Douglas Gregor8ce33212009-11-17 17:59:40 +00005489 // If the given name refers to an interface type, retrieve the
5490 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005491 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005492 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005493 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005494 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5495 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005496 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005497
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005498 // Add all of the factory methods in this Objective-C class, its protocols,
5499 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005500 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005501
Douglas Gregor6fc04132010-08-27 15:10:57 +00005502 // If this is a send-to-super, try to add the special "super" send
5503 // completion.
5504 if (IsSuper) {
5505 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005506 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005507 Results.Ignore(SuperMethod);
5508 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005509
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005510 // If we're inside an Objective-C method definition, prefer its selector to
5511 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005512 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005513 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005514
Douglas Gregor1154e272010-09-16 16:06:31 +00005515 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005516 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005517 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005518 SemaRef.CurContext, Selectors, AtArgumentExpression,
5519 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005520 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005521 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005522
Douglas Gregord720daf2010-04-06 17:30:22 +00005523 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005524 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005525 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005526 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005527 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005528 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005529 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005530 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005531 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005532
5533 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005534 }
5535 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005536
5537 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5538 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005539 M != MEnd; ++M) {
5540 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005541 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005542 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005543 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005544 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005545
Nico Weber2e0c8f72014-12-27 03:58:08 +00005546 Result R(MethList->getMethod(),
5547 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005548 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005549 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005550 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005551 }
5552 }
5553 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005554
5555 Results.ExitScope();
5556}
Douglas Gregor6285f752010-04-06 16:40:00 +00005557
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005558void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005559 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005560 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005561 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005562
5563 QualType T = this->GetTypeFromParser(Receiver);
5564
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005565 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005566 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005567 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005568 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005569
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005570 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005571 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005572
5573 // If we're actually at the argument expression (rather than prior to the
5574 // selector), we're actually performing code completion for an expression.
5575 // Determine whether we have a single, best method. If so, we can
5576 // code-complete the expression using the corresponding parameter type as
5577 // our preferred type, improving completion results.
5578 if (AtArgumentExpression) {
5579 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005580 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005581 if (PreferredType.isNull())
5582 CodeCompleteOrdinaryName(S, PCC_Expression);
5583 else
5584 CodeCompleteExpression(S, PreferredType);
5585 return;
5586 }
5587
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005588 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005589 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005590 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005591}
5592
Richard Trieu2bd04012011-09-09 02:00:50 +00005593void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005594 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005595 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005596 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005597 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005598
5599 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005600
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005601 // If necessary, apply function/array conversion to the receiver.
5602 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005603 if (RecExpr) {
5604 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5605 if (Conv.isInvalid()) // conversion failed. bail.
5606 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005607 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005608 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005609 QualType ReceiverType = RecExpr? RecExpr->getType()
5610 : Super? Context.getObjCObjectPointerType(
5611 Context.getObjCInterfaceType(Super))
5612 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005613
Douglas Gregordc520b02010-11-08 21:12:30 +00005614 // If we're messaging an expression with type "id" or "Class", check
5615 // whether we know something special about the receiver that allows
5616 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005617 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005618 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5619 if (ReceiverType->isObjCClassType())
5620 return CodeCompleteObjCClassMessage(S,
5621 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005622 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005623 AtArgumentExpression, Super);
5624
5625 ReceiverType = Context.getObjCObjectPointerType(
5626 Context.getObjCInterfaceType(IFace));
5627 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005628 } else if (RecExpr && getLangOpts().CPlusPlus) {
5629 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5630 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005631 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005632 ReceiverType = RecExpr->getType();
5633 }
5634 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005635
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005636 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005637 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005638 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005639 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005640 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005641
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005642 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005643
Douglas Gregor6fc04132010-08-27 15:10:57 +00005644 // If this is a send-to-super, try to add the special "super" send
5645 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005646 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005647 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005648 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005649 Results.Ignore(SuperMethod);
5650 }
5651
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005652 // If we're inside an Objective-C method definition, prefer its selector to
5653 // others.
5654 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5655 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005656
Douglas Gregor1154e272010-09-16 16:06:31 +00005657 // Keep track of the selectors we've already added.
5658 VisitedSelectorSet Selectors;
5659
Douglas Gregora3329fa2009-11-18 00:06:18 +00005660 // Handle messages to Class. This really isn't a message to an instance
5661 // method, so we treat it the same way we would treat a message send to a
5662 // class method.
5663 if (ReceiverType->isObjCClassType() ||
5664 ReceiverType->isObjCQualifiedClassType()) {
5665 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5666 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005667 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005668 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005669 }
5670 }
5671 // Handle messages to a qualified ID ("id<foo>").
5672 else if (const ObjCObjectPointerType *QualID
5673 = ReceiverType->getAsObjCQualifiedIdType()) {
5674 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005675 for (auto *I : QualID->quals())
5676 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005677 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005678 }
5679 // Handle messages to a pointer to interface type.
5680 else if (const ObjCObjectPointerType *IFacePtr
5681 = ReceiverType->getAsObjCInterfacePointerType()) {
5682 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005683 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005684 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005685 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005686
5687 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005688 for (auto *I : IFacePtr->quals())
5689 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005690 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005691 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005692 // Handle messages to "id".
5693 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005694 // We're messaging "id", so provide all instance methods we know
5695 // about as code-completion results.
5696
5697 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005698 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005699 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005700 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5701 I != N; ++I) {
5702 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005703 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005704 continue;
5705
Sebastian Redl75d8a322010-08-02 23:18:59 +00005706 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005707 }
5708 }
5709
Sebastian Redl75d8a322010-08-02 23:18:59 +00005710 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5711 MEnd = MethodPool.end();
5712 M != MEnd; ++M) {
5713 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005714 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005715 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005716 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005717 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005718
Nico Weber2e0c8f72014-12-27 03:58:08 +00005719 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005720 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005721
Nico Weber2e0c8f72014-12-27 03:58:08 +00005722 Result R(MethList->getMethod(),
5723 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005724 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005725 R.AllParametersAreInformative = false;
5726 Results.MaybeAddResult(R, CurContext);
5727 }
5728 }
5729 }
Steve Naroffeae65032009-11-07 02:08:14 +00005730 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005731
5732
5733 // If we're actually at the argument expression (rather than prior to the
5734 // selector), we're actually performing code completion for an expression.
5735 // Determine whether we have a single, best method. If so, we can
5736 // code-complete the expression using the corresponding parameter type as
5737 // our preferred type, improving completion results.
5738 if (AtArgumentExpression) {
5739 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005740 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005741 if (PreferredType.isNull())
5742 CodeCompleteOrdinaryName(S, PCC_Expression);
5743 else
5744 CodeCompleteExpression(S, PreferredType);
5745 return;
5746 }
5747
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005748 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005749 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005750 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005751}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005752
Douglas Gregor68762e72010-08-23 21:17:50 +00005753void Sema::CodeCompleteObjCForCollection(Scope *S,
5754 DeclGroupPtrTy IterationVar) {
5755 CodeCompleteExpressionData Data;
5756 Data.ObjCCollection = true;
5757
5758 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005759 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005760 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5761 if (*I)
5762 Data.IgnoreDecls.push_back(*I);
5763 }
5764 }
5765
5766 CodeCompleteExpression(S, Data);
5767}
5768
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005769void Sema::CodeCompleteObjCSelector(Scope *S,
5770 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005771 // If we have an external source, load the entire class method
5772 // pool from the AST file.
5773 if (ExternalSource) {
5774 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5775 I != N; ++I) {
5776 Selector Sel = ExternalSource->GetExternalSelector(I);
5777 if (Sel.isNull() || MethodPool.count(Sel))
5778 continue;
5779
5780 ReadMethodPool(Sel);
5781 }
5782 }
5783
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005784 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005785 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005786 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005787 Results.EnterNewScope();
5788 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5789 MEnd = MethodPool.end();
5790 M != MEnd; ++M) {
5791
5792 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005793 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005794 continue;
5795
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005796 CodeCompletionBuilder Builder(Results.getAllocator(),
5797 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005798 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005799 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005800 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005801 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005802 continue;
5803 }
5804
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005805 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005806 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005807 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005808 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005809 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005810 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005811 Accumulator.clear();
5812 }
5813 }
5814
Benjamin Kramer632500c2011-07-26 16:59:25 +00005815 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005816 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005817 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005818 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005819 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005820 }
5821 Results.ExitScope();
5822
5823 HandleCodeCompleteResults(this, CodeCompleter,
5824 CodeCompletionContext::CCC_SelectorName,
5825 Results.data(), Results.size());
5826}
5827
Douglas Gregorbaf69612009-11-18 04:19:12 +00005828/// \brief Add all of the protocol declarations that we find in the given
5829/// (translation unit) context.
5830static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005831 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005832 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005833 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005834
Aaron Ballman629afae2014-03-07 19:56:05 +00005835 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005836 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005837 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005838 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005839 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5840 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005841 }
5842}
5843
5844void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5845 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005846 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005847 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005848 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005849
Douglas Gregora3b23b02010-12-09 21:44:02 +00005850 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5851 Results.EnterNewScope();
5852
5853 // Tell the result set to ignore all of the protocols we have
5854 // already seen.
5855 // FIXME: This doesn't work when caching code-completion results.
5856 for (unsigned I = 0; I != NumProtocols; ++I)
5857 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5858 Protocols[I].second))
5859 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005860
Douglas Gregora3b23b02010-12-09 21:44:02 +00005861 // Add all protocols.
5862 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5863 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005864
Douglas Gregora3b23b02010-12-09 21:44:02 +00005865 Results.ExitScope();
5866 }
5867
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005868 HandleCodeCompleteResults(this, CodeCompleter,
5869 CodeCompletionContext::CCC_ObjCProtocolName,
5870 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005871}
5872
5873void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005874 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005875 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005876 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005877
Douglas Gregora3b23b02010-12-09 21:44:02 +00005878 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5879 Results.EnterNewScope();
5880
5881 // Add all protocols.
5882 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5883 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005884
Douglas Gregora3b23b02010-12-09 21:44:02 +00005885 Results.ExitScope();
5886 }
5887
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005888 HandleCodeCompleteResults(this, CodeCompleter,
5889 CodeCompletionContext::CCC_ObjCProtocolName,
5890 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005891}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005892
5893/// \brief Add all of the Objective-C interface declarations that we find in
5894/// the given (translation unit) context.
5895static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5896 bool OnlyForwardDeclarations,
5897 bool OnlyUnimplemented,
5898 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005899 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005900
Aaron Ballman629afae2014-03-07 19:56:05 +00005901 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005902 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005903 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005904 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005905 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005906 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5907 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005908 }
5909}
5910
5911void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005912 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005913 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005914 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005915 Results.EnterNewScope();
5916
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005917 if (CodeCompleter->includeGlobals()) {
5918 // Add all classes.
5919 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5920 false, Results);
5921 }
5922
Douglas Gregor49c22a72009-11-18 16:26:39 +00005923 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005924
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005925 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005926 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005927 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005928}
5929
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005930void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5931 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005932 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005933 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005934 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005935 Results.EnterNewScope();
5936
5937 // Make sure that we ignore the class we're currently defining.
5938 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005939 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005940 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00005941 Results.Ignore(CurClass);
5942
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005943 if (CodeCompleter->includeGlobals()) {
5944 // Add all classes.
5945 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5946 false, Results);
5947 }
5948
Douglas Gregor49c22a72009-11-18 16:26:39 +00005949 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005950
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005951 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005952 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005953 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005954}
5955
5956void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005957 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005958 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005959 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005960 Results.EnterNewScope();
5961
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005962 if (CodeCompleter->includeGlobals()) {
5963 // Add all unimplemented classes.
5964 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5965 true, Results);
5966 }
5967
Douglas Gregor49c22a72009-11-18 16:26:39 +00005968 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005969
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005970 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005971 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005972 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005973}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005974
5975void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005976 IdentifierInfo *ClassName,
5977 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005978 typedef CodeCompletionResult Result;
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 // Ignore any categories we find that have already been implemented by this
5985 // interface.
5986 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5987 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005988 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005989 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00005990 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005991 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005992 }
5993
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005994 // Add all of the categories we know about.
5995 Results.EnterNewScope();
5996 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00005997 for (const auto *D : TU->decls())
5998 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00005999 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006000 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6001 nullptr),
6002 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006003 Results.ExitScope();
6004
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006005 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006006 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006007 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006008}
6009
6010void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006011 IdentifierInfo *ClassName,
6012 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00006013 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006014
6015 // Find the corresponding interface. If we couldn't find the interface, the
6016 // program itself is ill-formed. However, we'll try to be helpful still by
6017 // providing the list of all of the categories we know about.
6018 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006019 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006020 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6021 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006022 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006023
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006024 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006025 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00006026 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006027
6028 // Add all of the categories that have have corresponding interface
6029 // declarations in this class and any of its superclasses, except for
6030 // already-implemented categories in the class itself.
6031 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6032 Results.EnterNewScope();
6033 bool IgnoreImplemented = true;
6034 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006035 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006036 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00006037 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00006038 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6039 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006040 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006041
6042 Class = Class->getSuperClass();
6043 IgnoreImplemented = false;
6044 }
6045 Results.ExitScope();
6046
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006047 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00006048 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006049 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00006050}
Douglas Gregor5d649882009-11-18 22:32:06 +00006051
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006052void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006053 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006054 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006055 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006056
6057 // Figure out where this @synthesize lives.
6058 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006059 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006060 if (!Container ||
6061 (!isa<ObjCImplementationDecl>(Container) &&
6062 !isa<ObjCCategoryImplDecl>(Container)))
6063 return;
6064
6065 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006066 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006067 for (const auto *D : Container->decls())
6068 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006069 Results.Ignore(PropertyImpl->getPropertyDecl());
6070
6071 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006072 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006073 Results.EnterNewScope();
6074 if (ObjCImplementationDecl *ClassImpl
6075 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor95147142011-05-05 15:50:42 +00006076 AddObjCProperties(ClassImpl->getClassInterface(), false,
6077 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006078 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006079 else
6080 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006081 false, /*AllowNullaryMethods=*/false, CurContext,
6082 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006083 Results.ExitScope();
6084
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006085 HandleCodeCompleteResults(this, CodeCompleter,
6086 CodeCompletionContext::CCC_Other,
6087 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006088}
6089
6090void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006091 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006092 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006093 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006094 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006095 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006096
6097 // Figure out where this @synthesize lives.
6098 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006099 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006100 if (!Container ||
6101 (!isa<ObjCImplementationDecl>(Container) &&
6102 !isa<ObjCCategoryImplDecl>(Container)))
6103 return;
6104
6105 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006106 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006107 if (ObjCImplementationDecl *ClassImpl
6108 = dyn_cast<ObjCImplementationDecl>(Container))
6109 Class = ClassImpl->getClassInterface();
6110 else
6111 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6112 ->getClassInterface();
6113
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006114 // Determine the type of the property we're synthesizing.
6115 QualType PropertyType = Context.getObjCIdType();
6116 if (Class) {
6117 if (ObjCPropertyDecl *Property
6118 = Class->FindPropertyDeclaration(PropertyName)) {
6119 PropertyType
6120 = Property->getType().getNonReferenceType().getUnqualifiedType();
6121
6122 // Give preference to ivars
6123 Results.setPreferredType(PropertyType);
6124 }
6125 }
6126
Douglas Gregor5d649882009-11-18 22:32:06 +00006127 // Add all of the instance variables in this class and its superclasses.
6128 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006129 bool SawSimilarlyNamedIvar = false;
6130 std::string NameWithPrefix;
6131 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006132 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006133 std::string NameWithSuffix = PropertyName->getName().str();
6134 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006135 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006136 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6137 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006138 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6139 CurContext, nullptr, false);
6140
Douglas Gregor331faa02011-04-18 14:13:53 +00006141 // Determine whether we've seen an ivar with a name similar to the
6142 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006143 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006144 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006145 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006146 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006147
6148 // Reduce the priority of this result by one, to give it a slight
6149 // advantage over other results whose names don't match so closely.
6150 if (Results.size() &&
6151 Results.data()[Results.size() - 1].Kind
6152 == CodeCompletionResult::RK_Declaration &&
6153 Results.data()[Results.size() - 1].Declaration == Ivar)
6154 Results.data()[Results.size() - 1].Priority--;
6155 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006156 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006157 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006158
6159 if (!SawSimilarlyNamedIvar) {
6160 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006161 // an ivar of the appropriate type.
6162 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006163 typedef CodeCompletionResult Result;
6164 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006165 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6166 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006167
Douglas Gregor75acd922011-09-27 23:30:47 +00006168 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006169 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006170 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006171 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6172 Results.AddResult(Result(Builder.TakeString(), Priority,
6173 CXCursor_ObjCIvarDecl));
6174 }
6175
Douglas Gregor5d649882009-11-18 22:32:06 +00006176 Results.ExitScope();
6177
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006178 HandleCodeCompleteResults(this, CodeCompleter,
6179 CodeCompletionContext::CCC_Other,
6180 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006181}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006182
Douglas Gregor416b5752010-08-25 01:08:01 +00006183// Mapping from selectors to the methods that implement that selector, along
6184// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006185typedef llvm::DenseMap<
6186 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006187
6188/// \brief Find all of the methods that reside in the given container
6189/// (and its superclasses, protocols, etc.) that meet the given
6190/// criteria. Insert those methods into the map of known methods,
6191/// indexed by selector so they can be easily found.
6192static void FindImplementableMethods(ASTContext &Context,
6193 ObjCContainerDecl *Container,
6194 bool WantInstanceMethods,
6195 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006196 KnownMethodsMap &KnownMethods,
6197 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006198 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006199 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006200 if (!IFace->hasDefinition())
6201 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006202
6203 IFace = IFace->getDefinition();
6204 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006205
Douglas Gregor636a61e2010-04-07 00:21:17 +00006206 const ObjCList<ObjCProtocolDecl> &Protocols
6207 = IFace->getReferencedProtocols();
6208 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006209 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006210 I != E; ++I)
6211 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006212 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006213
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006214 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006215 for (auto *Cat : IFace->visible_categories()) {
6216 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006217 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006218 }
6219
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006220 // Visit the superclass.
6221 if (IFace->getSuperClass())
6222 FindImplementableMethods(Context, IFace->getSuperClass(),
6223 WantInstanceMethods, ReturnType,
6224 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006225 }
6226
6227 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6228 // Recurse into protocols.
6229 const ObjCList<ObjCProtocolDecl> &Protocols
6230 = Category->getReferencedProtocols();
6231 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006232 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006233 I != E; ++I)
6234 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006235 KnownMethods, InOriginalClass);
6236
6237 // If this category is the original class, jump to the interface.
6238 if (InOriginalClass && Category->getClassInterface())
6239 FindImplementableMethods(Context, Category->getClassInterface(),
6240 WantInstanceMethods, ReturnType, KnownMethods,
6241 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006242 }
6243
6244 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006245 // Make sure we have a definition; that's what we'll walk.
6246 if (!Protocol->hasDefinition())
6247 return;
6248 Protocol = Protocol->getDefinition();
6249 Container = Protocol;
6250
6251 // Recurse into protocols.
6252 const ObjCList<ObjCProtocolDecl> &Protocols
6253 = Protocol->getReferencedProtocols();
6254 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6255 E = Protocols.end();
6256 I != E; ++I)
6257 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6258 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006259 }
6260
6261 // Add methods in this container. This operation occurs last because
6262 // we want the methods from this container to override any methods
6263 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006264 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006265 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006266 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006267 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006268 continue;
6269
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006270 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006271 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006272 }
6273 }
6274}
6275
Douglas Gregor669a25a2011-02-17 00:22:45 +00006276/// \brief Add the parenthesized return or parameter type chunk to a code
6277/// completion string.
6278static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006279 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006280 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006281 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006282 CodeCompletionBuilder &Builder) {
6283 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor29979142012-04-10 18:35:07 +00006284 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6285 if (!Quals.empty())
6286 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006287 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006288 Builder.getAllocator()));
6289 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6290}
6291
6292/// \brief Determine whether the given class is or inherits from a class by
6293/// the given name.
6294static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006295 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006296 if (!Class)
6297 return false;
6298
6299 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6300 return true;
6301
6302 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6303}
6304
6305/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6306/// Key-Value Observing (KVO).
6307static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6308 bool IsInstanceMethod,
6309 QualType ReturnType,
6310 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006311 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006312 ResultBuilder &Results) {
6313 IdentifierInfo *PropName = Property->getIdentifier();
6314 if (!PropName || PropName->getLength() == 0)
6315 return;
6316
Douglas Gregor75acd922011-09-27 23:30:47 +00006317 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6318
Douglas Gregor669a25a2011-02-17 00:22:45 +00006319 // Builder that will create each code completion.
6320 typedef CodeCompletionResult Result;
6321 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006322 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006323
6324 // The selector table.
6325 SelectorTable &Selectors = Context.Selectors;
6326
6327 // The property name, copied into the code completion allocation region
6328 // on demand.
6329 struct KeyHolder {
6330 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006331 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006332 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006333
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006334 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006335 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6336
Douglas Gregor669a25a2011-02-17 00:22:45 +00006337 operator const char *() {
6338 if (CopiedKey)
6339 return CopiedKey;
6340
6341 return CopiedKey = Allocator.CopyString(Key);
6342 }
6343 } Key(Allocator, PropName->getName());
6344
6345 // The uppercased name of the property name.
6346 std::string UpperKey = PropName->getName();
6347 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006348 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006349
6350 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6351 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6352 Property->getType());
6353 bool ReturnTypeMatchesVoid
6354 = ReturnType.isNull() || ReturnType->isVoidType();
6355
6356 // Add the normal accessor -(type)key.
6357 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006358 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006359 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6360 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006361 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6362 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006363
6364 Builder.AddTypedTextChunk(Key);
6365 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6366 CXCursor_ObjCInstanceMethodDecl));
6367 }
6368
6369 // If we have an integral or boolean property (or the user has provided
6370 // an integral or boolean return type), add the accessor -(type)isKey.
6371 if (IsInstanceMethod &&
6372 ((!ReturnType.isNull() &&
6373 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6374 (ReturnType.isNull() &&
6375 (Property->getType()->isIntegerType() ||
6376 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006377 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006378 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006379 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6380 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006381 if (ReturnType.isNull()) {
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("BOOL");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 }
6386
6387 Builder.AddTypedTextChunk(
6388 Allocator.CopyString(SelectorId->getName()));
6389 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6390 CXCursor_ObjCInstanceMethodDecl));
6391 }
6392 }
6393
6394 // Add the normal mutator.
6395 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6396 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006397 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006398 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006399 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006400 if (ReturnType.isNull()) {
6401 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6402 Builder.AddTextChunk("void");
6403 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6404 }
6405
6406 Builder.AddTypedTextChunk(
6407 Allocator.CopyString(SelectorId->getName()));
6408 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006409 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6410 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006411 Builder.AddTextChunk(Key);
6412 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6413 CXCursor_ObjCInstanceMethodDecl));
6414 }
6415 }
6416
6417 // Indexed and unordered accessors
6418 unsigned IndexedGetterPriority = CCP_CodePattern;
6419 unsigned IndexedSetterPriority = CCP_CodePattern;
6420 unsigned UnorderedGetterPriority = CCP_CodePattern;
6421 unsigned UnorderedSetterPriority = CCP_CodePattern;
6422 if (const ObjCObjectPointerType *ObjCPointer
6423 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6424 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6425 // If this interface type is not provably derived from a known
6426 // collection, penalize the corresponding completions.
6427 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6428 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6429 if (!InheritsFromClassNamed(IFace, "NSArray"))
6430 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6431 }
6432
6433 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6434 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6435 if (!InheritsFromClassNamed(IFace, "NSSet"))
6436 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6437 }
6438 }
6439 } else {
6440 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6441 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6442 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6443 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6444 }
6445
6446 // Add -(NSUInteger)countOf<key>
6447 if (IsInstanceMethod &&
6448 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006449 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006450 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006451 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6452 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006453 if (ReturnType.isNull()) {
6454 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6455 Builder.AddTextChunk("NSUInteger");
6456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6457 }
6458
6459 Builder.AddTypedTextChunk(
6460 Allocator.CopyString(SelectorId->getName()));
6461 Results.AddResult(Result(Builder.TakeString(),
6462 std::min(IndexedGetterPriority,
6463 UnorderedGetterPriority),
6464 CXCursor_ObjCInstanceMethodDecl));
6465 }
6466 }
6467
6468 // Indexed getters
6469 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6470 if (IsInstanceMethod &&
6471 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006472 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006473 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006474 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006475 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006476 if (ReturnType.isNull()) {
6477 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6478 Builder.AddTextChunk("id");
6479 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6480 }
6481
6482 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6483 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6484 Builder.AddTextChunk("NSUInteger");
6485 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6486 Builder.AddTextChunk("index");
6487 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6488 CXCursor_ObjCInstanceMethodDecl));
6489 }
6490 }
6491
6492 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6493 if (IsInstanceMethod &&
6494 (ReturnType.isNull() ||
6495 (ReturnType->isObjCObjectPointerType() &&
6496 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6497 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6498 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006499 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006500 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006501 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006502 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006503 if (ReturnType.isNull()) {
6504 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6505 Builder.AddTextChunk("NSArray *");
6506 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6507 }
6508
6509 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6510 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6511 Builder.AddTextChunk("NSIndexSet *");
6512 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6513 Builder.AddTextChunk("indexes");
6514 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6515 CXCursor_ObjCInstanceMethodDecl));
6516 }
6517 }
6518
6519 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6520 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006521 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006522 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006523 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006524 &Context.Idents.get("range")
6525 };
6526
David Blaikie82e95a32014-11-19 07:49:47 +00006527 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006528 if (ReturnType.isNull()) {
6529 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6530 Builder.AddTextChunk("void");
6531 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6532 }
6533
6534 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6535 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6536 Builder.AddPlaceholderChunk("object-type");
6537 Builder.AddTextChunk(" **");
6538 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6539 Builder.AddTextChunk("buffer");
6540 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6541 Builder.AddTypedTextChunk("range:");
6542 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6543 Builder.AddTextChunk("NSRange");
6544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6545 Builder.AddTextChunk("inRange");
6546 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6547 CXCursor_ObjCInstanceMethodDecl));
6548 }
6549 }
6550
6551 // Mutable indexed accessors
6552
6553 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6554 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006555 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006556 IdentifierInfo *SelectorIds[2] = {
6557 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006558 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006559 };
6560
David Blaikie82e95a32014-11-19 07:49:47 +00006561 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006562 if (ReturnType.isNull()) {
6563 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564 Builder.AddTextChunk("void");
6565 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6566 }
6567
6568 Builder.AddTypedTextChunk("insertObject:");
6569 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6570 Builder.AddPlaceholderChunk("object-type");
6571 Builder.AddTextChunk(" *");
6572 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6573 Builder.AddTextChunk("object");
6574 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6575 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6576 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6577 Builder.AddPlaceholderChunk("NSUInteger");
6578 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6579 Builder.AddTextChunk("index");
6580 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6581 CXCursor_ObjCInstanceMethodDecl));
6582 }
6583 }
6584
6585 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6586 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006587 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006588 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006589 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006590 &Context.Idents.get("atIndexes")
6591 };
6592
David Blaikie82e95a32014-11-19 07:49:47 +00006593 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006594 if (ReturnType.isNull()) {
6595 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6596 Builder.AddTextChunk("void");
6597 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6598 }
6599
6600 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6601 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6602 Builder.AddTextChunk("NSArray *");
6603 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6604 Builder.AddTextChunk("array");
6605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6606 Builder.AddTypedTextChunk("atIndexes:");
6607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6608 Builder.AddPlaceholderChunk("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)removeObjectFromKeyAtIndex:(NSUInteger)index
6617 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006618 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006619 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006620 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006621 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006622 if (ReturnType.isNull()) {
6623 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6624 Builder.AddTextChunk("void");
6625 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6626 }
6627
6628 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6629 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6630 Builder.AddTextChunk("NSUInteger");
6631 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6632 Builder.AddTextChunk("index");
6633 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6634 CXCursor_ObjCInstanceMethodDecl));
6635 }
6636 }
6637
6638 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6639 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006640 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006641 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006642 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006643 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006644 if (ReturnType.isNull()) {
6645 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6646 Builder.AddTextChunk("void");
6647 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6648 }
6649
6650 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6651 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6652 Builder.AddTextChunk("NSIndexSet *");
6653 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6654 Builder.AddTextChunk("indexes");
6655 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6656 CXCursor_ObjCInstanceMethodDecl));
6657 }
6658 }
6659
6660 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6661 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006662 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006663 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006664 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006665 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006666 &Context.Idents.get("withObject")
6667 };
6668
David Blaikie82e95a32014-11-19 07:49:47 +00006669 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006670 if (ReturnType.isNull()) {
6671 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6672 Builder.AddTextChunk("void");
6673 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6674 }
6675
6676 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6677 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6678 Builder.AddPlaceholderChunk("NSUInteger");
6679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6680 Builder.AddTextChunk("index");
6681 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6682 Builder.AddTypedTextChunk("withObject:");
6683 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6684 Builder.AddTextChunk("id");
6685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6686 Builder.AddTextChunk("object");
6687 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6688 CXCursor_ObjCInstanceMethodDecl));
6689 }
6690 }
6691
6692 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6693 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006694 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006695 = (Twine("replace") + UpperKey + "AtIndexes").str();
6696 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006697 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006698 &Context.Idents.get(SelectorName1),
6699 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006700 };
6701
David Blaikie82e95a32014-11-19 07:49:47 +00006702 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006703 if (ReturnType.isNull()) {
6704 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6705 Builder.AddTextChunk("void");
6706 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6707 }
6708
6709 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6710 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6711 Builder.AddPlaceholderChunk("NSIndexSet *");
6712 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6713 Builder.AddTextChunk("indexes");
6714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6715 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6716 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6717 Builder.AddTextChunk("NSArray *");
6718 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6719 Builder.AddTextChunk("array");
6720 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6721 CXCursor_ObjCInstanceMethodDecl));
6722 }
6723 }
6724
6725 // Unordered getters
6726 // - (NSEnumerator *)enumeratorOfKey
6727 if (IsInstanceMethod &&
6728 (ReturnType.isNull() ||
6729 (ReturnType->isObjCObjectPointerType() &&
6730 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6731 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6732 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006733 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006734 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006735 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6736 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006737 if (ReturnType.isNull()) {
6738 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6739 Builder.AddTextChunk("NSEnumerator *");
6740 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6741 }
6742
6743 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6744 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6745 CXCursor_ObjCInstanceMethodDecl));
6746 }
6747 }
6748
6749 // - (type *)memberOfKey:(type *)object
6750 if (IsInstanceMethod &&
6751 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006752 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006753 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006754 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006755 if (ReturnType.isNull()) {
6756 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6757 Builder.AddPlaceholderChunk("object-type");
6758 Builder.AddTextChunk(" *");
6759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6760 }
6761
6762 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6764 if (ReturnType.isNull()) {
6765 Builder.AddPlaceholderChunk("object-type");
6766 Builder.AddTextChunk(" *");
6767 } else {
6768 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006769 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006770 Builder.getAllocator()));
6771 }
6772 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6773 Builder.AddTextChunk("object");
6774 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6775 CXCursor_ObjCInstanceMethodDecl));
6776 }
6777 }
6778
6779 // Mutable unordered accessors
6780 // - (void)addKeyObject:(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("add") + 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)addKey:(NSSet *)objects
6804 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006805 std::string SelectorName = (Twine("add") + 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)removeKeyObject:(type *)object
6825 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006826 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006827 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006828 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006829 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006830 if (ReturnType.isNull()) {
6831 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6832 Builder.AddTextChunk("void");
6833 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6834 }
6835
6836 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6837 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6838 Builder.AddPlaceholderChunk("object-type");
6839 Builder.AddTextChunk(" *");
6840 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6841 Builder.AddTextChunk("object");
6842 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6843 CXCursor_ObjCInstanceMethodDecl));
6844 }
6845 }
6846
6847 // - (void)removeKey:(NSSet *)objects
6848 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006849 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006850 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006851 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006852 if (ReturnType.isNull()) {
6853 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6854 Builder.AddTextChunk("void");
6855 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6856 }
6857
6858 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6859 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6860 Builder.AddTextChunk("NSSet *");
6861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6862 Builder.AddTextChunk("objects");
6863 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6864 CXCursor_ObjCInstanceMethodDecl));
6865 }
6866 }
6867
6868 // - (void)intersectKey:(NSSet *)objects
6869 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006870 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006871 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006872 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006873 if (ReturnType.isNull()) {
6874 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6875 Builder.AddTextChunk("void");
6876 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6877 }
6878
6879 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6880 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6881 Builder.AddTextChunk("NSSet *");
6882 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6883 Builder.AddTextChunk("objects");
6884 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6885 CXCursor_ObjCInstanceMethodDecl));
6886 }
6887 }
6888
6889 // Key-Value Observing
6890 // + (NSSet *)keyPathsForValuesAffectingKey
6891 if (!IsInstanceMethod &&
6892 (ReturnType.isNull() ||
6893 (ReturnType->isObjCObjectPointerType() &&
6894 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6895 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6896 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006897 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006898 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006899 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006900 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6901 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006902 if (ReturnType.isNull()) {
6903 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6904 Builder.AddTextChunk("NSSet *");
6905 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6906 }
6907
6908 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6909 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006910 CXCursor_ObjCClassMethodDecl));
6911 }
6912 }
6913
6914 // + (BOOL)automaticallyNotifiesObserversForKey
6915 if (!IsInstanceMethod &&
6916 (ReturnType.isNull() ||
6917 ReturnType->isIntegerType() ||
6918 ReturnType->isBooleanType())) {
6919 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006920 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00006921 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006922 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6923 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00006924 if (ReturnType.isNull()) {
6925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6926 Builder.AddTextChunk("BOOL");
6927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6928 }
6929
6930 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6931 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6932 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00006933 }
6934 }
6935}
6936
Douglas Gregor636a61e2010-04-07 00:21:17 +00006937void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6938 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006939 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006940 // Determine the return type of the method we're declaring, if
6941 // provided.
6942 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00006943 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006944 if (CurContext->isObjCContainer()) {
6945 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6946 IDecl = cast<Decl>(OCD);
6947 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006948 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00006949 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006950 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00006951 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006952 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6953 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006954 IsInImplementation = true;
6955 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006956 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006957 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006958 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006959 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00006960 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006961 }
6962
6963 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00006964 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00006965 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006966 }
6967
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006968 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006969 HandleCodeCompleteResults(this, CodeCompleter,
6970 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00006971 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006972 return;
6973 }
6974
6975 // Find all of the methods that we could declare/implement here.
6976 KnownMethodsMap KnownMethods;
6977 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006978 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006979
Douglas Gregor636a61e2010-04-07 00:21:17 +00006980 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00006981 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006982 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006983 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006984 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006985 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00006986 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006987 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6988 MEnd = KnownMethods.end();
6989 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006990 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006991 CodeCompletionBuilder Builder(Results.getAllocator(),
6992 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006993
6994 // If the result type was not already provided, add it to the
6995 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00006996 if (ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00006997 AddObjCPassingTypeChunk(Method->getReturnType(),
6998 Method->getObjCDeclQualifier(), Context, Policy,
6999 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007000
7001 Selector Sel = Method->getSelector();
7002
7003 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007004 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007005 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007006
7007 // Add parameters to the pattern.
7008 unsigned I = 0;
7009 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7010 PEnd = Method->param_end();
7011 P != PEnd; (void)++P, ++I) {
7012 // Add the part of the selector name.
7013 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007014 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007015 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007016 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7017 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00007018 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007019 } else
7020 break;
7021
7022 // Add the parameter type.
Douglas Gregor29979142012-04-10 18:35:07 +00007023 AddObjCPassingTypeChunk((*P)->getOriginalType(),
7024 (*P)->getObjCDeclQualifier(),
7025 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00007026 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007027
7028 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007029 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007030 }
7031
7032 if (Method->isVariadic()) {
7033 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007034 Builder.AddChunk(CodeCompletionString::CK_Comma);
7035 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00007036 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00007037
Douglas Gregord37c59d2010-05-28 00:57:46 +00007038 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007039 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007040 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7041 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7042 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00007043 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00007044 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007045 Builder.AddTextChunk("return");
7046 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7047 Builder.AddPlaceholderChunk("expression");
7048 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007049 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007050 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00007051
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007052 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7053 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00007054 }
7055
Douglas Gregor416b5752010-08-25 01:08:01 +00007056 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007057 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007058 Priority += CCD_InBaseClass;
7059
Douglas Gregor78254c82012-03-27 23:34:16 +00007060 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007061 }
7062
Douglas Gregor669a25a2011-02-17 00:22:45 +00007063 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7064 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007065 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007066 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007067 Containers.push_back(SearchDecl);
7068
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007069 VisitedSelectorSet KnownSelectors;
7070 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7071 MEnd = KnownMethods.end();
7072 M != MEnd; ++M)
7073 KnownSelectors.insert(M->first);
7074
7075
Douglas Gregor669a25a2011-02-17 00:22:45 +00007076 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7077 if (!IFace)
7078 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7079 IFace = Category->getClassInterface();
7080
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007081 if (IFace)
7082 for (auto *Cat : IFace->visible_categories())
7083 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007084
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007085 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Aaron Ballmand174edf2014-03-13 19:11:50 +00007086 for (auto *P : Containers[I]->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007087 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007088 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007089 }
7090
Douglas Gregor636a61e2010-04-07 00:21:17 +00007091 Results.ExitScope();
7092
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007093 HandleCodeCompleteResults(this, CodeCompleter,
7094 CodeCompletionContext::CCC_Other,
7095 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007096}
Douglas Gregor95887f92010-07-08 23:20:03 +00007097
7098void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7099 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007100 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007101 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007102 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007103 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007104 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007105 if (ExternalSource) {
7106 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7107 I != N; ++I) {
7108 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007109 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007110 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007111
7112 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007113 }
7114 }
7115
7116 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007117 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007118 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007119 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007120 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007121
7122 if (ReturnTy)
7123 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007124
Douglas Gregor95887f92010-07-08 23:20:03 +00007125 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007126 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7127 MEnd = MethodPool.end();
7128 M != MEnd; ++M) {
7129 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7130 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007131 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007132 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007133 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007134 continue;
7135
Douglas Gregor45879692010-07-08 23:37:41 +00007136 if (AtParameterName) {
7137 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007138 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007139 if (NumSelIdents &&
7140 NumSelIdents <= MethList->getMethod()->param_size()) {
7141 ParmVarDecl *Param =
7142 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007143 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007144 CodeCompletionBuilder Builder(Results.getAllocator(),
7145 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007146 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007147 Param->getIdentifier()->getName()));
7148 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007149 }
7150 }
7151
7152 continue;
7153 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007154
Nico Weber2e0c8f72014-12-27 03:58:08 +00007155 Result R(MethList->getMethod(),
7156 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007157 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007158 R.AllParametersAreInformative = false;
7159 R.DeclaringEntity = true;
7160 Results.MaybeAddResult(R, CurContext);
7161 }
7162 }
7163
7164 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007165 HandleCodeCompleteResults(this, CodeCompleter,
7166 CodeCompletionContext::CCC_Other,
7167 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007168}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007169
Douglas Gregorec00a262010-08-24 22:20:20 +00007170void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007171 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007172 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007173 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007174 Results.EnterNewScope();
7175
7176 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007177 CodeCompletionBuilder Builder(Results.getAllocator(),
7178 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007179 Builder.AddTypedTextChunk("if");
7180 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7181 Builder.AddPlaceholderChunk("condition");
7182 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007183
7184 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007185 Builder.AddTypedTextChunk("ifdef");
7186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7187 Builder.AddPlaceholderChunk("macro");
7188 Results.AddResult(Builder.TakeString());
7189
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007190 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007191 Builder.AddTypedTextChunk("ifndef");
7192 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7193 Builder.AddPlaceholderChunk("macro");
7194 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007195
7196 if (InConditional) {
7197 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007198 Builder.AddTypedTextChunk("elif");
7199 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7200 Builder.AddPlaceholderChunk("condition");
7201 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007202
7203 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007204 Builder.AddTypedTextChunk("else");
7205 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007206
7207 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007208 Builder.AddTypedTextChunk("endif");
7209 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007210 }
7211
7212 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007213 Builder.AddTypedTextChunk("include");
7214 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7215 Builder.AddTextChunk("\"");
7216 Builder.AddPlaceholderChunk("header");
7217 Builder.AddTextChunk("\"");
7218 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007219
7220 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007221 Builder.AddTypedTextChunk("include");
7222 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7223 Builder.AddTextChunk("<");
7224 Builder.AddPlaceholderChunk("header");
7225 Builder.AddTextChunk(">");
7226 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007227
7228 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007229 Builder.AddTypedTextChunk("define");
7230 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7231 Builder.AddPlaceholderChunk("macro");
7232 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007233
7234 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007235 Builder.AddTypedTextChunk("define");
7236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7237 Builder.AddPlaceholderChunk("macro");
7238 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7239 Builder.AddPlaceholderChunk("args");
7240 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7241 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007242
7243 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007244 Builder.AddTypedTextChunk("undef");
7245 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7246 Builder.AddPlaceholderChunk("macro");
7247 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007248
7249 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007250 Builder.AddTypedTextChunk("line");
7251 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7252 Builder.AddPlaceholderChunk("number");
7253 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007254
7255 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007256 Builder.AddTypedTextChunk("line");
7257 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7258 Builder.AddPlaceholderChunk("number");
7259 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7260 Builder.AddTextChunk("\"");
7261 Builder.AddPlaceholderChunk("filename");
7262 Builder.AddTextChunk("\"");
7263 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007264
7265 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007266 Builder.AddTypedTextChunk("error");
7267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7268 Builder.AddPlaceholderChunk("message");
7269 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007270
7271 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007272 Builder.AddTypedTextChunk("pragma");
7273 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7274 Builder.AddPlaceholderChunk("arguments");
7275 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007276
David Blaikiebbafb8a2012-03-11 07:00:24 +00007277 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007278 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007279 Builder.AddTypedTextChunk("import");
7280 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7281 Builder.AddTextChunk("\"");
7282 Builder.AddPlaceholderChunk("header");
7283 Builder.AddTextChunk("\"");
7284 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007285
7286 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007287 Builder.AddTypedTextChunk("import");
7288 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7289 Builder.AddTextChunk("<");
7290 Builder.AddPlaceholderChunk("header");
7291 Builder.AddTextChunk(">");
7292 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007293 }
7294
7295 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007296 Builder.AddTypedTextChunk("include_next");
7297 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7298 Builder.AddTextChunk("\"");
7299 Builder.AddPlaceholderChunk("header");
7300 Builder.AddTextChunk("\"");
7301 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007302
7303 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007304 Builder.AddTypedTextChunk("include_next");
7305 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7306 Builder.AddTextChunk("<");
7307 Builder.AddPlaceholderChunk("header");
7308 Builder.AddTextChunk(">");
7309 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007310
7311 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007312 Builder.AddTypedTextChunk("warning");
7313 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7314 Builder.AddPlaceholderChunk("message");
7315 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007316
7317 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7318 // completions for them. And __include_macros is a Clang-internal extension
7319 // that we don't want to encourage anyone to use.
7320
7321 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7322 Results.ExitScope();
7323
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007324 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007325 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007326 Results.data(), Results.size());
7327}
7328
7329void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007330 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007331 S->getFnParent()? Sema::PCC_RecoveryInFunction
7332 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007333}
7334
Douglas Gregorec00a262010-08-24 22:20:20 +00007335void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007336 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007337 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007338 IsDefinition? CodeCompletionContext::CCC_MacroName
7339 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007340 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7341 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007342 CodeCompletionBuilder Builder(Results.getAllocator(),
7343 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007344 Results.EnterNewScope();
7345 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7346 MEnd = PP.macro_end();
7347 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007348 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007349 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007350 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7351 CCP_CodePattern,
7352 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007353 }
7354 Results.ExitScope();
7355 } else if (IsDefinition) {
7356 // FIXME: Can we detect when the user just wrote an include guard above?
7357 }
7358
Douglas Gregor0ac41382010-09-23 23:01:17 +00007359 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007360 Results.data(), Results.size());
7361}
7362
Douglas Gregorec00a262010-08-24 22:20:20 +00007363void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007364 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007365 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007366 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007367
7368 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007369 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007370
7371 // defined (<macro>)
7372 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007373 CodeCompletionBuilder Builder(Results.getAllocator(),
7374 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007375 Builder.AddTypedTextChunk("defined");
7376 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7377 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7378 Builder.AddPlaceholderChunk("macro");
7379 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7380 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007381 Results.ExitScope();
7382
7383 HandleCodeCompleteResults(this, CodeCompleter,
7384 CodeCompletionContext::CCC_PreprocessorExpression,
7385 Results.data(), Results.size());
7386}
7387
7388void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7389 IdentifierInfo *Macro,
7390 MacroInfo *MacroInfo,
7391 unsigned Argument) {
7392 // FIXME: In the future, we could provide "overload" results, much like we
7393 // do for function calls.
7394
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007395 // Now just ignore this. There will be another code-completion callback
7396 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007397}
7398
Douglas Gregor11583702010-08-25 17:04:25 +00007399void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007400 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007401 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007402 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007403}
7404
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007405void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007406 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007407 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007408 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7409 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007410 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7411 CodeCompletionDeclConsumer Consumer(Builder,
7412 Context.getTranslationUnitDecl());
7413 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7414 Consumer);
7415 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007416
7417 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007418 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007419
7420 Results.clear();
7421 Results.insert(Results.end(),
7422 Builder.data(), Builder.data() + Builder.size());
7423}