blob: b3059d588717b660689fa0cbea6e7433544716d0 [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/AST/DeclObjC.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Jordan Rose4938f272013-02-09 10:09:43 +000017#include "clang/Basic/CharInfo.h"
Douglas Gregor07f43572012-01-29 18:15:03 +000018#include "clang/Lex/HeaderSearch.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/CodeCompleteConsumer.h"
22#include "clang/Sema/ExternalSemaSource.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Sema/Overload.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
Douglas Gregor1154e272010-09-16 16:06:31 +000027#include "llvm/ADT/DenseSet.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000028#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000029#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000030#include "llvm/ADT/SmallString.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000032#include "llvm/ADT/StringSwitch.h"
Douglas Gregor67c692c2010-08-26 15:07:07 +000033#include "llvm/ADT/Twine.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000034#include <list>
35#include <map>
36#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000037
38using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000039using namespace sema;
Douglas Gregor2436e712009-09-17 21:32:03 +000040
Douglas Gregor3545ff42009-09-21 16:56:56 +000041namespace {
42 /// \brief A container of code-completion results.
43 class ResultBuilder {
44 public:
45 /// \brief The type of a name-lookup filter, which can be provided to the
46 /// name-lookup routines to specify which declarations should be included in
47 /// the result set (when it returns true) and which declarations should be
48 /// filtered out (returns false).
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000049 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +000050
John McCall276321a2010-08-25 06:19:51 +000051 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +000052
53 private:
54 /// \brief The actual results we have found.
55 std::vector<Result> Results;
56
57 /// \brief A record of all of the declarations we have found and placed
58 /// into the result set, used to ensure that no declaration ever gets into
59 /// the result set twice.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000060 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
Douglas Gregor3545ff42009-09-21 16:56:56 +000061
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000062 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000063
64 /// \brief An entry in the shadow map, which is optimized to store
65 /// a single (declaration, index) mapping (the common case) but
66 /// can also store a list of (declaration, index) mappings.
67 class ShadowMapEntry {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000069
70 /// \brief Contains either the solitary NamedDecl * or a vector
71 /// of (declaration, index) pairs.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000072 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
Douglas Gregor05e7ca32009-12-06 20:23:50 +000073
74 /// \brief When the entry contains a single declaration, this is
75 /// the index associated with that entry.
76 unsigned SingleDeclIndex;
77
78 public:
79 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000081 void Add(const NamedDecl *ND, unsigned Index) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000082 if (DeclOrVector.isNull()) {
83 // 0 - > 1 elements: just set the single element information.
84 DeclOrVector = ND;
85 SingleDeclIndex = Index;
86 return;
87 }
88
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +000089 if (const NamedDecl *PrevND =
90 DeclOrVector.dyn_cast<const NamedDecl *>()) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +000091 // 1 -> 2 elements: create the vector of results and push in the
92 // existing declaration.
93 DeclIndexPairVector *Vec = new DeclIndexPairVector;
94 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
95 DeclOrVector = Vec;
96 }
97
98 // Add the new element to the end of the vector.
99 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
100 DeclIndexPair(ND, Index));
101 }
102
103 void Destroy() {
104 if (DeclIndexPairVector *Vec
105 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
106 delete Vec;
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 DeclOrVector = ((NamedDecl *)nullptr);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000108 }
109 }
110
111 // Iteration.
112 class iterator;
113 iterator begin() const;
114 iterator end() const;
115 };
116
Douglas Gregor3545ff42009-09-21 16:56:56 +0000117 /// \brief A mapping from declaration names to the declarations that have
118 /// this name within a particular scope and their index within the list of
119 /// results.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000120 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000121
122 /// \brief The semantic analysis object for which results are being
123 /// produced.
124 Sema &SemaRef;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000125
126 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000127 CodeCompletionAllocator &Allocator;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000128
129 CodeCompletionTUInfo &CCTUInfo;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000130
131 /// \brief If non-NULL, a filter function used to remove any code-completion
132 /// results that are not desirable.
133 LookupFilter Filter;
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000134
135 /// \brief Whether we should allow declarations as
136 /// nested-name-specifiers that would otherwise be filtered out.
137 bool AllowNestedNameSpecifiers;
138
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000139 /// \brief If set, the type that we would prefer our resulting value
140 /// declarations to have.
141 ///
142 /// Closely matching the preferred type gives a boost to a result's
143 /// priority.
144 CanQualType PreferredType;
145
Douglas Gregor3545ff42009-09-21 16:56:56 +0000146 /// \brief A list of shadow maps, which is used to model name hiding at
147 /// different levels of, e.g., the inheritance hierarchy.
148 std::list<ShadowMap> ShadowMaps;
149
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000150 /// \brief If we're potentially referring to a C++ member function, the set
151 /// of qualifiers applied to the object type.
152 Qualifiers ObjectTypeQualifiers;
153
154 /// \brief Whether the \p ObjectTypeQualifiers field is active.
155 bool HasObjectTypeQualifiers;
156
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000157 /// \brief The selector that we prefer.
158 Selector PreferredSelector;
159
Douglas Gregor05fcf842010-11-02 20:36:02 +0000160 /// \brief The completion context in which we are gathering results.
Douglas Gregor50832e02010-09-20 22:39:41 +0000161 CodeCompletionContext CompletionContext;
162
James Dennett596e4752012-06-14 03:11:41 +0000163 /// \brief If we are in an instance method definition, the \@implementation
Douglas Gregor05fcf842010-11-02 20:36:02 +0000164 /// object.
165 ObjCImplementationDecl *ObjCImplementation;
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000166
Douglas Gregor50832e02010-09-20 22:39:41 +0000167 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor95887f92010-07-08 23:20:03 +0000168
Douglas Gregor0212fd72010-09-21 16:06:22 +0000169 void MaybeAddConstructorResults(Result R);
170
Douglas Gregor3545ff42009-09-21 16:56:56 +0000171 public:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000172 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000173 CodeCompletionTUInfo &CCTUInfo,
Douglas Gregor0ac41382010-09-23 23:01:17 +0000174 const CodeCompletionContext &CompletionContext,
Craig Topperc3ec1492014-05-26 06:22:03 +0000175 LookupFilter Filter = nullptr)
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000176 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
177 Filter(Filter),
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000178 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregor05fcf842010-11-02 20:36:02 +0000179 CompletionContext(CompletionContext),
Craig Topperc3ec1492014-05-26 06:22:03 +0000180 ObjCImplementation(nullptr)
Douglas Gregor05fcf842010-11-02 20:36:02 +0000181 {
182 // If this is an Objective-C instance method definition, dig out the
183 // corresponding implementation.
184 switch (CompletionContext.getKind()) {
185 case CodeCompletionContext::CCC_Expression:
186 case CodeCompletionContext::CCC_ObjCMessageReceiver:
187 case CodeCompletionContext::CCC_ParenthesizedExpression:
188 case CodeCompletionContext::CCC_Statement:
189 case CodeCompletionContext::CCC_Recovery:
190 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
191 if (Method->isInstanceMethod())
192 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
193 ObjCImplementation = Interface->getImplementation();
194 break;
195
196 default:
197 break;
198 }
199 }
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000200
201 /// \brief Determine the priority for a reference to the given declaration.
202 unsigned getBasePriority(const NamedDecl *D);
203
Douglas Gregorf64acca2010-05-25 21:41:55 +0000204 /// \brief Whether we should include code patterns in the completion
205 /// results.
206 bool includeCodePatterns() const {
207 return SemaRef.CodeCompleter &&
Douglas Gregorac322ec2010-08-27 21:18:54 +0000208 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregorf64acca2010-05-25 21:41:55 +0000209 }
210
Douglas Gregor3545ff42009-09-21 16:56:56 +0000211 /// \brief Set the filter used for code-completion results.
212 void setFilter(LookupFilter Filter) {
213 this->Filter = Filter;
214 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000215
216 Result *data() { return Results.empty()? nullptr : &Results.front(); }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000217 unsigned size() const { return Results.size(); }
218 bool empty() const { return Results.empty(); }
219
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000220 /// \brief Specify the preferred type.
221 void setPreferredType(QualType T) {
222 PreferredType = SemaRef.Context.getCanonicalType(T);
223 }
224
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000225 /// \brief Set the cv-qualifiers on the object type, for us in filtering
226 /// calls to member functions.
227 ///
228 /// When there are qualifiers in this set, they will be used to filter
229 /// out member functions that aren't available (because there will be a
230 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231 /// match.
232 void setObjectTypeQualifiers(Qualifiers Quals) {
233 ObjectTypeQualifiers = Quals;
234 HasObjectTypeQualifiers = true;
235 }
236
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000237 /// \brief Set the preferred selector.
238 ///
239 /// When an Objective-C method declaration result is added, and that
240 /// method's selector matches this preferred selector, we give that method
241 /// a slight priority boost.
242 void setPreferredSelector(Selector Sel) {
243 PreferredSelector = Sel;
244 }
Douglas Gregor05fcf842010-11-02 20:36:02 +0000245
Douglas Gregor50832e02010-09-20 22:39:41 +0000246 /// \brief Retrieve the code-completion context for which results are
247 /// being collected.
248 const CodeCompletionContext &getCompletionContext() const {
249 return CompletionContext;
250 }
251
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000252 /// \brief Specify whether nested-name-specifiers are allowed.
253 void allowNestedNameSpecifiers(bool Allow = true) {
254 AllowNestedNameSpecifiers = Allow;
255 }
256
Douglas Gregor74661272010-09-21 00:03:25 +0000257 /// \brief Return the semantic analysis object for which we are collecting
258 /// code completion results.
259 Sema &getSema() const { return SemaRef; }
260
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000261 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +0000262 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000263
264 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000265
Douglas Gregor7c208612010-01-14 00:20:49 +0000266 /// \brief Determine whether the given declaration is at all interesting
267 /// as a code-completion result.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000268 ///
269 /// \param ND the declaration that we are inspecting.
270 ///
271 /// \param AsNestedNameSpecifier will be set true if this declaration is
272 /// only interesting when it is a nested-name-specifier.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000273 bool isInterestingDecl(const NamedDecl *ND,
274 bool &AsNestedNameSpecifier) const;
Douglas Gregore0717ab2010-01-14 00:41:07 +0000275
276 /// \brief Check whether the result is hidden by the Hiding declaration.
277 ///
278 /// \returns true if the result is hidden and cannot be found, false if
279 /// the hidden result could still be found. When false, \p R may be
280 /// modified to describe how the result can be found (e.g., via extra
281 /// qualification).
282 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000283 const NamedDecl *Hiding);
Douglas Gregore0717ab2010-01-14 00:41:07 +0000284
Douglas Gregor3545ff42009-09-21 16:56:56 +0000285 /// \brief Add a new result to this result set (if it isn't already in one
286 /// of the shadow maps), or replace an existing result (for, e.g., a
287 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000288 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000289 /// \param R the result to add (if it is unique).
Douglas Gregor2af2f672009-09-21 20:12:40 +0000290 ///
Douglas Gregord8c61782012-02-15 15:34:24 +0000291 /// \param CurContext the context in which this result will be named.
Craig Topperc3ec1492014-05-26 06:22:03 +0000292 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
293
Douglas Gregorc580c522010-01-14 01:09:38 +0000294 /// \brief Add a new result to this result set, where we already know
Yaron Keren8fbe43982014-11-14 18:33:42 +0000295 /// the hiding declaration (if any).
Douglas Gregorc580c522010-01-14 01:09:38 +0000296 ///
297 /// \param R the result to add (if it is unique).
298 ///
299 /// \param CurContext the context in which this result will be named.
300 ///
301 /// \param Hiding the declaration that hides the result.
Douglas Gregor09bbc652010-01-14 15:47:35 +0000302 ///
303 /// \param InBaseClass whether the result was found in a base
304 /// class of the searched context.
305 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
306 bool InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +0000307
Douglas Gregor78a21012010-01-14 16:01:26 +0000308 /// \brief Add a new non-declaration result to this result set.
309 void AddResult(Result R);
310
Douglas Gregor3545ff42009-09-21 16:56:56 +0000311 /// \brief Enter into a new scope.
312 void EnterNewScope();
313
314 /// \brief Exit from the current scope.
315 void ExitScope();
316
Douglas Gregorbaf69612009-11-18 04:19:12 +0000317 /// \brief Ignore this declaration, if it is seen again.
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +0000318 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
Douglas Gregorbaf69612009-11-18 04:19:12 +0000319
Douglas Gregor3545ff42009-09-21 16:56:56 +0000320 /// \name Name lookup predicates
321 ///
322 /// These predicates can be passed to the name lookup functions to filter the
323 /// results of name lookup. All of the predicates have the same type, so that
324 ///
325 //@{
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000326 bool IsOrdinaryName(const NamedDecl *ND) const;
327 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
328 bool IsIntegralConstantValue(const NamedDecl *ND) const;
329 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
330 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
331 bool IsEnum(const NamedDecl *ND) const;
332 bool IsClassOrStruct(const NamedDecl *ND) const;
333 bool IsUnion(const NamedDecl *ND) const;
334 bool IsNamespace(const NamedDecl *ND) const;
335 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
336 bool IsType(const NamedDecl *ND) const;
337 bool IsMember(const NamedDecl *ND) const;
338 bool IsObjCIvar(const NamedDecl *ND) const;
339 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
340 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
341 bool IsObjCCollection(const NamedDecl *ND) const;
342 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000343 //@}
344 };
345}
346
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000347class ResultBuilder::ShadowMapEntry::iterator {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000348 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000349 unsigned SingleDeclIndex;
350
351public:
352 typedef DeclIndexPair value_type;
353 typedef value_type reference;
354 typedef std::ptrdiff_t difference_type;
355 typedef std::input_iterator_tag iterator_category;
356
357 class pointer {
358 DeclIndexPair Value;
359
360 public:
361 pointer(const DeclIndexPair &Value) : Value(Value) { }
362
363 const DeclIndexPair *operator->() const {
364 return &Value;
365 }
366 };
Craig Topperc3ec1492014-05-26 06:22:03 +0000367
368 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000369
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000370 iterator(const NamedDecl *SingleDecl, unsigned Index)
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000371 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
372
373 iterator(const DeclIndexPair *Iterator)
374 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
375
376 iterator &operator++() {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000377 if (DeclOrIterator.is<const NamedDecl *>()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000378 DeclOrIterator = (NamedDecl *)nullptr;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000379 SingleDeclIndex = 0;
380 return *this;
381 }
382
383 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
384 ++I;
385 DeclOrIterator = I;
386 return *this;
387 }
388
Chris Lattner9795b392010-09-04 18:12:20 +0000389 /*iterator operator++(int) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000390 iterator tmp(*this);
391 ++(*this);
392 return tmp;
Chris Lattner9795b392010-09-04 18:12:20 +0000393 }*/
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000394
395 reference operator*() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000396 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000397 return reference(ND, SingleDeclIndex);
398
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000399 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000400 }
401
402 pointer operator->() const {
403 return pointer(**this);
404 }
405
406 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000407 return X.DeclOrIterator.getOpaqueValue()
408 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000409 X.SingleDeclIndex == Y.SingleDeclIndex;
410 }
411
412 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000413 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000414 }
415};
416
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000417ResultBuilder::ShadowMapEntry::iterator
418ResultBuilder::ShadowMapEntry::begin() const {
419 if (DeclOrVector.isNull())
420 return iterator();
421
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000422 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000423 return iterator(ND, SingleDeclIndex);
424
425 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
426}
427
428ResultBuilder::ShadowMapEntry::iterator
429ResultBuilder::ShadowMapEntry::end() const {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000430 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000431 return iterator();
432
433 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
434}
435
Douglas Gregor2af2f672009-09-21 20:12:40 +0000436/// \brief Compute the qualification required to get from the current context
437/// (\p CurContext) to the target context (\p TargetContext).
438///
439/// \param Context the AST context in which the qualification will be used.
440///
441/// \param CurContext the context where an entity is being named, which is
442/// typically based on the current scope.
443///
444/// \param TargetContext the context in which the named entity actually
445/// resides.
446///
447/// \returns a nested name specifier that refers into the target context, or
448/// NULL if no qualification is needed.
449static NestedNameSpecifier *
450getRequiredQualification(ASTContext &Context,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000451 const DeclContext *CurContext,
452 const DeclContext *TargetContext) {
453 SmallVector<const DeclContext *, 4> TargetParents;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000454
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000455 for (const DeclContext *CommonAncestor = TargetContext;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000456 CommonAncestor && !CommonAncestor->Encloses(CurContext);
457 CommonAncestor = CommonAncestor->getLookupParent()) {
458 if (CommonAncestor->isTransparentContext() ||
459 CommonAncestor->isFunctionOrMethod())
460 continue;
461
462 TargetParents.push_back(CommonAncestor);
463 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000464
465 NestedNameSpecifier *Result = nullptr;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000466 while (!TargetParents.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000467 const DeclContext *Parent = TargetParents.pop_back_val();
468
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000469 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
Douglas Gregor68762e72010-08-23 21:17:50 +0000470 if (!Namespace->getIdentifier())
471 continue;
472
Douglas Gregor2af2f672009-09-21 20:12:40 +0000473 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregor68762e72010-08-23 21:17:50 +0000474 }
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000475 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000476 Result = NestedNameSpecifier::Create(Context, Result,
477 false,
478 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000479 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000480 return Result;
481}
482
Alp Toker034bbd52014-06-30 01:33:53 +0000483/// Determine whether \p Id is a name reserved for the implementation (C99
484/// 7.1.3, C++ [lib.global.names]).
485static bool isReservedName(const IdentifierInfo *Id) {
486 if (Id->getLength() < 2)
487 return false;
488 const char *Name = Id->getNameStart();
489 return Name[0] == '_' &&
490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z'));
491}
492
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000493bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000494 bool &AsNestedNameSpecifier) const {
495 AsNestedNameSpecifier = false;
496
Douglas Gregor7c208612010-01-14 00:20:49 +0000497 ND = ND->getUnderlyingDecl();
Douglas Gregor58acf322009-10-09 22:16:47 +0000498
499 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000500 if (!ND->getDeclName())
501 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000502
503 // Friend declarations and declarations introduced due to friends are never
504 // added as results.
Richard Smith6eece292015-01-15 02:27:20 +0000505 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
Douglas Gregor7c208612010-01-14 00:20:49 +0000506 return false;
507
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000508 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000509 if (isa<ClassTemplateSpecializationDecl>(ND) ||
510 isa<ClassTemplatePartialSpecializationDecl>(ND))
511 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000512
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000513 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000514 if (isa<UsingDecl>(ND))
515 return false;
516
517 // Some declarations have reserved names that we don't want to ever show.
Alp Toker034bbd52014-06-30 01:33:53 +0000518 // Filter out names reserved for the implementation if they come from a
519 // system header.
520 // TODO: Add a predicate for this.
521 if (const IdentifierInfo *Id = ND->getIdentifier())
522 if (isReservedName(Id) &&
523 (ND->getLocation().isInvalid() ||
524 SemaRef.SourceMgr.isInSystemHeader(
525 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregor7c208612010-01-14 00:20:49 +0000526 return false;
Douglas Gregor2927c0c2010-11-09 03:59:40 +0000527
Douglas Gregor59cab552010-08-16 23:05:20 +0000528 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
529 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
530 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor0ac41382010-09-23 23:01:17 +0000531 Filter != &ResultBuilder::IsNamespaceOrAlias &&
Craig Topperc3ec1492014-05-26 06:22:03 +0000532 Filter != nullptr))
Douglas Gregor59cab552010-08-16 23:05:20 +0000533 AsNestedNameSpecifier = true;
534
Douglas Gregor3545ff42009-09-21 16:56:56 +0000535 // Filter out any unwanted results.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000536 if (Filter && !(this->*Filter)(ND)) {
537 // Check whether it is interesting as a nested-name-specifier.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000538 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000539 IsNestedNameSpecifier(ND) &&
540 (Filter != &ResultBuilder::IsMember ||
541 (isa<CXXRecordDecl>(ND) &&
542 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
543 AsNestedNameSpecifier = true;
544 return true;
545 }
546
Douglas Gregor7c208612010-01-14 00:20:49 +0000547 return false;
Douglas Gregor59cab552010-08-16 23:05:20 +0000548 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000549 // ... then it must be interesting!
550 return true;
551}
552
Douglas Gregore0717ab2010-01-14 00:41:07 +0000553bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000554 const NamedDecl *Hiding) {
Douglas Gregore0717ab2010-01-14 00:41:07 +0000555 // In C, there is no way to refer to a hidden name.
556 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
557 // name if we introduce the tag type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000558 if (!SemaRef.getLangOpts().CPlusPlus)
Douglas Gregore0717ab2010-01-14 00:41:07 +0000559 return true;
560
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000561 const DeclContext *HiddenCtx =
562 R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregore0717ab2010-01-14 00:41:07 +0000563
564 // There is no way to qualify a name declared in a function or method.
565 if (HiddenCtx->isFunctionOrMethod())
566 return true;
567
Sebastian Redl50c68252010-08-31 00:36:30 +0000568 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregore0717ab2010-01-14 00:41:07 +0000569 return true;
570
571 // We can refer to the result with the appropriate qualification. Do it.
572 R.Hidden = true;
573 R.QualifierIsInformative = false;
574
575 if (!R.Qualifier)
576 R.Qualifier = getRequiredQualification(SemaRef.Context,
577 CurContext,
578 R.Declaration->getDeclContext());
579 return false;
580}
581
Douglas Gregor95887f92010-07-08 23:20:03 +0000582/// \brief A simplified classification of types used to determine whether two
583/// types are "similar enough" when adjusting priorities.
Douglas Gregor6e240332010-08-16 16:18:59 +0000584SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000585 switch (T->getTypeClass()) {
586 case Type::Builtin:
587 switch (cast<BuiltinType>(T)->getKind()) {
588 case BuiltinType::Void:
589 return STC_Void;
590
591 case BuiltinType::NullPtr:
592 return STC_Pointer;
593
594 case BuiltinType::Overload:
595 case BuiltinType::Dependent:
Douglas Gregor95887f92010-07-08 23:20:03 +0000596 return STC_Other;
597
598 case BuiltinType::ObjCId:
599 case BuiltinType::ObjCClass:
600 case BuiltinType::ObjCSel:
601 return STC_ObjectiveC;
602
603 default:
604 return STC_Arithmetic;
605 }
David Blaikie8a40f702012-01-17 06:56:22 +0000606
Douglas Gregor95887f92010-07-08 23:20:03 +0000607 case Type::Complex:
608 return STC_Arithmetic;
609
610 case Type::Pointer:
611 return STC_Pointer;
612
613 case Type::BlockPointer:
614 return STC_Block;
615
616 case Type::LValueReference:
617 case Type::RValueReference:
618 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return STC_Array;
625
626 case Type::DependentSizedExtVector:
627 case Type::Vector:
628 case Type::ExtVector:
629 return STC_Arithmetic;
630
631 case Type::FunctionProto:
632 case Type::FunctionNoProto:
633 return STC_Function;
634
635 case Type::Record:
636 return STC_Record;
637
638 case Type::Enum:
639 return STC_Arithmetic;
640
641 case Type::ObjCObject:
642 case Type::ObjCInterface:
643 case Type::ObjCObjectPointer:
644 return STC_ObjectiveC;
645
646 default:
647 return STC_Other;
648 }
649}
650
651/// \brief Get the type that a given expression will have if this declaration
652/// is used as an expression in its "typical" code-completion form.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000653QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
Douglas Gregor95887f92010-07-08 23:20:03 +0000654 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
655
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000656 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000657 return C.getTypeDeclType(Type);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000658 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000659 return C.getObjCInterfaceType(Iface);
660
661 QualType T;
Alp Tokera2794f92014-01-22 07:29:52 +0000662 if (const FunctionDecl *Function = ND->getAsFunction())
Douglas Gregor603d81b2010-07-13 08:18:22 +0000663 T = Function->getCallResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000664 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000665 T = Method->getSendResultType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000666 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000667 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000668 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000669 T = Property->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000670 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
Douglas Gregor95887f92010-07-08 23:20:03 +0000671 T = Value->getType();
672 else
673 return QualType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000674
675 // Dig through references, function pointers, and block pointers to
676 // get down to the likely type of an expression when the entity is
677 // used.
678 do {
679 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
680 T = Ref->getPointeeType();
681 continue;
682 }
683
684 if (const PointerType *Pointer = T->getAs<PointerType>()) {
685 if (Pointer->getPointeeType()->isFunctionType()) {
686 T = Pointer->getPointeeType();
687 continue;
688 }
689
690 break;
691 }
692
693 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
694 T = Block->getPointeeType();
695 continue;
696 }
697
698 if (const FunctionType *Function = T->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000699 T = Function->getReturnType();
Douglas Gregoraf670a82011-04-14 20:33:34 +0000700 continue;
701 }
702
703 break;
704 } while (true);
705
706 return T;
Douglas Gregor95887f92010-07-08 23:20:03 +0000707}
708
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000709unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
710 if (!ND)
711 return CCP_Unlikely;
712
713 // Context-based decisions.
Richard Smith541b38b2013-09-20 01:15:31 +0000714 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
715 if (LexicalDC->isFunctionOrMethod()) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000716 // _cmd is relatively rare
717 if (const ImplicitParamDecl *ImplicitParam =
718 dyn_cast<ImplicitParamDecl>(ND))
719 if (ImplicitParam->getIdentifier() &&
720 ImplicitParam->getIdentifier()->isStr("_cmd"))
721 return CCP_ObjC_cmd;
722
723 return CCP_LocalDeclaration;
724 }
Richard Smith541b38b2013-09-20 01:15:31 +0000725
726 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000727 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
728 return CCP_MemberDeclaration;
729
730 // Content-based decisions.
731 if (isa<EnumConstantDecl>(ND))
732 return CCP_Constant;
733
Douglas Gregor52e0de42013-01-31 05:03:46 +0000734 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
735 // message receiver, or parenthesized expression context. There, it's as
736 // likely that the user will want to write a type as other declarations.
737 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
738 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
739 CompletionContext.getKind()
740 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
741 CompletionContext.getKind()
742 == CodeCompletionContext::CCC_ParenthesizedExpression))
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000743 return CCP_Type;
744
745 return CCP_Declaration;
746}
747
Douglas Gregor50832e02010-09-20 22:39:41 +0000748void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
749 // If this is an Objective-C method declaration whose selector matches our
750 // preferred selector, give it a priority boost.
751 if (!PreferredSelector.isNull())
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000752 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
Douglas Gregor50832e02010-09-20 22:39:41 +0000753 if (PreferredSelector == Method->getSelector())
754 R.Priority += CCD_SelectorMatch;
Douglas Gregor5fb901d2010-09-20 23:11:55 +0000755
Douglas Gregor50832e02010-09-20 22:39:41 +0000756 // If we have a preferred type, adjust the priority for results with exactly-
757 // matching or nearly-matching types.
758 if (!PreferredType.isNull()) {
759 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
760 if (!T.isNull()) {
761 CanQualType TC = SemaRef.Context.getCanonicalType(T);
762 // Check for exactly-matching types (modulo qualifiers).
763 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
764 R.Priority /= CCF_ExactTypeMatch;
765 // Check for nearly-matching types, based on classification of each.
766 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor95887f92010-07-08 23:20:03 +0000767 == getSimplifiedTypeClass(TC)) &&
Douglas Gregor50832e02010-09-20 22:39:41 +0000768 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
769 R.Priority /= CCF_SimilarTypeMatch;
770 }
771 }
Douglas Gregor95887f92010-07-08 23:20:03 +0000772}
773
Douglas Gregor0212fd72010-09-21 16:06:22 +0000774void ResultBuilder::MaybeAddConstructorResults(Result R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
Douglas Gregor0212fd72010-09-21 16:06:22 +0000776 !CompletionContext.wantConstructorResults())
777 return;
778
779 ASTContext &Context = SemaRef.Context;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000780 const NamedDecl *D = R.Declaration;
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 const CXXRecordDecl *Record = nullptr;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000782 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Douglas Gregor0212fd72010-09-21 16:06:22 +0000783 Record = ClassTemplate->getTemplatedDecl();
784 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
785 // Skip specializations and partial specializations.
786 if (isa<ClassTemplateSpecializationDecl>(Record))
787 return;
788 } else {
789 // There are no constructors here.
790 return;
791 }
792
793 Record = Record->getDefinition();
794 if (!Record)
795 return;
796
797
798 QualType RecordTy = Context.getTypeDeclType(Record);
799 DeclarationName ConstructorName
800 = Context.DeclarationNames.getCXXConstructorName(
801 Context.getCanonicalType(RecordTy));
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000802 DeclContext::lookup_const_result Ctors = Record->lookup(ConstructorName);
803 for (DeclContext::lookup_const_iterator I = Ctors.begin(),
804 E = Ctors.end();
805 I != E; ++I) {
David Blaikieff7d47a2012-12-19 00:45:41 +0000806 R.Declaration = *I;
Douglas Gregor0212fd72010-09-21 16:06:22 +0000807 R.CursorKind = getCursorKindForDecl(R.Declaration);
808 Results.push_back(R);
809 }
810}
811
Douglas Gregor7c208612010-01-14 00:20:49 +0000812void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
813 assert(!ShadowMaps.empty() && "Must enter into a results scope");
814
815 if (R.Kind != Result::RK_Declaration) {
816 // For non-declaration results, just add the result.
817 Results.push_back(R);
818 return;
819 }
820
821 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000822 if (const UsingShadowDecl *Using =
823 dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000824 MaybeAddResult(Result(Using->getTargetDecl(),
825 getBasePriority(Using->getTargetDecl()),
826 R.Qualifier),
827 CurContext);
Douglas Gregor7c208612010-01-14 00:20:49 +0000828 return;
829 }
830
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000831 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
Douglas Gregor7c208612010-01-14 00:20:49 +0000832 unsigned IDNS = CanonDecl->getIdentifierNamespace();
833
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000834 bool AsNestedNameSpecifier = false;
835 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000836 return;
837
Douglas Gregor0212fd72010-09-21 16:06:22 +0000838 // C++ constructors are never found by name lookup.
839 if (isa<CXXConstructorDecl>(R.Declaration))
840 return;
841
Douglas Gregor3545ff42009-09-21 16:56:56 +0000842 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000843 ShadowMapEntry::iterator I, IEnd;
844 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
845 if (NamePos != SMap.end()) {
846 I = NamePos->second.begin();
847 IEnd = NamePos->second.end();
848 }
849
850 for (; I != IEnd; ++I) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000851 const NamedDecl *ND = I->first;
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000852 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000853 if (ND->getCanonicalDecl() == CanonDecl) {
854 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000855 Results[Index].Declaration = R.Declaration;
856
Douglas Gregor3545ff42009-09-21 16:56:56 +0000857 // We're done.
858 return;
859 }
860 }
861
862 // This is a new declaration in this scope. However, check whether this
863 // declaration name is hidden by a similarly-named declaration in an outer
864 // scope.
865 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
866 --SMEnd;
867 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000868 ShadowMapEntry::iterator I, IEnd;
869 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
870 if (NamePos != SM->end()) {
871 I = NamePos->second.begin();
872 IEnd = NamePos->second.end();
873 }
874 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000875 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000876 if (I->first->hasTagIdentifierNamespace() &&
Richard Smith541b38b2013-09-20 01:15:31 +0000877 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
878 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000879 continue;
880
881 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000882 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000883 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000884 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000885 continue;
886
887 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000888 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000889 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000890
891 break;
892 }
893 }
894
895 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000896 if (!AllDeclsFound.insert(CanonDecl).second)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000897 return;
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000898
Douglas Gregore412a5a2009-09-23 22:26:46 +0000899 // If the filter is for nested-name-specifiers, then this result starts a
900 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000901 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000902 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000903 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor50832e02010-09-20 22:39:41 +0000904 } else
905 AdjustResultPriorityForDecl(R);
Douglas Gregorc2cb2e22010-08-27 15:29:55 +0000906
Douglas Gregor5bf52692009-09-22 23:15:58 +0000907 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000908 if (R.QualifierIsInformative && !R.Qualifier &&
909 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000910 const DeclContext *Ctx = R.Declaration->getDeclContext();
911 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
913 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000914 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000915 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
916 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor5bf52692009-09-22 23:15:58 +0000917 else
918 R.QualifierIsInformative = false;
919 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000920
Douglas Gregor3545ff42009-09-21 16:56:56 +0000921 // Insert this result into the set of results and into the current shadow
922 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000923 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000924 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +0000925
926 if (!AsNestedNameSpecifier)
927 MaybeAddConstructorResults(R);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000928}
929
Douglas Gregorc580c522010-01-14 01:09:38 +0000930void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000931 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000932 if (R.Kind != Result::RK_Declaration) {
933 // For non-declaration results, just add the result.
934 Results.push_back(R);
935 return;
936 }
937
Douglas Gregorc580c522010-01-14 01:09:38 +0000938 // Look through using declarations.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000939 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
Douglas Gregor0a0e2b32013-01-31 04:52:16 +0000940 AddResult(Result(Using->getTargetDecl(),
941 getBasePriority(Using->getTargetDecl()),
942 R.Qualifier),
943 CurContext, Hiding);
Douglas Gregorc580c522010-01-14 01:09:38 +0000944 return;
945 }
946
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000947 bool AsNestedNameSpecifier = false;
948 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000949 return;
950
Douglas Gregor0212fd72010-09-21 16:06:22 +0000951 // C++ constructors are never found by name lookup.
952 if (isa<CXXConstructorDecl>(R.Declaration))
953 return;
954
Douglas Gregorc580c522010-01-14 01:09:38 +0000955 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
956 return;
Nick Lewyckyc3921482012-04-03 21:44:08 +0000957
Douglas Gregorc580c522010-01-14 01:09:38 +0000958 // Make sure that any given declaration only shows up in the result set once.
David Blaikie82e95a32014-11-19 07:49:47 +0000959 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
Douglas Gregorc580c522010-01-14 01:09:38 +0000960 return;
961
962 // If the filter is for nested-name-specifiers, then this result starts a
963 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000964 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000965 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000966 R.Priority = CCP_NestedNameSpecifier;
967 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000968 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
969 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl50c68252010-08-31 00:36:30 +0000970 ->getRedeclContext()))
Douglas Gregor09bbc652010-01-14 15:47:35 +0000971 R.QualifierIsInformative = true;
972
Douglas Gregorc580c522010-01-14 01:09:38 +0000973 // If this result is supposed to have an informative qualifier, add one.
974 if (R.QualifierIsInformative && !R.Qualifier &&
975 !R.StartsNestedNameSpecifier) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000976 const DeclContext *Ctx = R.Declaration->getDeclContext();
977 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000978 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
979 Namespace);
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000980 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
Craig Topperc3ec1492014-05-26 06:22:03 +0000981 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000982 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000983 else
984 R.QualifierIsInformative = false;
985 }
986
Douglas Gregora2db7932010-05-26 22:00:08 +0000987 // Adjust the priority if this result comes from a base class.
988 if (InBaseClass)
989 R.Priority += CCD_InBaseClass;
990
Douglas Gregor50832e02010-09-20 22:39:41 +0000991 AdjustResultPriorityForDecl(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000992
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000993 if (HasObjectTypeQualifiers)
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000994 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
Douglas Gregor9be0ed42010-08-26 16:36:48 +0000995 if (Method->isInstance()) {
996 Qualifiers MethodQuals
997 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
998 if (ObjectTypeQualifiers == MethodQuals)
999 R.Priority += CCD_ObjectQualifierMatch;
1000 else if (ObjectTypeQualifiers - MethodQuals) {
1001 // The method cannot be invoked, because doing so would drop
1002 // qualifiers.
1003 return;
1004 }
1005 }
1006
Douglas Gregorc580c522010-01-14 01:09:38 +00001007 // Insert this result into the set of results.
1008 Results.push_back(R);
Douglas Gregor0212fd72010-09-21 16:06:22 +00001009
1010 if (!AsNestedNameSpecifier)
1011 MaybeAddConstructorResults(R);
Douglas Gregorc580c522010-01-14 01:09:38 +00001012}
1013
Douglas Gregor78a21012010-01-14 16:01:26 +00001014void ResultBuilder::AddResult(Result R) {
1015 assert(R.Kind != Result::RK_Declaration &&
1016 "Declaration results need more context");
1017 Results.push_back(R);
1018}
1019
Douglas Gregor3545ff42009-09-21 16:56:56 +00001020/// \brief Enter into a new scope.
1021void ResultBuilder::EnterNewScope() {
1022 ShadowMaps.push_back(ShadowMap());
1023}
1024
1025/// \brief Exit from the current scope.
1026void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +00001027 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1028 EEnd = ShadowMaps.back().end();
1029 E != EEnd;
1030 ++E)
1031 E->second.Destroy();
1032
Douglas Gregor3545ff42009-09-21 16:56:56 +00001033 ShadowMaps.pop_back();
1034}
1035
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001036/// \brief Determines whether this given declaration will be found by
1037/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001038bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001039 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1040
Richard Smith541b38b2013-09-20 01:15:31 +00001041 // If name lookup finds a local extern declaration, then we are in a
1042 // context where it behaves like an ordinary name.
1043 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001044 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001045 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001046 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001047 if (isa<ObjCIvarDecl>(ND))
1048 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001049 }
1050
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001051 return ND->getIdentifierNamespace() & IDNS;
1052}
1053
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001054/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +00001055/// ordinary name lookup but is not a type name.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001056bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001057 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1058 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1059 return false;
1060
Richard Smith541b38b2013-09-20 01:15:31 +00001061 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001062 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +00001063 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001064 else if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001065 if (isa<ObjCIvarDecl>(ND))
1066 return true;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001067 }
1068
Douglas Gregor70febae2010-05-28 00:49:12 +00001069 return ND->getIdentifierNamespace() & IDNS;
1070}
1071
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001072bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
Douglas Gregor85b50632010-07-28 21:50:18 +00001073 if (!IsOrdinaryNonTypeName(ND))
1074 return 0;
1075
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001076 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
Douglas Gregor85b50632010-07-28 21:50:18 +00001077 if (VD->getType()->isIntegralOrEnumerationType())
1078 return true;
1079
1080 return false;
1081}
1082
Douglas Gregor70febae2010-05-28 00:49:12 +00001083/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001084/// ordinary name lookup.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001085bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +00001086 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1087
Richard Smith541b38b2013-09-20 01:15:31 +00001088 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001089 if (SemaRef.getLangOpts().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +00001090 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001091
1092 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +00001093 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1094 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001095}
1096
Douglas Gregor3545ff42009-09-21 16:56:56 +00001097/// \brief Determines whether the given declaration is suitable as the
1098/// start of a C++ nested-name-specifier, e.g., a class or namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001099bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001101 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001102 ND = ClassTemplate->getTemplatedDecl();
1103
1104 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1105}
1106
1107/// \brief Determines whether the given declaration is an enumeration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001108bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001109 return isa<EnumDecl>(ND);
1110}
1111
1112/// \brief Determines whether the given declaration is a class or struct.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001113bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001114 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001115 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001116 ND = ClassTemplate->getTemplatedDecl();
Joao Matosdc86f942012-08-31 18:45:21 +00001117
1118 // For purposes of this check, interfaces match too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001119 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001120 return RD->getTagKind() == TTK_Class ||
Joao Matosdc86f942012-08-31 18:45:21 +00001121 RD->getTagKind() == TTK_Struct ||
1122 RD->getTagKind() == TTK_Interface;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001123
1124 return false;
1125}
1126
1127/// \brief Determines whether the given declaration is a union.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001128bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001129 // Allow us to find class templates, too.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001130 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
Douglas Gregor3545ff42009-09-21 16:56:56 +00001131 ND = ClassTemplate->getTemplatedDecl();
1132
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001133 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +00001134 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001135
1136 return false;
1137}
1138
1139/// \brief Determines whether the given declaration is a namespace.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001140bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001141 return isa<NamespaceDecl>(ND);
1142}
1143
1144/// \brief Determines whether the given declaration is a namespace or
1145/// namespace alias.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001146bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001147 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1148}
1149
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001150/// \brief Determines whether the given declaration is a type.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001151bool ResultBuilder::IsType(const NamedDecl *ND) const {
1152 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fa2642010-08-24 01:06:58 +00001153 ND = Using->getTargetDecl();
1154
1155 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001156}
1157
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001158/// \brief Determines which members of a class should be visible via
1159/// "." or "->". Only value declarations, nested name specifiers, and
1160/// using declarations thereof should show up.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001161bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1162 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
Douglas Gregor99fe2ad2009-12-11 17:31:05 +00001163 ND = Using->getTargetDecl();
1164
Douglas Gregor70788392009-12-11 18:14:22 +00001165 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1166 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +00001167}
1168
Douglas Gregora817a192010-05-27 23:06:34 +00001169static bool isObjCReceiverType(ASTContext &C, QualType T) {
1170 T = C.getCanonicalType(T);
1171 switch (T->getTypeClass()) {
1172 case Type::ObjCObject:
1173 case Type::ObjCInterface:
1174 case Type::ObjCObjectPointer:
1175 return true;
1176
1177 case Type::Builtin:
1178 switch (cast<BuiltinType>(T)->getKind()) {
1179 case BuiltinType::ObjCId:
1180 case BuiltinType::ObjCClass:
1181 case BuiltinType::ObjCSel:
1182 return true;
1183
1184 default:
1185 break;
1186 }
1187 return false;
1188
1189 default:
1190 break;
1191 }
1192
David Blaikiebbafb8a2012-03-11 07:00:24 +00001193 if (!C.getLangOpts().CPlusPlus)
Douglas Gregora817a192010-05-27 23:06:34 +00001194 return false;
1195
1196 // FIXME: We could perform more analysis here to determine whether a
1197 // particular class type has any conversions to Objective-C types. For now,
1198 // just accept all class types.
1199 return T->isDependentType() || T->isRecordType();
1200}
1201
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001202bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
Douglas Gregora817a192010-05-27 23:06:34 +00001203 QualType T = getDeclUsageType(SemaRef.Context, ND);
1204 if (T.isNull())
1205 return false;
1206
1207 T = SemaRef.Context.getBaseElementType(T);
1208 return isObjCReceiverType(SemaRef.Context, T);
1209}
1210
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001211bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
Douglas Gregord8c61782012-02-15 15:34:24 +00001212 if (IsObjCMessageReceiver(ND))
1213 return true;
1214
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001215 const VarDecl *Var = dyn_cast<VarDecl>(ND);
Douglas Gregord8c61782012-02-15 15:34:24 +00001216 if (!Var)
1217 return false;
1218
1219 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1220}
1221
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001222bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001223 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1224 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
Douglas Gregor68762e72010-08-23 21:17:50 +00001225 return false;
1226
1227 QualType T = getDeclUsageType(SemaRef.Context, ND);
1228 if (T.isNull())
1229 return false;
1230
1231 T = SemaRef.Context.getBaseElementType(T);
1232 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1233 T->isObjCIdType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001234 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
Douglas Gregor68762e72010-08-23 21:17:50 +00001235}
Douglas Gregora817a192010-05-27 23:06:34 +00001236
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001237bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001238 return false;
1239}
1240
James Dennettf1243872012-06-17 05:33:25 +00001241/// \brief Determines whether the given declaration is an Objective-C
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001242/// instance variable.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00001243bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
Douglas Gregor2b8162b2010-01-14 16:08:12 +00001244 return isa<ObjCIvarDecl>(ND);
1245}
1246
Douglas Gregorc580c522010-01-14 01:09:38 +00001247namespace {
1248 /// \brief Visible declaration consumer that adds a code-completion result
1249 /// for each visible declaration.
1250 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1251 ResultBuilder &Results;
1252 DeclContext *CurContext;
1253
1254 public:
1255 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1256 : Results(Results), CurContext(CurContext) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00001257
1258 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1259 bool InBaseClass) override {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001260 bool Accessible = true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001261 if (Ctx)
1262 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
Craig Topperc3ec1492014-05-26 06:22:03 +00001263
1264 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1265 false, Accessible);
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001266 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +00001267 }
1268 };
1269}
1270
Douglas Gregor3545ff42009-09-21 16:56:56 +00001271/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001272static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +00001273 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001274 typedef CodeCompletionResult Result;
Douglas Gregora2db7932010-05-26 22:00:08 +00001275 Results.AddResult(Result("short", CCP_Type));
1276 Results.AddResult(Result("long", CCP_Type));
1277 Results.AddResult(Result("signed", CCP_Type));
1278 Results.AddResult(Result("unsigned", CCP_Type));
1279 Results.AddResult(Result("void", CCP_Type));
1280 Results.AddResult(Result("char", CCP_Type));
1281 Results.AddResult(Result("int", CCP_Type));
1282 Results.AddResult(Result("float", CCP_Type));
1283 Results.AddResult(Result("double", CCP_Type));
1284 Results.AddResult(Result("enum", CCP_Type));
1285 Results.AddResult(Result("struct", CCP_Type));
1286 Results.AddResult(Result("union", CCP_Type));
1287 Results.AddResult(Result("const", CCP_Type));
1288 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001289
Douglas Gregor3545ff42009-09-21 16:56:56 +00001290 if (LangOpts.C99) {
1291 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001292 Results.AddResult(Result("_Complex", CCP_Type));
1293 Results.AddResult(Result("_Imaginary", CCP_Type));
1294 Results.AddResult(Result("_Bool", CCP_Type));
1295 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001296 }
1297
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001298 CodeCompletionBuilder Builder(Results.getAllocator(),
1299 Results.getCodeCompletionTUInfo());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001300 if (LangOpts.CPlusPlus) {
1301 // C++-specific
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001302 Results.AddResult(Result("bool", CCP_Type +
1303 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregora2db7932010-05-26 22:00:08 +00001304 Results.AddResult(Result("class", CCP_Type));
1305 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001306
Douglas Gregorf4c33342010-05-28 00:22:41 +00001307 // typename qualified-id
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001308 Builder.AddTypedTextChunk("typename");
1309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1310 Builder.AddPlaceholderChunk("qualifier");
1311 Builder.AddTextChunk("::");
1312 Builder.AddPlaceholderChunk("name");
1313 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001314
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001315 if (LangOpts.CPlusPlus11) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001316 Results.AddResult(Result("auto", CCP_Type));
1317 Results.AddResult(Result("char16_t", CCP_Type));
1318 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001319
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001320 Builder.AddTypedTextChunk("decltype");
1321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1322 Builder.AddPlaceholderChunk("expression");
1323 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1324 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001325 }
1326 }
1327
1328 // GNU extensions
1329 if (LangOpts.GNUMode) {
1330 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001331 // Results.AddResult(Result("_Decimal32"));
1332 // Results.AddResult(Result("_Decimal64"));
1333 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001334
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001335 Builder.AddTypedTextChunk("typeof");
1336 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1337 Builder.AddPlaceholderChunk("expression");
1338 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001339
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001340 Builder.AddTypedTextChunk("typeof");
1341 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1342 Builder.AddPlaceholderChunk("type");
1343 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1344 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001345 }
1346}
1347
John McCallfaf5fb42010-08-26 23:41:50 +00001348static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001349 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001350 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001351 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001352 // Note: we don't suggest either "auto" or "register", because both
1353 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1354 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001355 Results.AddResult(Result("extern"));
1356 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001357}
1358
John McCallfaf5fb42010-08-26 23:41:50 +00001359static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001361 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00001362 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001363 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001364 case Sema::PCC_Class:
1365 case Sema::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001366 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001367 Results.AddResult(Result("explicit"));
1368 Results.AddResult(Result("friend"));
1369 Results.AddResult(Result("mutable"));
1370 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001371 }
1372 // Fall through
1373
John McCallfaf5fb42010-08-26 23:41:50 +00001374 case Sema::PCC_ObjCInterface:
1375 case Sema::PCC_ObjCImplementation:
1376 case Sema::PCC_Namespace:
1377 case Sema::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001378 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001379 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001380 break;
1381
John McCallfaf5fb42010-08-26 23:41:50 +00001382 case Sema::PCC_ObjCInstanceVariableList:
1383 case Sema::PCC_Expression:
1384 case Sema::PCC_Statement:
1385 case Sema::PCC_ForInit:
1386 case Sema::PCC_Condition:
1387 case Sema::PCC_RecoveryInFunction:
1388 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001389 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001390 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001391 break;
1392 }
1393}
1394
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001395static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1396static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1397static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001398 ResultBuilder &Results,
1399 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001400static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001401 ResultBuilder &Results,
1402 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001403static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001404 ResultBuilder &Results,
1405 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001406static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001407
Douglas Gregorf4c33342010-05-28 00:22:41 +00001408static void AddTypedefResult(ResultBuilder &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001409 CodeCompletionBuilder Builder(Results.getAllocator(),
1410 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("typedef");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("type");
1414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1415 Builder.AddPlaceholderChunk("name");
1416 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001417}
1418
John McCallfaf5fb42010-08-26 23:41:50 +00001419static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001420 const LangOptions &LangOpts) {
Douglas Gregor70febae2010-05-28 00:49:12 +00001421 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001422 case Sema::PCC_Namespace:
1423 case Sema::PCC_Class:
1424 case Sema::PCC_ObjCInstanceVariableList:
1425 case Sema::PCC_Template:
1426 case Sema::PCC_MemberTemplate:
1427 case Sema::PCC_Statement:
1428 case Sema::PCC_RecoveryInFunction:
1429 case Sema::PCC_Type:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001430 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor80039242011-02-15 20:33:25 +00001431 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor70febae2010-05-28 00:49:12 +00001432 return true;
1433
John McCallfaf5fb42010-08-26 23:41:50 +00001434 case Sema::PCC_Expression:
1435 case Sema::PCC_Condition:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001436 return LangOpts.CPlusPlus;
1437
1438 case Sema::PCC_ObjCInterface:
1439 case Sema::PCC_ObjCImplementation:
Douglas Gregor70febae2010-05-28 00:49:12 +00001440 return false;
1441
John McCallfaf5fb42010-08-26 23:41:50 +00001442 case Sema::PCC_ForInit:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001443 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor70febae2010-05-28 00:49:12 +00001444 }
David Blaikie8a40f702012-01-17 06:56:22 +00001445
1446 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor70febae2010-05-28 00:49:12 +00001447}
1448
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001449static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1450 const Preprocessor &PP) {
1451 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001452 Policy.AnonymousTagLocations = false;
1453 Policy.SuppressStrongLifetime = true;
Douglas Gregor2e10cf92011-11-03 00:16:13 +00001454 Policy.SuppressUnwrittenScope = true;
Douglas Gregore5c79d52011-10-18 21:20:17 +00001455 return Policy;
1456}
1457
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00001458/// \brief Retrieve a printing policy suitable for code completion.
1459static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1460 return getCompletionPrintingPolicy(S.Context, S.PP);
1461}
1462
Douglas Gregore5c79d52011-10-18 21:20:17 +00001463/// \brief Retrieve the string representation of the given type as a string
1464/// that has the appropriate lifetime for code completion.
1465///
1466/// This routine provides a fast path where we provide constant strings for
1467/// common type names.
1468static const char *GetCompletionTypeString(QualType T,
1469 ASTContext &Context,
1470 const PrintingPolicy &Policy,
1471 CodeCompletionAllocator &Allocator) {
1472 if (!T.getLocalQualifiers()) {
1473 // Built-in type names are constant strings.
1474 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Argyrios Kyrtzidisbbff3da2012-05-05 04:20:28 +00001475 return BT->getNameAsCString(Policy);
Douglas Gregore5c79d52011-10-18 21:20:17 +00001476
1477 // Anonymous tag types are constant strings.
1478 if (const TagType *TagT = dyn_cast<TagType>(T))
1479 if (TagDecl *Tag = TagT->getDecl())
John McCall5ea95772013-03-09 00:54:27 +00001480 if (!Tag->hasNameForLinkage()) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001481 switch (Tag->getTagKind()) {
1482 case TTK_Struct: return "struct <anonymous>";
Joao Matosdc86f942012-08-31 18:45:21 +00001483 case TTK_Interface: return "__interface <anonymous>";
1484 case TTK_Class: return "class <anonymous>";
Douglas Gregore5c79d52011-10-18 21:20:17 +00001485 case TTK_Union: return "union <anonymous>";
1486 case TTK_Enum: return "enum <anonymous>";
1487 }
1488 }
1489 }
1490
1491 // Slow path: format the type as a string.
1492 std::string Result;
1493 T.getAsStringInternal(Result, Policy);
1494 return Allocator.CopyString(Result);
1495}
1496
Douglas Gregord8c61782012-02-15 15:34:24 +00001497/// \brief Add a completion for "this", if we're in a member function.
1498static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1499 QualType ThisTy = S.getCurrentThisType();
1500 if (ThisTy.isNull())
1501 return;
1502
1503 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001504 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregord8c61782012-02-15 15:34:24 +00001505 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1506 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1507 S.Context,
1508 Policy,
1509 Allocator));
1510 Builder.AddTypedTextChunk("this");
Joao Matosdc86f942012-08-31 18:45:21 +00001511 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregord8c61782012-02-15 15:34:24 +00001512}
1513
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001514/// \brief Add language constructs that show up for "ordinary" names.
John McCallfaf5fb42010-08-26 23:41:50 +00001515static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001516 Scope *S,
1517 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001518 ResultBuilder &Results) {
Douglas Gregore5c79d52011-10-18 21:20:17 +00001519 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001520 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregore5c79d52011-10-18 21:20:17 +00001521 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001522
John McCall276321a2010-08-25 06:19:51 +00001523 typedef CodeCompletionResult Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001524 switch (CCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00001525 case Sema::PCC_Namespace:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001527 if (Results.includeCodePatterns()) {
1528 // namespace <identifier> { declarations }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001529 Builder.AddTypedTextChunk("namespace");
1530 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1531 Builder.AddPlaceholderChunk("identifier");
1532 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1533 Builder.AddPlaceholderChunk("declarations");
1534 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1535 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1536 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001537 }
1538
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001539 // namespace identifier = identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001540 Builder.AddTypedTextChunk("namespace");
1541 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1542 Builder.AddPlaceholderChunk("name");
1543 Builder.AddChunk(CodeCompletionString::CK_Equal);
1544 Builder.AddPlaceholderChunk("namespace");
1545 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001546
1547 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001548 Builder.AddTypedTextChunk("using");
1549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1550 Builder.AddTextChunk("namespace");
1551 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1552 Builder.AddPlaceholderChunk("identifier");
1553 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001554
1555 // asm(string-literal)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001556 Builder.AddTypedTextChunk("asm");
1557 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1558 Builder.AddPlaceholderChunk("string-literal");
1559 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1560 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001561
Douglas Gregorf4c33342010-05-28 00:22:41 +00001562 if (Results.includeCodePatterns()) {
1563 // Explicit template instantiation
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001564 Builder.AddTypedTextChunk("template");
1565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566 Builder.AddPlaceholderChunk("declaration");
1567 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001568 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001569 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001570
David Blaikiebbafb8a2012-03-11 07:00:24 +00001571 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001572 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001573
Douglas Gregorf4c33342010-05-28 00:22:41 +00001574 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001575 // Fall through
1576
John McCallfaf5fb42010-08-26 23:41:50 +00001577 case Sema::PCC_Class:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001579 // Using declaration
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001580 Builder.AddTypedTextChunk("using");
1581 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1582 Builder.AddPlaceholderChunk("qualifier");
1583 Builder.AddTextChunk("::");
1584 Builder.AddPlaceholderChunk("name");
1585 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001586
Douglas Gregorf4c33342010-05-28 00:22:41 +00001587 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001588 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001589 Builder.AddTypedTextChunk("using");
1590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1591 Builder.AddTextChunk("typename");
1592 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1593 Builder.AddPlaceholderChunk("qualifier");
1594 Builder.AddTextChunk("::");
1595 Builder.AddPlaceholderChunk("name");
1596 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001597 }
1598
John McCallfaf5fb42010-08-26 23:41:50 +00001599 if (CCC == Sema::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001600 AddTypedefResult(Results);
1601
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001602 // public:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001603 Builder.AddTypedTextChunk("public");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001604 if (Results.includeCodePatterns())
1605 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001607
1608 // protected:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001609 Builder.AddTypedTextChunk("protected");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001610 if (Results.includeCodePatterns())
1611 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001612 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001613
1614 // private:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001615 Builder.AddTypedTextChunk("private");
Douglas Gregor9489cdf2012-04-10 17:56:28 +00001616 if (Results.includeCodePatterns())
1617 Builder.AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001618 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001619 }
1620 }
1621 // Fall through
1622
John McCallfaf5fb42010-08-26 23:41:50 +00001623 case Sema::PCC_Template:
1624 case Sema::PCC_MemberTemplate:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001625 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001626 // template < parameters >
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001627 Builder.AddTypedTextChunk("template");
1628 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1629 Builder.AddPlaceholderChunk("parameters");
1630 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1631 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632 }
1633
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1635 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001636 break;
1637
John McCallfaf5fb42010-08-26 23:41:50 +00001638 case Sema::PCC_ObjCInterface:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001639 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1640 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1641 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001642 break;
1643
John McCallfaf5fb42010-08-26 23:41:50 +00001644 case Sema::PCC_ObjCImplementation:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1646 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1647 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001648 break;
1649
John McCallfaf5fb42010-08-26 23:41:50 +00001650 case Sema::PCC_ObjCInstanceVariableList:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001651 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001652 break;
1653
John McCallfaf5fb42010-08-26 23:41:50 +00001654 case Sema::PCC_RecoveryInFunction:
1655 case Sema::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001656 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001657
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1659 SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001660 Builder.AddTypedTextChunk("try");
1661 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1662 Builder.AddPlaceholderChunk("statements");
1663 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1664 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1665 Builder.AddTextChunk("catch");
1666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1667 Builder.AddPlaceholderChunk("declaration");
1668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1669 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1670 Builder.AddPlaceholderChunk("statements");
1671 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1672 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001674 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001675 if (SemaRef.getLangOpts().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001676 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001677
Douglas Gregorf64acca2010-05-25 21:41:55 +00001678 if (Results.includeCodePatterns()) {
1679 // if (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001680 Builder.AddTypedTextChunk("if");
1681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001683 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001684 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001685 Builder.AddPlaceholderChunk("expression");
1686 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1687 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1688 Builder.AddPlaceholderChunk("statements");
1689 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1690 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1691 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001692
Douglas Gregorf64acca2010-05-25 21:41:55 +00001693 // switch (condition) { }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("switch");
1695 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001696 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001697 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001698 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001699 Builder.AddPlaceholderChunk("expression");
1700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1701 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1702 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1703 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001705 }
1706
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001707 // Switch-specific statements.
John McCallaab3e412010-08-25 08:40:02 +00001708 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001709 // case expression:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001710 Builder.AddTypedTextChunk("case");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddPlaceholderChunk("expression");
1713 Builder.AddChunk(CodeCompletionString::CK_Colon);
1714 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001715
1716 // default:
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001717 Builder.AddTypedTextChunk("default");
1718 Builder.AddChunk(CodeCompletionString::CK_Colon);
1719 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001720 }
1721
Douglas Gregorf64acca2010-05-25 21:41:55 +00001722 if (Results.includeCodePatterns()) {
1723 /// while (condition) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001724 Builder.AddTypedTextChunk("while");
1725 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001727 Builder.AddPlaceholderChunk("condition");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001728 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001729 Builder.AddPlaceholderChunk("expression");
1730 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1731 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1732 Builder.AddPlaceholderChunk("statements");
1733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1734 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1735 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001736
1737 // do { statements } while ( expression );
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001738 Builder.AddTypedTextChunk("do");
1739 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1740 Builder.AddPlaceholderChunk("statements");
1741 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1742 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1743 Builder.AddTextChunk("while");
1744 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1745 Builder.AddPlaceholderChunk("expression");
1746 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1747 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001748
Douglas Gregorf64acca2010-05-25 21:41:55 +00001749 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001750 Builder.AddTypedTextChunk("for");
1751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001752 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001753 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001754 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001755 Builder.AddPlaceholderChunk("init-expression");
1756 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1757 Builder.AddPlaceholderChunk("condition");
1758 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1759 Builder.AddPlaceholderChunk("inc-expression");
1760 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1761 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1762 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1763 Builder.AddPlaceholderChunk("statements");
1764 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1765 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1766 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001767 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001768
1769 if (S->getContinueParent()) {
1770 // continue ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001771 Builder.AddTypedTextChunk("continue");
1772 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001773 }
1774
1775 if (S->getBreakParent()) {
1776 // break ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001777 Builder.AddTypedTextChunk("break");
1778 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001779 }
1780
1781 // "return expression ;" or "return ;", depending on whether we
1782 // know the function is void or not.
1783 bool isVoid = false;
1784 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001785 isVoid = Function->getReturnType()->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001786 else if (ObjCMethodDecl *Method
1787 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00001788 isVoid = Method->getReturnType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001789 else if (SemaRef.getCurBlock() &&
1790 !SemaRef.getCurBlock()->ReturnType.isNull())
1791 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001792 Builder.AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001793 if (!isVoid) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1795 Builder.AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001796 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001797 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001798
Douglas Gregorf4c33342010-05-28 00:22:41 +00001799 // goto identifier ;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001800 Builder.AddTypedTextChunk("goto");
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("label");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001804
Douglas Gregorf4c33342010-05-28 00:22:41 +00001805 // Using directives
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001806 Builder.AddTypedTextChunk("using");
1807 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1808 Builder.AddTextChunk("namespace");
1809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1810 Builder.AddPlaceholderChunk("identifier");
1811 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001812 }
1813
1814 // Fall through (for statement expressions).
John McCallfaf5fb42010-08-26 23:41:50 +00001815 case Sema::PCC_ForInit:
1816 case Sema::PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001818 // Fall through: conditions and statements can have expressions.
1819
Douglas Gregor5e35d592010-09-14 23:59:36 +00001820 case Sema::PCC_ParenthesizedExpression:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001822 CCC == Sema::PCC_ParenthesizedExpression) {
1823 // (__bridge <type>)<expression>
1824 Builder.AddTypedTextChunk("__bridge");
1825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1826 Builder.AddPlaceholderChunk("type");
1827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1828 Builder.AddPlaceholderChunk("expression");
1829 Results.AddResult(Result(Builder.TakeString()));
1830
1831 // (__bridge_transfer <Objective-C type>)<expression>
1832 Builder.AddTypedTextChunk("__bridge_transfer");
1833 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1834 Builder.AddPlaceholderChunk("Objective-C type");
1835 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1836 Builder.AddPlaceholderChunk("expression");
1837 Results.AddResult(Result(Builder.TakeString()));
1838
1839 // (__bridge_retained <CF type>)<expression>
1840 Builder.AddTypedTextChunk("__bridge_retained");
1841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1842 Builder.AddPlaceholderChunk("CF type");
1843 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1844 Builder.AddPlaceholderChunk("expression");
1845 Results.AddResult(Result(Builder.TakeString()));
1846 }
1847 // Fall through
1848
John McCallfaf5fb42010-08-26 23:41:50 +00001849 case Sema::PCC_Expression: {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001850 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001851 // 'this', if we're in a non-static member function.
Douglas Gregord8c61782012-02-15 15:34:24 +00001852 addThisCompletion(SemaRef, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001853
Douglas Gregore5c79d52011-10-18 21:20:17 +00001854 // true
1855 Builder.AddResultTypeChunk("bool");
1856 Builder.AddTypedTextChunk("true");
1857 Results.AddResult(Result(Builder.TakeString()));
1858
1859 // false
1860 Builder.AddResultTypeChunk("bool");
1861 Builder.AddTypedTextChunk("false");
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001863
David Blaikiebbafb8a2012-03-11 07:00:24 +00001864 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001865 // dynamic_cast < type-id > ( expression )
1866 Builder.AddTypedTextChunk("dynamic_cast");
1867 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1868 Builder.AddPlaceholderChunk("type");
1869 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1870 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1871 Builder.AddPlaceholderChunk("expression");
1872 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1873 Results.AddResult(Result(Builder.TakeString()));
1874 }
Douglas Gregorf4c33342010-05-28 00:22:41 +00001875
1876 // static_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001877 Builder.AddTypedTextChunk("static_cast");
1878 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1879 Builder.AddPlaceholderChunk("type");
1880 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1882 Builder.AddPlaceholderChunk("expression");
1883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1884 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001885
Douglas Gregorf4c33342010-05-28 00:22:41 +00001886 // reinterpret_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001887 Builder.AddTypedTextChunk("reinterpret_cast");
1888 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1889 Builder.AddPlaceholderChunk("type");
1890 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1891 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1892 Builder.AddPlaceholderChunk("expression");
1893 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1894 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001895
Douglas Gregorf4c33342010-05-28 00:22:41 +00001896 // const_cast < type-id > ( expression )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001897 Builder.AddTypedTextChunk("const_cast");
1898 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1899 Builder.AddPlaceholderChunk("type");
1900 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1902 Builder.AddPlaceholderChunk("expression");
1903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1904 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001905
David Blaikiebbafb8a2012-03-11 07:00:24 +00001906 if (SemaRef.getLangOpts().RTTI) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001907 // typeid ( expression-or-type )
Douglas Gregore5c79d52011-10-18 21:20:17 +00001908 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001909 Builder.AddTypedTextChunk("typeid");
1910 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1911 Builder.AddPlaceholderChunk("expression-or-type");
1912 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1913 Results.AddResult(Result(Builder.TakeString()));
1914 }
1915
Douglas Gregorf4c33342010-05-28 00:22:41 +00001916 // new T ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001917 Builder.AddTypedTextChunk("new");
1918 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1919 Builder.AddPlaceholderChunk("type");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1921 Builder.AddPlaceholderChunk("expressions");
1922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1923 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001924
Douglas Gregorf4c33342010-05-28 00:22:41 +00001925 // new T [ ] ( ... )
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001926 Builder.AddTypedTextChunk("new");
1927 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1928 Builder.AddPlaceholderChunk("type");
1929 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1930 Builder.AddPlaceholderChunk("size");
1931 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1932 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1933 Builder.AddPlaceholderChunk("expressions");
1934 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1935 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001936
Douglas Gregorf4c33342010-05-28 00:22:41 +00001937 // delete expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001938 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001939 Builder.AddTypedTextChunk("delete");
1940 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1941 Builder.AddPlaceholderChunk("expression");
1942 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001943
Douglas Gregorf4c33342010-05-28 00:22:41 +00001944 // delete [] expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001945 Builder.AddResultTypeChunk("void");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001946 Builder.AddTypedTextChunk("delete");
1947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1948 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1949 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1950 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1951 Builder.AddPlaceholderChunk("expression");
1952 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001953
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 if (SemaRef.getLangOpts().CXXExceptions) {
Douglas Gregorc05f6572011-04-12 02:47:21 +00001955 // throw expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001956 Builder.AddResultTypeChunk("void");
Douglas Gregorc05f6572011-04-12 02:47:21 +00001957 Builder.AddTypedTextChunk("throw");
1958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1959 Builder.AddPlaceholderChunk("expression");
1960 Results.AddResult(Result(Builder.TakeString()));
1961 }
Douglas Gregor4205fef2011-10-18 16:29:03 +00001962
Douglas Gregora2db7932010-05-26 22:00:08 +00001963 // FIXME: Rethrow?
Douglas Gregor4205fef2011-10-18 16:29:03 +00001964
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001965 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregor4205fef2011-10-18 16:29:03 +00001966 // nullptr
Douglas Gregore5c79d52011-10-18 21:20:17 +00001967 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001968 Builder.AddTypedTextChunk("nullptr");
1969 Results.AddResult(Result(Builder.TakeString()));
1970
1971 // alignof
Douglas Gregore5c79d52011-10-18 21:20:17 +00001972 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001973 Builder.AddTypedTextChunk("alignof");
1974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1975 Builder.AddPlaceholderChunk("type");
1976 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1977 Results.AddResult(Result(Builder.TakeString()));
1978
1979 // noexcept
Douglas Gregore5c79d52011-10-18 21:20:17 +00001980 Builder.AddResultTypeChunk("bool");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001981 Builder.AddTypedTextChunk("noexcept");
1982 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1983 Builder.AddPlaceholderChunk("expression");
1984 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1985 Results.AddResult(Result(Builder.TakeString()));
1986
1987 // sizeof... expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00001988 Builder.AddResultTypeChunk("size_t");
Douglas Gregor4205fef2011-10-18 16:29:03 +00001989 Builder.AddTypedTextChunk("sizeof...");
1990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1991 Builder.AddPlaceholderChunk("parameter-pack");
1992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1993 Results.AddResult(Result(Builder.TakeString()));
1994 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001995 }
1996
David Blaikiebbafb8a2012-03-11 07:00:24 +00001997 if (SemaRef.getLangOpts().ObjC1) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001998 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001999 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2000 // The interface can be NULL.
2001 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregore5c79d52011-10-18 21:20:17 +00002002 if (ID->getSuperClass()) {
2003 std::string SuperType;
2004 SuperType = ID->getSuperClass()->getNameAsString();
2005 if (Method->isInstanceMethod())
2006 SuperType += " *";
2007
2008 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2009 Builder.AddTypedTextChunk("super");
2010 Results.AddResult(Result(Builder.TakeString()));
2011 }
Ted Kremenek305a0a72010-05-31 21:43:10 +00002012 }
2013
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002014 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002015 }
2016
Jordan Rose58d54722012-06-30 21:33:57 +00002017 if (SemaRef.getLangOpts().C11) {
2018 // _Alignof
2019 Builder.AddResultTypeChunk("size_t");
2020 if (SemaRef.getASTContext().Idents.get("alignof").hasMacroDefinition())
2021 Builder.AddTypedTextChunk("alignof");
2022 else
2023 Builder.AddTypedTextChunk("_Alignof");
2024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2025 Builder.AddPlaceholderChunk("type");
2026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2027 Results.AddResult(Result(Builder.TakeString()));
2028 }
2029
Douglas Gregorf4c33342010-05-28 00:22:41 +00002030 // sizeof expression
Douglas Gregore5c79d52011-10-18 21:20:17 +00002031 Builder.AddResultTypeChunk("size_t");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002032 Builder.AddTypedTextChunk("sizeof");
2033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2034 Builder.AddPlaceholderChunk("expression-or-type");
2035 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002037 break;
2038 }
Douglas Gregor99fa2642010-08-24 01:06:58 +00002039
John McCallfaf5fb42010-08-26 23:41:50 +00002040 case Sema::PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00002041 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor99fa2642010-08-24 01:06:58 +00002042 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002043 }
2044
David Blaikiebbafb8a2012-03-11 07:00:24 +00002045 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2046 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002047
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregor78a21012010-01-14 16:01:26 +00002049 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002050}
2051
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002052/// \brief If the given declaration has an associated type, add it as a result
2053/// type chunk.
2054static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002055 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002056 const NamedDecl *ND,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002057 CodeCompletionBuilder &Result) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002058 if (!ND)
2059 return;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002060
2061 // Skip constructors and conversion functions, which have their return types
2062 // built into their names.
2063 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2064 return;
2065
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002066 // Determine the type of the declaration (if it has a type).
Alp Tokera2794f92014-01-22 07:29:52 +00002067 QualType T;
2068 if (const FunctionDecl *Function = ND->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00002069 T = Function->getReturnType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002070 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Alp Toker314cc812014-01-25 16:55:45 +00002071 T = Method->getReturnType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002072 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002073 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2074 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2075 /* Do nothing: ignore unresolved using declarations*/
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002076 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002077 T = Value->getType();
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002078 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002079 T = Property->getType();
2080
2081 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2082 return;
2083
Douglas Gregor75acd922011-09-27 23:30:47 +00002084 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregor304f9b02011-02-01 21:15:40 +00002085 Result.getAllocator()));
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002086}
2087
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002088static void MaybeAddSentinel(ASTContext &Context,
2089 const NamedDecl *FunctionOrMethod,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002090 CodeCompletionBuilder &Result) {
Douglas Gregordbb71db2010-08-23 23:51:41 +00002091 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2092 if (Sentinel->getSentinel() == 0) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002093 if (Context.getLangOpts().ObjC1 &&
Douglas Gregordbb71db2010-08-23 23:51:41 +00002094 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002095 Result.AddTextChunk(", nil");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002096 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002097 Result.AddTextChunk(", NULL");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002098 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002099 Result.AddTextChunk(", (void*)0");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002100 }
2101}
2102
Douglas Gregor8f08d742011-07-30 07:55:26 +00002103static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2104 std::string Result;
2105 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002106 Result += "in ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002107 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002108 Result += "inout ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002109 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002110 Result += "out ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002111 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002112 Result += "bycopy ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002113 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002114 Result += "byref ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002115 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor407d1f92011-11-09 02:13:45 +00002116 Result += "oneway ";
Douglas Gregor8f08d742011-07-30 07:55:26 +00002117 return Result;
2118}
2119
Douglas Gregore90dd002010-08-24 16:15:59 +00002120static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002121 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002122 const ParmVarDecl *Param,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002123 bool SuppressName = false,
2124 bool SuppressBlock = false) {
Douglas Gregore90dd002010-08-24 16:15:59 +00002125 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2126 if (Param->getType()->isDependentType() ||
2127 !Param->getType()->isBlockPointerType()) {
2128 // The argument for a dependent or non-block parameter is a placeholder
2129 // containing that parameter's type.
2130 std::string Result;
2131
Douglas Gregor981a0c42010-08-29 19:47:46 +00002132 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002133 Result = Param->getIdentifier()->getName();
2134
John McCall31168b02011-06-15 23:02:42 +00002135 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002136
2137 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002138 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2139 + Result + ")";
Douglas Gregor981a0c42010-08-29 19:47:46 +00002140 if (Param->getIdentifier() && !SuppressName)
Douglas Gregore90dd002010-08-24 16:15:59 +00002141 Result += Param->getIdentifier()->getName();
2142 }
2143 return Result;
2144 }
2145
2146 // The argument for a block pointer parameter is a block literal with
2147 // the appropriate type.
David Blaikie6adc78e2013-02-18 22:06:02 +00002148 FunctionTypeLoc Block;
2149 FunctionProtoTypeLoc BlockProto;
Douglas Gregore90dd002010-08-24 16:15:59 +00002150 TypeLoc TL;
2151 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2152 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2153 while (true) {
2154 // Look through typedefs.
Douglas Gregord793e7c2011-10-18 04:23:19 +00002155 if (!SuppressBlock) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002156 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2157 if (TypeSourceInfo *InnerTSInfo =
2158 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002159 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2160 continue;
2161 }
2162 }
2163
2164 // Look through qualified types
David Blaikie6adc78e2013-02-18 22:06:02 +00002165 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2166 TL = QualifiedTL.getUnqualifiedLoc();
Douglas Gregore90dd002010-08-24 16:15:59 +00002167 continue;
2168 }
2169 }
2170
Douglas Gregore90dd002010-08-24 16:15:59 +00002171 // Try to get the function prototype behind the block pointer type,
2172 // then we're done.
David Blaikie6adc78e2013-02-18 22:06:02 +00002173 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2174 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2175 Block = TL.getAs<FunctionTypeLoc>();
2176 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregore90dd002010-08-24 16:15:59 +00002177 }
2178 break;
2179 }
2180 }
2181
2182 if (!Block) {
2183 // We were unable to find a FunctionProtoTypeLoc with parameter names
2184 // for the block; just use the parameter type as a placeholder.
2185 std::string Result;
Douglas Gregord793e7c2011-10-18 04:23:19 +00002186 if (!ObjCMethodParam && Param->getIdentifier())
2187 Result = Param->getIdentifier()->getName();
2188
John McCall31168b02011-06-15 23:02:42 +00002189 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregore90dd002010-08-24 16:15:59 +00002190
2191 if (ObjCMethodParam) {
Douglas Gregor8f08d742011-07-30 07:55:26 +00002192 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2193 + Result + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002194 if (Param->getIdentifier())
2195 Result += Param->getIdentifier()->getName();
2196 }
2197
2198 return Result;
2199 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002200
Douglas Gregore90dd002010-08-24 16:15:59 +00002201 // We have the function prototype behind the block pointer type, as it was
2202 // written in the source.
Douglas Gregor67da50e2010-09-08 22:47:51 +00002203 std::string Result;
Alp Toker314cc812014-01-25 16:55:45 +00002204 QualType ResultType = Block.getTypePtr()->getReturnType();
Douglas Gregord793e7c2011-10-18 04:23:19 +00002205 if (!ResultType->isVoidType() || SuppressBlock)
John McCall31168b02011-06-15 23:02:42 +00002206 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregord793e7c2011-10-18 04:23:19 +00002207
2208 // Format the parameter list.
2209 std::string Params;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002210 if (!BlockProto || Block.getNumParams() == 0) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002211 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002212 Params = "(...)";
Douglas Gregoraf25cfa2010-10-02 23:49:58 +00002213 else
Douglas Gregord793e7c2011-10-18 04:23:19 +00002214 Params = "(void)";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002215 } else {
Douglas Gregord793e7c2011-10-18 04:23:19 +00002216 Params += "(";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002217 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
Douglas Gregor67da50e2010-09-08 22:47:51 +00002218 if (I)
Douglas Gregord793e7c2011-10-18 04:23:19 +00002219 Params += ", ";
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002220 Params += FormatFunctionParameter(Context, Policy, Block.getParam(I),
2221 /*SuppressName=*/false,
Douglas Gregord793e7c2011-10-18 04:23:19 +00002222 /*SuppressBlock=*/true);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002223
David Blaikie6adc78e2013-02-18 22:06:02 +00002224 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Douglas Gregord793e7c2011-10-18 04:23:19 +00002225 Params += ", ...";
Douglas Gregor67da50e2010-09-08 22:47:51 +00002226 }
Douglas Gregord793e7c2011-10-18 04:23:19 +00002227 Params += ")";
Douglas Gregor400f5972010-08-31 05:13:43 +00002228 }
Douglas Gregor67da50e2010-09-08 22:47:51 +00002229
Douglas Gregord793e7c2011-10-18 04:23:19 +00002230 if (SuppressBlock) {
2231 // Format as a parameter.
2232 Result = Result + " (^";
2233 if (Param->getIdentifier())
2234 Result += Param->getIdentifier()->getName();
2235 Result += ")";
2236 Result += Params;
2237 } else {
2238 // Format as a block literal argument.
2239 Result = '^' + Result;
2240 Result += Params;
2241
2242 if (Param->getIdentifier())
2243 Result += Param->getIdentifier()->getName();
2244 }
2245
Douglas Gregore90dd002010-08-24 16:15:59 +00002246 return Result;
2247}
2248
Douglas Gregor3545ff42009-09-21 16:56:56 +00002249/// \brief Add function parameter chunks to the given code completion string.
2250static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002251 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002252 const FunctionDecl *Function,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002253 CodeCompletionBuilder &Result,
2254 unsigned Start = 0,
2255 bool InOptional = false) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002256 bool FirstParameter = true;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002257
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002258 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002259 const ParmVarDecl *Param = Function->getParamDecl(P);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002260
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002261 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002262 // When we see an optional default argument, put that argument and
2263 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002264 CodeCompletionBuilder Opt(Result.getAllocator(),
2265 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002266 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002267 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002268 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002269 Result.AddOptionalChunk(Opt.TakeString());
2270 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002271 }
2272
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002273 if (FirstParameter)
2274 FirstParameter = false;
2275 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002276 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002277
2278 InOptional = false;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002279
2280 // Format the placeholder string.
Douglas Gregor75acd922011-09-27 23:30:47 +00002281 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2282 Param);
Douglas Gregore90dd002010-08-24 16:15:59 +00002283
Douglas Gregor400f5972010-08-31 05:13:43 +00002284 if (Function->isVariadic() && P == N - 1)
2285 PlaceholderStr += ", ...";
2286
Douglas Gregor3545ff42009-09-21 16:56:56 +00002287 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002288 Result.AddPlaceholderChunk(
2289 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002290 }
Douglas Gregorba449032009-09-22 21:42:17 +00002291
2292 if (const FunctionProtoType *Proto
2293 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregordbb71db2010-08-23 23:51:41 +00002294 if (Proto->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002295 if (Proto->getNumParams() == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002296 Result.AddPlaceholderChunk("...");
Douglas Gregordbb71db2010-08-23 23:51:41 +00002297
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002298 MaybeAddSentinel(Context, Function, Result);
Douglas Gregordbb71db2010-08-23 23:51:41 +00002299 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002300}
2301
2302/// \brief Add template parameter chunks to the given code completion string.
2303static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00002304 const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002305 const TemplateDecl *Template,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002306 CodeCompletionBuilder &Result,
2307 unsigned MaxParameters = 0,
2308 unsigned Start = 0,
2309 bool InDefaultArg = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002310 bool FirstParameter = true;
Richard Smith6eece292015-01-15 02:27:20 +00002311
2312 // Prefer to take the template parameter names from the first declaration of
2313 // the template.
2314 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2315
Douglas Gregor3545ff42009-09-21 16:56:56 +00002316 TemplateParameterList *Params = Template->getTemplateParameters();
2317 TemplateParameterList::iterator PEnd = Params->end();
2318 if (MaxParameters)
2319 PEnd = Params->begin() + MaxParameters;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002320 for (TemplateParameterList::iterator P = Params->begin() + Start;
2321 P != PEnd; ++P) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002322 bool HasDefaultArg = false;
2323 std::string PlaceholderStr;
2324 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2325 if (TTP->wasDeclaredWithTypename())
2326 PlaceholderStr = "typename";
2327 else
2328 PlaceholderStr = "class";
2329
2330 if (TTP->getIdentifier()) {
2331 PlaceholderStr += ' ';
2332 PlaceholderStr += TTP->getIdentifier()->getName();
2333 }
2334
2335 HasDefaultArg = TTP->hasDefaultArgument();
2336 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002337 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002338 if (NTTP->getIdentifier())
2339 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCall31168b02011-06-15 23:02:42 +00002340 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002341 HasDefaultArg = NTTP->hasDefaultArgument();
2342 } else {
2343 assert(isa<TemplateTemplateParmDecl>(*P));
2344 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2345
2346 // Since putting the template argument list into the placeholder would
2347 // be very, very long, we just use an abbreviation.
2348 PlaceholderStr = "template<...> class";
2349 if (TTP->getIdentifier()) {
2350 PlaceholderStr += ' ';
2351 PlaceholderStr += TTP->getIdentifier()->getName();
2352 }
2353
2354 HasDefaultArg = TTP->hasDefaultArgument();
2355 }
2356
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002357 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002358 // When we see an optional default argument, put that argument and
2359 // the remaining default arguments into a new, optional string.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002360 CodeCompletionBuilder Opt(Result.getAllocator(),
2361 Result.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002362 if (!FirstParameter)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002363 Opt.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor75acd922011-09-27 23:30:47 +00002364 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002365 P - Params->begin(), true);
2366 Result.AddOptionalChunk(Opt.TakeString());
2367 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002368 }
2369
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002370 InDefaultArg = false;
2371
Douglas Gregor3545ff42009-09-21 16:56:56 +00002372 if (FirstParameter)
2373 FirstParameter = false;
2374 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002375 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002376
2377 // Add the placeholder string.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002378 Result.AddPlaceholderChunk(
2379 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002380 }
2381}
2382
Douglas Gregorf2510672009-09-21 19:57:38 +00002383/// \brief Add a qualifier to the given code-completion string, if the
2384/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00002385static void
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002386AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregor0f622362009-12-11 18:44:16 +00002387 NestedNameSpecifier *Qualifier,
2388 bool QualifierIsInformative,
Douglas Gregor75acd922011-09-27 23:30:47 +00002389 ASTContext &Context,
2390 const PrintingPolicy &Policy) {
Douglas Gregorf2510672009-09-21 19:57:38 +00002391 if (!Qualifier)
2392 return;
2393
2394 std::string PrintedNNS;
2395 {
2396 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor75acd922011-09-27 23:30:47 +00002397 Qualifier->print(OS, Policy);
Douglas Gregorf2510672009-09-21 19:57:38 +00002398 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00002399 if (QualifierIsInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002400 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor5bf52692009-09-22 23:15:58 +00002401 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002402 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorf2510672009-09-21 19:57:38 +00002403}
2404
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002405static void
2406AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002407 const FunctionDecl *Function) {
Douglas Gregor0f622362009-12-11 18:44:16 +00002408 const FunctionProtoType *Proto
2409 = Function->getType()->getAs<FunctionProtoType>();
2410 if (!Proto || !Proto->getTypeQuals())
2411 return;
2412
Douglas Gregor304f9b02011-02-01 21:15:40 +00002413 // FIXME: Add ref-qualifier!
2414
2415 // Handle single qualifiers without copying
2416 if (Proto->getTypeQuals() == Qualifiers::Const) {
2417 Result.AddInformativeChunk(" const");
2418 return;
2419 }
2420
2421 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2422 Result.AddInformativeChunk(" volatile");
2423 return;
2424 }
2425
2426 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2427 Result.AddInformativeChunk(" restrict");
2428 return;
2429 }
2430
2431 // Handle multiple qualifiers.
Douglas Gregor0f622362009-12-11 18:44:16 +00002432 std::string QualsStr;
David Blaikief5697e52012-08-10 00:55:35 +00002433 if (Proto->isConst())
Douglas Gregor0f622362009-12-11 18:44:16 +00002434 QualsStr += " const";
David Blaikief5697e52012-08-10 00:55:35 +00002435 if (Proto->isVolatile())
Douglas Gregor0f622362009-12-11 18:44:16 +00002436 QualsStr += " volatile";
David Blaikief5697e52012-08-10 00:55:35 +00002437 if (Proto->isRestrict())
Douglas Gregor0f622362009-12-11 18:44:16 +00002438 QualsStr += " restrict";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002439 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregor0f622362009-12-11 18:44:16 +00002440}
2441
Douglas Gregor0212fd72010-09-21 16:06:22 +00002442/// \brief Add the name of the given declaration
Douglas Gregor75acd922011-09-27 23:30:47 +00002443static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002444 const NamedDecl *ND,
2445 CodeCompletionBuilder &Result) {
Douglas Gregor0212fd72010-09-21 16:06:22 +00002446 DeclarationName Name = ND->getDeclName();
2447 if (!Name)
2448 return;
2449
2450 switch (Name.getNameKind()) {
Douglas Gregor304f9b02011-02-01 21:15:40 +00002451 case DeclarationName::CXXOperatorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002452 const char *OperatorName = nullptr;
Douglas Gregor304f9b02011-02-01 21:15:40 +00002453 switch (Name.getCXXOverloadedOperator()) {
2454 case OO_None:
2455 case OO_Conditional:
2456 case NUM_OVERLOADED_OPERATORS:
2457 OperatorName = "operator";
2458 break;
2459
2460#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2461 case OO_##Name: OperatorName = "operator" Spelling; break;
2462#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2463#include "clang/Basic/OperatorKinds.def"
2464
2465 case OO_New: OperatorName = "operator new"; break;
2466 case OO_Delete: OperatorName = "operator delete"; break;
2467 case OO_Array_New: OperatorName = "operator new[]"; break;
2468 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2469 case OO_Call: OperatorName = "operator()"; break;
2470 case OO_Subscript: OperatorName = "operator[]"; break;
2471 }
2472 Result.AddTypedTextChunk(OperatorName);
2473 break;
2474 }
2475
Douglas Gregor0212fd72010-09-21 16:06:22 +00002476 case DeclarationName::Identifier:
2477 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor0212fd72010-09-21 16:06:22 +00002478 case DeclarationName::CXXDestructorName:
2479 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002480 Result.AddTypedTextChunk(
2481 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002482 break;
2483
2484 case DeclarationName::CXXUsingDirective:
2485 case DeclarationName::ObjCZeroArgSelector:
2486 case DeclarationName::ObjCOneArgSelector:
2487 case DeclarationName::ObjCMultiArgSelector:
2488 break;
2489
2490 case DeclarationName::CXXConstructorName: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002491 CXXRecordDecl *Record = nullptr;
Douglas Gregor0212fd72010-09-21 16:06:22 +00002492 QualType Ty = Name.getCXXNameType();
2493 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2494 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2495 else if (const InjectedClassNameType *InjectedTy
2496 = Ty->getAs<InjectedClassNameType>())
2497 Record = InjectedTy->getDecl();
2498 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002499 Result.AddTypedTextChunk(
2500 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002501 break;
2502 }
2503
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002504 Result.AddTypedTextChunk(
2505 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor0212fd72010-09-21 16:06:22 +00002506 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002507 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Douglas Gregor75acd922011-09-27 23:30:47 +00002508 AddTemplateParameterChunks(Context, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002509 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002510 }
2511 break;
2512 }
2513 }
2514}
2515
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002516CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002517 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002518 CodeCompletionTUInfo &CCTUInfo,
2519 bool IncludeBriefComments) {
2520 return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo,
2521 IncludeBriefComments);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002522}
2523
Douglas Gregor3545ff42009-09-21 16:56:56 +00002524/// \brief If possible, create a new code completion string for the given
2525/// result.
2526///
2527/// \returns Either a new, heap-allocated code completion string describing
2528/// how to use this result, or NULL to indicate that the string or name of the
2529/// result is all that is needed.
2530CodeCompletionString *
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002531CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2532 Preprocessor &PP,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002533 CodeCompletionAllocator &Allocator,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002534 CodeCompletionTUInfo &CCTUInfo,
2535 bool IncludeBriefComments) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002536 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002537
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002538 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002539 if (Kind == RK_Pattern) {
2540 Pattern->Priority = Priority;
2541 Pattern->Availability = Availability;
Douglas Gregor78254c82012-03-27 23:34:16 +00002542
2543 if (Declaration) {
2544 Result.addParentContext(Declaration->getDeclContext());
Douglas Gregor78254c82012-03-27 23:34:16 +00002545 Pattern->ParentName = Result.getParentName();
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002546 // Provide code completion comment for self.GetterName where
2547 // GetterName is the getter method for a property with name
2548 // different from the property name (declared via a property
2549 // getter attribute.
2550 const NamedDecl *ND = Declaration;
2551 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2552 if (M->isPropertyAccessor())
2553 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2554 if (PDecl->getGetterName() == M->getSelector() &&
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002555 PDecl->getIdentifier() != M->getIdentifier()) {
2556 if (const RawComment *RC =
2557 Ctx.getRawCommentForAnyRedecl(M)) {
Fariborz Jahanian1fcf4922013-03-22 17:55:27 +00002558 Result.addBriefComment(RC->getBriefText(Ctx));
2559 Pattern->BriefComment = Result.getBriefComment();
2560 }
Fariborz Jahanianbe8bc672013-03-23 01:10:45 +00002561 else if (const RawComment *RC =
2562 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2563 Result.addBriefComment(RC->getBriefText(Ctx));
2564 Pattern->BriefComment = Result.getBriefComment();
2565 }
2566 }
Douglas Gregor78254c82012-03-27 23:34:16 +00002567 }
2568
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002569 return Pattern;
2570 }
Douglas Gregorf09935f2009-12-01 05:55:20 +00002571
Douglas Gregorf09935f2009-12-01 05:55:20 +00002572 if (Kind == RK_Keyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002573 Result.AddTypedTextChunk(Keyword);
2574 return Result.TakeString();
Douglas Gregorf09935f2009-12-01 05:55:20 +00002575 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002576
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002577 if (Kind == RK_Macro) {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002578 const MacroDirective *MD = PP.getMacroDirectiveHistory(Macro);
2579 assert(MD && "Not a macro?");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002580 const MacroInfo *MI = MD->getMacroInfo();
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002581 assert((!MD->isDefined() || MI) && "missing MacroInfo for define");
Douglas Gregorf09935f2009-12-01 05:55:20 +00002582
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002583 Result.AddTypedTextChunk(
2584 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregorf09935f2009-12-01 05:55:20 +00002585
Ben Langmuirc28ce3a2014-09-30 20:00:18 +00002586 if (!MI || !MI->isFunctionLike())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002587 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002588
2589 // Format a function-like macro with placeholders for the arguments.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002590 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor0c505312011-07-30 08:17:44 +00002591 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002592
2593 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2594 if (MI->isC99Varargs()) {
2595 --AEnd;
2596
2597 if (A == AEnd) {
2598 Result.AddPlaceholderChunk("...");
2599 }
Douglas Gregor0c505312011-07-30 08:17:44 +00002600 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002601
Douglas Gregor0c505312011-07-30 08:17:44 +00002602 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002603 if (A != MI->arg_begin())
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002604 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregor3aa55262012-01-21 00:43:38 +00002605
2606 if (MI->isVariadic() && (A+1) == AEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002607 SmallString<32> Arg = (*A)->getName();
Douglas Gregor3aa55262012-01-21 00:43:38 +00002608 if (MI->isC99Varargs())
2609 Arg += ", ...";
2610 else
2611 Arg += "...";
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002612 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3aa55262012-01-21 00:43:38 +00002613 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002614 }
Douglas Gregor3aa55262012-01-21 00:43:38 +00002615
2616 // Non-variadic macros are simple.
2617 Result.AddPlaceholderChunk(
2618 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor0c505312011-07-30 08:17:44 +00002619 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002620 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002621 return Result.TakeString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002622 }
2623
Douglas Gregorf64acca2010-05-25 21:41:55 +00002624 assert(Kind == RK_Declaration && "Missed a result kind?");
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002625 const NamedDecl *ND = Declaration;
Douglas Gregor78254c82012-03-27 23:34:16 +00002626 Result.addParentContext(ND->getDeclContext());
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002627
2628 if (IncludeBriefComments) {
2629 // Add documentation comment, if it exists.
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +00002630 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002631 Result.addBriefComment(RC->getBriefText(Ctx));
Fariborz Jahanian15a0b552013-02-28 17:47:14 +00002632 }
2633 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2634 if (OMD->isPropertyAccessor())
2635 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2636 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2637 Result.addBriefComment(RC->getBriefText(Ctx));
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002638 }
2639
Douglas Gregor9eb77012009-11-07 00:00:49 +00002640 if (StartsNestedNameSpecifier) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002641 Result.AddTypedTextChunk(
2642 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002643 Result.AddTextChunk("::");
2644 return Result.TakeString();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002645 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002646
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002647 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2648 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002649
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002650 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002651
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002652 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002653 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002654 Ctx, Policy);
2655 AddTypedNameChunk(Ctx, Policy, ND, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002656 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002657 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002658 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002659 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002660 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002661 }
2662
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002663 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002664 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002665 Ctx, Policy);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002666 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002667 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor0212fd72010-09-21 16:06:22 +00002668
Douglas Gregor3545ff42009-09-21 16:56:56 +00002669 // Figure out which template parameters are deduced (or have default
2670 // arguments).
Benjamin Kramere0513cb2012-01-30 16:17:39 +00002671 llvm::SmallBitVector Deduced;
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002672 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002673 unsigned LastDeducibleArgument;
2674 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2675 --LastDeducibleArgument) {
2676 if (!Deduced[LastDeducibleArgument - 1]) {
2677 // C++0x: Figure out if the template argument has a default. If so,
2678 // the user doesn't need to type this argument.
2679 // FIXME: We need to abstract template parameters better!
2680 bool HasDefaultArg = false;
2681 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002682 LastDeducibleArgument - 1);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002683 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2684 HasDefaultArg = TTP->hasDefaultArgument();
2685 else if (NonTypeTemplateParmDecl *NTTP
2686 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2687 HasDefaultArg = NTTP->hasDefaultArgument();
2688 else {
2689 assert(isa<TemplateTemplateParmDecl>(Param));
2690 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00002691 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002692 }
2693
2694 if (!HasDefaultArg)
2695 break;
2696 }
2697 }
2698
2699 if (LastDeducibleArgument) {
2700 // Some of the function template arguments cannot be deduced from a
2701 // function call, so we introduce an explicit template argument list
2702 // containing all of the arguments up to the first deducible argument.
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002703 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002704 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor3545ff42009-09-21 16:56:56 +00002705 LastDeducibleArgument);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002706 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002707 }
2708
2709 // Add the function parameters
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002710 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002711 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002712 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor0f622362009-12-11 18:44:16 +00002713 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002714 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002715 }
2716
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002717 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00002718 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002719 Ctx, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002720 Result.AddTypedTextChunk(
2721 Result.getAllocator().CopyString(Template->getNameAsString()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002722 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002723 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002724 Result.AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002725 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002726 }
2727
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002728 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00002729 Selector Sel = Method->getSelector();
2730 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002731 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002732 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002733 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002734 }
2735
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00002736 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregor1b605f72009-11-19 01:08:35 +00002737 SelName += ':';
2738 if (StartParameter == 0)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002739 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002740 else {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002741 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregor1b605f72009-11-19 01:08:35 +00002742
2743 // If there is only one parameter, and we're past it, add an empty
2744 // typed-text chunk since there is nothing to type.
2745 if (Method->param_size() == 1)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002746 Result.AddTypedTextChunk("");
Douglas Gregor1b605f72009-11-19 01:08:35 +00002747 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00002748 unsigned Idx = 0;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00002749 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2750 PEnd = Method->param_end();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002751 P != PEnd; (void)++P, ++Idx) {
2752 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00002753 std::string Keyword;
2754 if (Idx > StartParameter)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002755 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002756 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramer632500c2011-07-26 16:59:25 +00002757 Keyword += II->getName();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002758 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00002759 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002760 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002761 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002762 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002763 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00002764
2765 // If we're before the starting parameter, skip the placeholder.
2766 if (Idx < StartParameter)
2767 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00002768
2769 std::string Arg;
Douglas Gregore90dd002010-08-24 16:15:59 +00002770
2771 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002772 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregore90dd002010-08-24 16:15:59 +00002773 else {
John McCall31168b02011-06-15 23:02:42 +00002774 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor8f08d742011-07-30 07:55:26 +00002775 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2776 + Arg + ")";
Douglas Gregore90dd002010-08-24 16:15:59 +00002777 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregor981a0c42010-08-29 19:47:46 +00002778 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramer632500c2011-07-26 16:59:25 +00002779 Arg += II->getName();
Douglas Gregore90dd002010-08-24 16:15:59 +00002780 }
2781
Douglas Gregor400f5972010-08-31 05:13:43 +00002782 if (Method->isVariadic() && (P + 1) == PEnd)
2783 Arg += ", ...";
2784
Douglas Gregor95887f92010-07-08 23:20:03 +00002785 if (DeclaringEntity)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002786 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor95887f92010-07-08 23:20:03 +00002787 else if (AllParametersAreInformative)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002788 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregorc8537c52009-11-19 07:41:15 +00002789 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002790 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregord3c5d792009-11-17 16:44:22 +00002791 }
2792
Douglas Gregor04c5f972009-12-23 00:21:46 +00002793 if (Method->isVariadic()) {
Douglas Gregor400f5972010-08-31 05:13:43 +00002794 if (Method->param_size() == 0) {
2795 if (DeclaringEntity)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002796 Result.AddTextChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002797 else if (AllParametersAreInformative)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002798 Result.AddInformativeChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002799 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002800 Result.AddPlaceholderChunk(", ...");
Douglas Gregor400f5972010-08-31 05:13:43 +00002801 }
Douglas Gregordbb71db2010-08-23 23:51:41 +00002802
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002803 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor04c5f972009-12-23 00:21:46 +00002804 }
2805
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002806 return Result.TakeString();
Douglas Gregord3c5d792009-11-17 16:44:22 +00002807 }
2808
Douglas Gregorf09935f2009-12-01 05:55:20 +00002809 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002810 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidis8d05ca72012-01-17 02:15:51 +00002811 Ctx, Policy);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002812
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002813 Result.AddTypedTextChunk(
2814 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002815 return Result.TakeString();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002816}
2817
Douglas Gregorf0f51982009-09-23 00:34:09 +00002818CodeCompletionString *
2819CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2820 unsigned CurrentArg,
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002821 Sema &S,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002822 CodeCompletionAllocator &Allocator,
2823 CodeCompletionTUInfo &CCTUInfo) const {
Douglas Gregor75acd922011-09-27 23:30:47 +00002824 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCall31168b02011-06-15 23:02:42 +00002825
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002826 // FIXME: Set priority, availability appropriately.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002827 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002828 FunctionDecl *FDecl = getFunction();
Douglas Gregor75acd922011-09-27 23:30:47 +00002829 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002830 const FunctionProtoType *Proto
2831 = dyn_cast<FunctionProtoType>(getFunctionType());
2832 if (!FDecl && !Proto) {
2833 // Function without a prototype. Just give the return type and a
2834 // highlighted ellipsis.
2835 const FunctionType *FT = getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00002836 Result.AddTextChunk(GetCompletionTypeString(FT->getReturnType(), S.Context,
2837 Policy, Result.getAllocator()));
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002838 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2839 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2840 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002841 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002842 }
2843
2844 if (FDecl)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002845 Result.AddTextChunk(
2846 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002847 else
Alp Toker314cc812014-01-25 16:55:45 +00002848 Result.AddTextChunk(Result.getAllocator().CopyString(
2849 Proto->getReturnType().getAsString(Policy)));
2850
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002851 Result.AddChunk(CodeCompletionString::CK_LeftParen);
Alp Toker9cacbab2014-01-20 20:26:09 +00002852 unsigned NumParams = FDecl ? FDecl->getNumParams() : Proto->getNumParams();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002853 for (unsigned I = 0; I != NumParams; ++I) {
2854 if (I)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002855 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002856
2857 std::string ArgString;
2858 QualType ArgType;
2859
2860 if (FDecl) {
2861 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2862 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2863 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00002864 ArgType = Proto->getParamType(I);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002865 }
2866
John McCall31168b02011-06-15 23:02:42 +00002867 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002868
2869 if (I == CurrentArg)
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002870 Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
2871 Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002872 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002873 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002874 }
2875
2876 if (Proto && Proto->isVariadic()) {
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002877 Result.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002878 if (CurrentArg < NumParams)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002879 Result.AddTextChunk("...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002880 else
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002881 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
Douglas Gregorf0f51982009-09-23 00:34:09 +00002882 }
Benjamin Kramerdb534a42012-03-26 16:57:36 +00002883 Result.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002884
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002885 return Result.TakeString();
Douglas Gregorf0f51982009-09-23 00:34:09 +00002886}
2887
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002888unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002889 const LangOptions &LangOpts,
Douglas Gregor6e240332010-08-16 16:18:59 +00002890 bool PreferredTypeIsPointer) {
2891 unsigned Priority = CCP_Macro;
2892
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002893 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2894 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2895 MacroName.equals("Nil")) {
Douglas Gregor6e240332010-08-16 16:18:59 +00002896 Priority = CCP_Constant;
2897 if (PreferredTypeIsPointer)
2898 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002899 }
2900 // Treat "YES", "NO", "true", and "false" as constants.
2901 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2902 MacroName.equals("true") || MacroName.equals("false"))
2903 Priority = CCP_Constant;
2904 // Treat "bool" as a type.
2905 else if (MacroName.equals("bool"))
2906 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2907
Douglas Gregor6e240332010-08-16 16:18:59 +00002908
2909 return Priority;
2910}
2911
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00002912CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002913 if (!D)
2914 return CXCursor_UnexposedDecl;
2915
2916 switch (D->getKind()) {
2917 case Decl::Enum: return CXCursor_EnumDecl;
2918 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2919 case Decl::Field: return CXCursor_FieldDecl;
2920 case Decl::Function:
2921 return CXCursor_FunctionDecl;
2922 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2923 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002924 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002925
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002926 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002927 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2928 case Decl::ObjCMethod:
2929 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2930 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2931 case Decl::CXXMethod: return CXCursor_CXXMethod;
2932 case Decl::CXXConstructor: return CXCursor_Constructor;
2933 case Decl::CXXDestructor: return CXCursor_Destructor;
2934 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2935 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Argyrios Kyrtzidis3698cef2012-01-24 21:39:26 +00002936 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002937 case Decl::ParmVar: return CXCursor_ParmDecl;
2938 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smithdda56e42011-04-15 14:24:37 +00002939 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002940 case Decl::Var: return CXCursor_VarDecl;
2941 case Decl::Namespace: return CXCursor_Namespace;
2942 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2943 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2944 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2945 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2946 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2947 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis12afd702011-09-30 17:58:23 +00002948 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002949 case Decl::ClassTemplatePartialSpecialization:
2950 return CXCursor_ClassTemplatePartialSpecialization;
2951 case Decl::UsingDirective: return CXCursor_UsingDirective;
Douglas Gregor3e653b32012-04-30 23:41:16 +00002952 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002953
2954 case Decl::Using:
2955 case Decl::UnresolvedUsingValue:
2956 case Decl::UnresolvedUsingTypename:
2957 return CXCursor_UsingDeclaration;
2958
Douglas Gregor4cd65962011-06-03 23:08:58 +00002959 case Decl::ObjCPropertyImpl:
2960 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2961 case ObjCPropertyImplDecl::Dynamic:
2962 return CXCursor_ObjCDynamicDecl;
2963
2964 case ObjCPropertyImplDecl::Synthesize:
2965 return CXCursor_ObjCSynthesizeDecl;
2966 }
Argyrios Kyrtzidis50e5b1d2012-10-05 00:22:24 +00002967
2968 case Decl::Import:
2969 return CXCursor_ModuleImportDecl;
Douglas Gregor4cd65962011-06-03 23:08:58 +00002970
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002971 default:
Dmitri Gribenkobdc80de2013-01-11 20:32:41 +00002972 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002973 switch (TD->getTagKind()) {
Joao Matosdc86f942012-08-31 18:45:21 +00002974 case TTK_Interface: // fall through
Douglas Gregor09c0eb12010-09-03 23:30:36 +00002975 case TTK_Struct: return CXCursor_StructDecl;
2976 case TTK_Class: return CXCursor_ClassDecl;
2977 case TTK_Union: return CXCursor_UnionDecl;
2978 case TTK_Enum: return CXCursor_EnumDecl;
2979 }
2980 }
2981 }
2982
2983 return CXCursor_UnexposedDecl;
2984}
2985
Douglas Gregor55b037b2010-07-08 20:55:51 +00002986static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
Douglas Gregor8cb17462012-10-09 16:01:50 +00002987 bool IncludeUndefined,
Douglas Gregor55b037b2010-07-08 20:55:51 +00002988 bool TargetTypeIsPointer = false) {
John McCall276321a2010-08-25 06:19:51 +00002989 typedef CodeCompletionResult Result;
Douglas Gregor55b037b2010-07-08 20:55:51 +00002990
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002991 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00002992
Douglas Gregor9eb77012009-11-07 00:00:49 +00002993 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2994 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00002995 M != MEnd; ++M) {
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002996 if (IncludeUndefined || M->first->hasMacroDefinition()) {
2997 if (MacroInfo *MI = M->second->getMacroInfo())
2998 if (MI->isUsedForHeaderGuard())
2999 continue;
3000
Douglas Gregor8cb17462012-10-09 16:01:50 +00003001 Results.AddResult(Result(M->first,
Douglas Gregor6e240332010-08-16 16:18:59 +00003002 getMacroUsagePriority(M->first->getName(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00003003 PP.getLangOpts(),
Douglas Gregor6e240332010-08-16 16:18:59 +00003004 TargetTypeIsPointer)));
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00003005 }
Douglas Gregor55b037b2010-07-08 20:55:51 +00003006 }
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003007
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003008 Results.ExitScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003009
Douglas Gregorf329c7c2009-10-30 16:50:04 +00003010}
3011
Douglas Gregorce0e8562010-08-23 21:54:33 +00003012static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3013 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003014 typedef CodeCompletionResult Result;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003015
3016 Results.EnterNewScope();
Douglas Gregor8e3e8742010-10-18 21:05:04 +00003017
Douglas Gregorce0e8562010-08-23 21:54:33 +00003018 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3019 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003020 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Douglas Gregorce0e8562010-08-23 21:54:33 +00003021 Results.AddResult(Result("__func__", CCP_Constant));
3022 Results.ExitScope();
3023}
3024
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003025static void HandleCodeCompleteResults(Sema *S,
3026 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003027 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00003028 CodeCompletionResult *Results,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003029 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00003030 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003031 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00003032}
3033
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003034static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3035 Sema::ParserCompletionContext PCC) {
3036 switch (PCC) {
John McCallfaf5fb42010-08-26 23:41:50 +00003037 case Sema::PCC_Namespace:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003038 return CodeCompletionContext::CCC_TopLevel;
3039
John McCallfaf5fb42010-08-26 23:41:50 +00003040 case Sema::PCC_Class:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003041 return CodeCompletionContext::CCC_ClassStructUnion;
3042
John McCallfaf5fb42010-08-26 23:41:50 +00003043 case Sema::PCC_ObjCInterface:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003044 return CodeCompletionContext::CCC_ObjCInterface;
3045
John McCallfaf5fb42010-08-26 23:41:50 +00003046 case Sema::PCC_ObjCImplementation:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003047 return CodeCompletionContext::CCC_ObjCImplementation;
3048
John McCallfaf5fb42010-08-26 23:41:50 +00003049 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003050 return CodeCompletionContext::CCC_ObjCIvarList;
3051
John McCallfaf5fb42010-08-26 23:41:50 +00003052 case Sema::PCC_Template:
3053 case Sema::PCC_MemberTemplate:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003054 if (S.CurContext->isFileContext())
3055 return CodeCompletionContext::CCC_TopLevel;
David Blaikie8a40f702012-01-17 06:56:22 +00003056 if (S.CurContext->isRecord())
Douglas Gregor0ac41382010-09-23 23:01:17 +00003057 return CodeCompletionContext::CCC_ClassStructUnion;
David Blaikie8a40f702012-01-17 06:56:22 +00003058 return CodeCompletionContext::CCC_Other;
Douglas Gregor0ac41382010-09-23 23:01:17 +00003059
John McCallfaf5fb42010-08-26 23:41:50 +00003060 case Sema::PCC_RecoveryInFunction:
Douglas Gregor0ac41382010-09-23 23:01:17 +00003061 return CodeCompletionContext::CCC_Recovery;
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003062
John McCallfaf5fb42010-08-26 23:41:50 +00003063 case Sema::PCC_ForInit:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003064 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3065 S.getLangOpts().ObjC1)
Douglas Gregorc769d6e2010-10-18 22:01:46 +00003066 return CodeCompletionContext::CCC_ParenthesizedExpression;
3067 else
3068 return CodeCompletionContext::CCC_Expression;
3069
3070 case Sema::PCC_Expression:
John McCallfaf5fb42010-08-26 23:41:50 +00003071 case Sema::PCC_Condition:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003072 return CodeCompletionContext::CCC_Expression;
3073
John McCallfaf5fb42010-08-26 23:41:50 +00003074 case Sema::PCC_Statement:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003075 return CodeCompletionContext::CCC_Statement;
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003076
John McCallfaf5fb42010-08-26 23:41:50 +00003077 case Sema::PCC_Type:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003078 return CodeCompletionContext::CCC_Type;
Douglas Gregor5e35d592010-09-14 23:59:36 +00003079
3080 case Sema::PCC_ParenthesizedExpression:
3081 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor80039242011-02-15 20:33:25 +00003082
3083 case Sema::PCC_LocalDeclarationSpecifiers:
3084 return CodeCompletionContext::CCC_Type;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003085 }
David Blaikie8a40f702012-01-17 06:56:22 +00003086
3087 llvm_unreachable("Invalid ParserCompletionContext!");
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003088}
3089
Douglas Gregorac322ec2010-08-27 21:18:54 +00003090/// \brief If we're in a C++ virtual member function, add completion results
3091/// that invoke the functions we override, since it's common to invoke the
3092/// overridden function as well as adding new functionality.
3093///
3094/// \param S The semantic analysis object for which we are generating results.
3095///
3096/// \param InContext This context in which the nested-name-specifier preceding
3097/// the code-completion point
3098static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3099 ResultBuilder &Results) {
3100 // Look through blocks.
3101 DeclContext *CurContext = S.CurContext;
3102 while (isa<BlockDecl>(CurContext))
3103 CurContext = CurContext->getParent();
3104
3105
3106 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3107 if (!Method || !Method->isVirtual())
3108 return;
3109
3110 // We need to have names for all of the parameters, if we're going to
3111 // generate a forwarding call.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003112 for (auto P : Method->params())
3113 if (!P->getDeclName())
Douglas Gregorac322ec2010-08-27 21:18:54 +00003114 return;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003115
Douglas Gregor75acd922011-09-27 23:30:47 +00003116 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003117 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3118 MEnd = Method->end_overridden_methods();
3119 M != MEnd; ++M) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003120 CodeCompletionBuilder Builder(Results.getAllocator(),
3121 Results.getCodeCompletionTUInfo());
Dmitri Gribenko6cfb1532013-02-14 13:53:30 +00003122 const CXXMethodDecl *Overridden = *M;
Douglas Gregorac322ec2010-08-27 21:18:54 +00003123 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3124 continue;
3125
3126 // If we need a nested-name-specifier, add one now.
3127 if (!InContext) {
3128 NestedNameSpecifier *NNS
3129 = getRequiredQualification(S.Context, CurContext,
3130 Overridden->getDeclContext());
3131 if (NNS) {
3132 std::string Str;
3133 llvm::raw_string_ostream OS(Str);
Douglas Gregor75acd922011-09-27 23:30:47 +00003134 NNS->print(OS, Policy);
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003135 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003136 }
3137 } else if (!InContext->Equals(Overridden->getDeclContext()))
3138 continue;
3139
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00003140 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003141 Overridden->getNameAsString()));
3142 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003143 bool FirstParam = true;
Aaron Ballman43b68be2014-03-07 17:50:17 +00003144 for (auto P : Method->params()) {
Douglas Gregorac322ec2010-08-27 21:18:54 +00003145 if (FirstParam)
3146 FirstParam = false;
3147 else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003148 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003149
Aaron Ballman43b68be2014-03-07 17:50:17 +00003150 Builder.AddPlaceholderChunk(
3151 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003152 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3154 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorac322ec2010-08-27 21:18:54 +00003155 CCP_SuperCompletion,
Douglas Gregor78254c82012-03-27 23:34:16 +00003156 CXCursor_CXXMethod,
3157 CXAvailability_Available,
3158 Overridden));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003159 Results.Ignore(Overridden);
3160 }
3161}
3162
Douglas Gregor07f43572012-01-29 18:15:03 +00003163void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3164 ModuleIdPath Path) {
3165 typedef CodeCompletionResult Result;
3166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003167 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor07f43572012-01-29 18:15:03 +00003168 CodeCompletionContext::CCC_Other);
3169 Results.EnterNewScope();
3170
3171 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003172 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor07f43572012-01-29 18:15:03 +00003173 typedef CodeCompletionResult Result;
3174 if (Path.empty()) {
3175 // Enumerate all top-level modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003176 SmallVector<Module *, 8> Modules;
Douglas Gregor07f43572012-01-29 18:15:03 +00003177 PP.getHeaderSearchInfo().collectAllModules(Modules);
3178 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3179 Builder.AddTypedTextChunk(
3180 Builder.getAllocator().CopyString(Modules[I]->Name));
3181 Results.AddResult(Result(Builder.TakeString(),
3182 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003183 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003184 Modules[I]->isAvailable()
3185 ? CXAvailability_Available
3186 : CXAvailability_NotAvailable));
3187 }
Daniel Jasper07e6c402013-08-05 20:26:17 +00003188 } else if (getLangOpts().Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00003189 // Load the named module.
3190 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3191 Module::AllVisible,
3192 /*IsInclusionDirective=*/false);
3193 // Enumerate submodules.
3194 if (Mod) {
3195 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3196 SubEnd = Mod->submodule_end();
3197 Sub != SubEnd; ++Sub) {
3198
3199 Builder.AddTypedTextChunk(
3200 Builder.getAllocator().CopyString((*Sub)->Name));
3201 Results.AddResult(Result(Builder.TakeString(),
3202 CCP_Declaration,
Argyrios Kyrtzidis345d05f2013-05-29 18:50:15 +00003203 CXCursor_ModuleImportDecl,
Douglas Gregor07f43572012-01-29 18:15:03 +00003204 (*Sub)->isAvailable()
3205 ? CXAvailability_Available
3206 : CXAvailability_NotAvailable));
3207 }
3208 }
3209 }
3210 Results.ExitScope();
3211 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3212 Results.data(),Results.size());
3213}
3214
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003215void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003216 ParserCompletionContext CompletionContext) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003217 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003218 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003219 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorac322ec2010-08-27 21:18:54 +00003220 Results.EnterNewScope();
Douglas Gregor50832e02010-09-20 22:39:41 +00003221
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003222 // Determine how to filter results, e.g., so that the names of
3223 // values (functions, enumerators, function templates, etc.) are
3224 // only allowed where we can have an expression.
3225 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003226 case PCC_Namespace:
3227 case PCC_Class:
3228 case PCC_ObjCInterface:
3229 case PCC_ObjCImplementation:
3230 case PCC_ObjCInstanceVariableList:
3231 case PCC_Template:
3232 case PCC_MemberTemplate:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003233 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003234 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003235 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3236 break;
3237
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003238 case PCC_Statement:
Douglas Gregor5e35d592010-09-14 23:59:36 +00003239 case PCC_ParenthesizedExpression:
Douglas Gregor4d755e82010-08-24 23:58:17 +00003240 case PCC_Expression:
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003241 case PCC_ForInit:
3242 case PCC_Condition:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003243 if (WantTypesInContext(CompletionContext, getLangOpts()))
Douglas Gregor70febae2010-05-28 00:49:12 +00003244 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3245 else
3246 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorac322ec2010-08-27 21:18:54 +00003247
David Blaikiebbafb8a2012-03-11 07:00:24 +00003248 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003249 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003250 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00003251
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003252 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00003253 // Unfiltered
3254 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00003255 }
3256
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003257 // If we are in a C++ non-static member function, check the qualifiers on
3258 // the member function to filter/prioritize the results list.
3259 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3260 if (CurMethod->isInstance())
3261 Results.setObjectTypeQualifiers(
3262 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3263
Douglas Gregorc580c522010-01-14 01:09:38 +00003264 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003265 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3266 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00003267
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003268 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00003269 Results.ExitScope();
3270
Douglas Gregorce0e8562010-08-23 21:54:33 +00003271 switch (CompletionContext) {
Douglas Gregor5e35d592010-09-14 23:59:36 +00003272 case PCC_ParenthesizedExpression:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003273 case PCC_Expression:
3274 case PCC_Statement:
3275 case PCC_RecoveryInFunction:
3276 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00003277 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003278 break;
3279
3280 case PCC_Namespace:
3281 case PCC_Class:
3282 case PCC_ObjCInterface:
3283 case PCC_ObjCImplementation:
3284 case PCC_ObjCInstanceVariableList:
3285 case PCC_Template:
3286 case PCC_MemberTemplate:
3287 case PCC_ForInit:
3288 case PCC_Condition:
3289 case PCC_Type:
Douglas Gregor80039242011-02-15 20:33:25 +00003290 case PCC_LocalDeclarationSpecifiers:
Douglas Gregorf02e5f32010-08-24 01:11:00 +00003291 break;
Douglas Gregorce0e8562010-08-23 21:54:33 +00003292 }
3293
Douglas Gregor9eb77012009-11-07 00:00:49 +00003294 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003295 AddMacroResults(PP, Results, false);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003296
Douglas Gregor50832e02010-09-20 22:39:41 +00003297 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003298 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00003299}
3300
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003301static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3302 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003303 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00003304 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003305 bool IsSuper,
3306 ResultBuilder &Results);
3307
3308void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3309 bool AllowNonIdentifiers,
3310 bool AllowNestedNameSpecifiers) {
John McCall276321a2010-08-25 06:19:51 +00003311 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003312 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003313 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00003314 AllowNestedNameSpecifiers
3315 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3316 : CodeCompletionContext::CCC_Name);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003317 Results.EnterNewScope();
3318
3319 // Type qualifiers can come after names.
3320 Results.AddResult(Result("const"));
3321 Results.AddResult(Result("volatile"));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003322 if (getLangOpts().C99)
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003323 Results.AddResult(Result("restrict"));
3324
David Blaikiebbafb8a2012-03-11 07:00:24 +00003325 if (getLangOpts().CPlusPlus) {
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003326 if (AllowNonIdentifiers) {
3327 Results.AddResult(Result("operator"));
3328 }
3329
3330 // Add nested-name-specifiers.
3331 if (AllowNestedNameSpecifiers) {
3332 Results.allowNestedNameSpecifiers();
Douglas Gregor0ac41382010-09-23 23:01:17 +00003333 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003334 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3335 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3336 CodeCompleter->includeGlobals());
Craig Topperc3ec1492014-05-26 06:22:03 +00003337 Results.setFilter(nullptr);
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003338 }
3339 }
3340 Results.ExitScope();
3341
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003342 // If we're in a context where we might have an expression (rather than a
3343 // declaration), and what we've seen so far is an Objective-C type that could
3344 // be a receiver of a class message, this may be a class message send with
3345 // the initial opening bracket '[' missing. Add appropriate completions.
3346 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003347 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003348 DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003349 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3350 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
Richard Smithb4a9e862013-04-12 22:46:28 +00003351 !DS.isTypeAltiVecVector() &&
3352 S &&
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003353 (S->getFlags() & Scope::DeclScope) != 0 &&
3354 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3355 Scope::FunctionPrototypeScope |
3356 Scope::AtCatchScope)) == 0) {
3357 ParsedType T = DS.getRepAsType();
3358 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00003359 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003360 }
3361
Douglas Gregor56ccce02010-08-24 04:59:56 +00003362 // Note that we intentionally suppress macro results here, since we do not
3363 // encourage using macros to produce the names of entities.
3364
Douglas Gregor0ac41382010-09-23 23:01:17 +00003365 HandleCodeCompleteResults(this, CodeCompleter,
3366 Results.getCompletionContext(),
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003367 Results.data(), Results.size());
3368}
3369
Douglas Gregor68762e72010-08-23 21:17:50 +00003370struct Sema::CodeCompleteExpressionData {
3371 CodeCompleteExpressionData(QualType PreferredType = QualType())
3372 : PreferredType(PreferredType), IntegralConstantExpression(false),
3373 ObjCCollection(false) { }
3374
3375 QualType PreferredType;
3376 bool IntegralConstantExpression;
3377 bool ObjCCollection;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003378 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregor68762e72010-08-23 21:17:50 +00003379};
3380
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003381/// \brief Perform code-completion in an expression context when we know what
3382/// type we're looking for.
Douglas Gregor68762e72010-08-23 21:17:50 +00003383void Sema::CodeCompleteExpression(Scope *S,
3384 const CodeCompleteExpressionData &Data) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003385 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003386 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003387 CodeCompletionContext::CCC_Expression);
Douglas Gregor68762e72010-08-23 21:17:50 +00003388 if (Data.ObjCCollection)
3389 Results.setFilter(&ResultBuilder::IsObjCCollection);
3390 else if (Data.IntegralConstantExpression)
Douglas Gregor85b50632010-07-28 21:50:18 +00003391 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003392 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003393 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3394 else
3395 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor68762e72010-08-23 21:17:50 +00003396
3397 if (!Data.PreferredType.isNull())
3398 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3399
3400 // Ignore any declarations that we were told that we don't care about.
3401 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3402 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003403
3404 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003405 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3406 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003407
3408 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003409 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003410 Results.ExitScope();
3411
Douglas Gregor55b037b2010-07-08 20:55:51 +00003412 bool PreferredTypeIsPointer = false;
Douglas Gregor68762e72010-08-23 21:17:50 +00003413 if (!Data.PreferredType.isNull())
3414 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3415 || Data.PreferredType->isMemberPointerType()
3416 || Data.PreferredType->isBlockPointerType();
Douglas Gregor55b037b2010-07-08 20:55:51 +00003417
Douglas Gregorce0e8562010-08-23 21:54:33 +00003418 if (S->getFnParent() &&
3419 !Data.ObjCCollection &&
3420 !Data.IntegralConstantExpression)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003421 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregorce0e8562010-08-23 21:54:33 +00003422
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003423 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00003424 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003425 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor68762e72010-08-23 21:17:50 +00003426 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3427 Data.PreferredType),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003428 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003429}
3430
Douglas Gregoreda7e542010-09-18 01:28:11 +00003431void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3432 if (E.isInvalid())
3433 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003434 else if (getLangOpts().ObjC1)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003435 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
Douglas Gregored0b69d2010-09-15 16:23:04 +00003436}
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003437
Douglas Gregorb888acf2010-12-09 23:01:55 +00003438/// \brief The set of properties that have already been added, referenced by
3439/// property name.
3440typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3441
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003442/// \brief Retrieve the container definition, if any?
3443static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3444 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3445 if (Interface->hasDefinition())
3446 return Interface->getDefinition();
3447
3448 return Interface;
3449 }
3450
3451 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3452 if (Protocol->hasDefinition())
3453 return Protocol->getDefinition();
3454
3455 return Protocol;
3456 }
3457 return Container;
3458}
3459
3460static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00003461 bool AllowCategories,
Douglas Gregor95147142011-05-05 15:50:42 +00003462 bool AllowNullaryMethods,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003463 DeclContext *CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003464 AddedPropertiesSet &AddedProperties,
Douglas Gregor9291bad2009-11-18 01:29:26 +00003465 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00003466 typedef CodeCompletionResult Result;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003467
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003468 // Retrieve the definition.
3469 Container = getContainerDef(Container);
3470
Douglas Gregor9291bad2009-11-18 01:29:26 +00003471 // Add properties in this container.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003472 for (const auto *P : Container->properties())
David Blaikie82e95a32014-11-19 07:49:47 +00003473 if (AddedProperties.insert(P->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00003474 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00003475 CurContext);
Craig Topperc3ec1492014-05-26 06:22:03 +00003476
Douglas Gregor95147142011-05-05 15:50:42 +00003477 // Add nullary methods
3478 if (AllowNullaryMethods) {
3479 ASTContext &Context = Container->getASTContext();
Douglas Gregor75acd922011-09-27 23:30:47 +00003480 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003481 for (auto *M : Container->methods()) {
Douglas Gregor95147142011-05-05 15:50:42 +00003482 if (M->getSelector().isUnarySelector())
3483 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
David Blaikie82e95a32014-11-19 07:49:47 +00003484 if (AddedProperties.insert(Name).second) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003485 CodeCompletionBuilder Builder(Results.getAllocator(),
3486 Results.getCodeCompletionTUInfo());
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003487 AddResultTypeChunk(Context, Policy, M, Builder);
Douglas Gregor95147142011-05-05 15:50:42 +00003488 Builder.AddTypedTextChunk(
3489 Results.getAllocator().CopyString(Name->getName()));
3490
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003491 Results.MaybeAddResult(Result(Builder.TakeString(), M,
Douglas Gregor78254c82012-03-27 23:34:16 +00003492 CCP_MemberDeclaration + CCD_MethodAsProperty),
Douglas Gregor95147142011-05-05 15:50:42 +00003493 CurContext);
3494 }
3495 }
3496 }
3497
3498
Douglas Gregor9291bad2009-11-18 01:29:26 +00003499 // Add properties in referenced protocols.
3500 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003501 for (auto *P : Protocol->protocols())
3502 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003503 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003504 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00003505 if (AllowCategories) {
3506 // Look through categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00003507 for (auto *Cat : IFace->known_categories())
3508 AddObjCProperties(Cat, AllowCategories, AllowNullaryMethods, CurContext,
3509 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00003510 }
Aaron Ballman15063e12014-03-13 21:35:02 +00003511
Douglas Gregor9291bad2009-11-18 01:29:26 +00003512 // Look through protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003513 for (auto *I : IFace->all_referenced_protocols())
3514 AddObjCProperties(I, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003515 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003516
3517 // Look in the superclass.
3518 if (IFace->getSuperClass())
Douglas Gregor95147142011-05-05 15:50:42 +00003519 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3520 AllowNullaryMethods, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003521 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003522 } else if (const ObjCCategoryDecl *Category
3523 = dyn_cast<ObjCCategoryDecl>(Container)) {
3524 // Look through protocols.
Aaron Ballman19a41762014-03-14 12:55:57 +00003525 for (auto *P : Category->protocols())
3526 AddObjCProperties(P, AllowCategories, AllowNullaryMethods, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003527 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003528 }
3529}
3530
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003531void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Douglas Gregor2436e712009-09-17 21:32:03 +00003532 SourceLocation OpLoc,
3533 bool IsArrow) {
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003534 if (!Base || !CodeCompleter)
Douglas Gregor2436e712009-09-17 21:32:03 +00003535 return;
3536
Douglas Gregor1cc88a92012-01-23 15:59:30 +00003537 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3538 if (ConvertedBase.isInvalid())
3539 return;
3540 Base = ConvertedBase.get();
3541
John McCall276321a2010-08-25 06:19:51 +00003542 typedef CodeCompletionResult Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003543
Douglas Gregor2436e712009-09-17 21:32:03 +00003544 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00003545
3546 if (IsArrow) {
3547 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3548 BaseType = Ptr->getPointeeType();
3549 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003550 /*Do nothing*/ ;
Douglas Gregor3545ff42009-09-21 16:56:56 +00003551 else
3552 return;
3553 }
3554
Douglas Gregor21325842011-07-07 16:03:39 +00003555 enum CodeCompletionContext::Kind contextKind;
3556
3557 if (IsArrow) {
3558 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3559 }
3560 else {
3561 if (BaseType->isObjCObjectPointerType() ||
3562 BaseType->isObjCObjectOrInterfaceType()) {
3563 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3564 }
3565 else {
3566 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3567 }
3568 }
3569
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003570 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003571 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00003572 CodeCompletionContext(contextKind,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003573 BaseType),
3574 &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003575 Results.EnterNewScope();
3576 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor9be0ed42010-08-26 16:36:48 +00003577 // Indicate that we are performing a member access, and the cv-qualifiers
3578 // for the base object type.
3579 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3580
Douglas Gregor9291bad2009-11-18 01:29:26 +00003581 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00003582 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00003583 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00003584 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3585 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003586
David Blaikiebbafb8a2012-03-11 07:00:24 +00003587 if (getLangOpts().CPlusPlus) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003588 if (!Results.empty()) {
3589 // The "template" keyword can follow "->" or "." in the grammar.
3590 // However, we only want to suggest the template keyword if something
3591 // is dependent.
3592 bool IsDependent = BaseType->isDependentType();
3593 if (!IsDependent) {
3594 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00003595 if (DeclContext *Ctx = DepScope->getEntity()) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003596 IsDependent = Ctx->isDependentContext();
3597 break;
3598 }
3599 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003600
Douglas Gregor9291bad2009-11-18 01:29:26 +00003601 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00003602 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003603 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003604 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003605 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3606 // Objective-C property reference.
Douglas Gregorb888acf2010-12-09 23:01:55 +00003607 AddedPropertiesSet AddedProperties;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003608
3609 // Add property results based on our interface.
3610 const ObjCObjectPointerType *ObjCPtr
3611 = BaseType->getAsObjCInterfacePointerType();
3612 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor95147142011-05-05 15:50:42 +00003613 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3614 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00003615 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003616
3617 // Add properties from the protocols in a qualified interface.
Aaron Ballman83731462014-03-17 16:14:00 +00003618 for (auto *I : ObjCPtr->quals())
3619 AddObjCProperties(I, true, /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor95147142011-05-05 15:50:42 +00003620 AddedProperties, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00003621 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003622 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00003623 // Objective-C instance variable access.
Craig Topperc3ec1492014-05-26 06:22:03 +00003624 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor9291bad2009-11-18 01:29:26 +00003625 if (const ObjCObjectPointerType *ObjCPtr
3626 = BaseType->getAs<ObjCObjectPointerType>())
3627 Class = ObjCPtr->getInterfaceDecl();
3628 else
John McCall8b07ec22010-05-15 11:32:37 +00003629 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00003630
3631 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00003632 if (Class) {
3633 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3634 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00003635 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3636 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00003637 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003638 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00003639
3640 // FIXME: How do we cope with isa?
3641
3642 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003643
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00003644 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003645 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003646 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003647 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00003648}
3649
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003650void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3651 if (!CodeCompleter)
3652 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00003653
3654 ResultBuilder::LookupFilter Filter = nullptr;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003655 enum CodeCompletionContext::Kind ContextKind
3656 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003657 switch ((DeclSpec::TST)TagSpec) {
3658 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003659 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003660 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003661 break;
3662
3663 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003664 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003665 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003666 break;
3667
3668 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003669 case DeclSpec::TST_class:
Joao Matosdc86f942012-08-31 18:45:21 +00003670 case DeclSpec::TST_interface:
Douglas Gregor3545ff42009-09-21 16:56:56 +00003671 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003672 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003673 break;
3674
3675 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003676 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003677 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003678
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003679 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3680 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00003681 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00003682
3683 // First pass: look for tags.
3684 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00003685 LookupVisibleDecls(S, LookupTagName, Consumer,
3686 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00003687
Douglas Gregor39982192010-08-15 06:18:01 +00003688 if (CodeCompleter->includeGlobals()) {
3689 // Second pass: look for nested name specifiers.
3690 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3691 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3692 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00003693
Douglas Gregor0ac41382010-09-23 23:01:17 +00003694 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003695 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00003696}
3697
Douglas Gregor28c78432010-08-27 17:35:51 +00003698void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003699 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003700 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003701 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor28c78432010-08-27 17:35:51 +00003702 Results.EnterNewScope();
3703 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3704 Results.AddResult("const");
3705 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3706 Results.AddResult("volatile");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003707 if (getLangOpts().C99 &&
Douglas Gregor28c78432010-08-27 17:35:51 +00003708 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3709 Results.AddResult("restrict");
Richard Smith8e1ac332013-03-28 01:55:44 +00003710 if (getLangOpts().C11 &&
3711 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3712 Results.AddResult("_Atomic");
Douglas Gregor28c78432010-08-27 17:35:51 +00003713 Results.ExitScope();
3714 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00003715 Results.getCompletionContext(),
Douglas Gregor28c78432010-08-27 17:35:51 +00003716 Results.data(), Results.size());
3717}
3718
Douglas Gregord328d572009-09-21 18:10:23 +00003719void Sema::CodeCompleteCase(Scope *S) {
John McCallaab3e412010-08-25 08:40:02 +00003720 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregord328d572009-09-21 18:10:23 +00003721 return;
John McCall5939b162011-08-06 07:30:58 +00003722
John McCallaab3e412010-08-25 08:40:02 +00003723 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCall5939b162011-08-06 07:30:58 +00003724 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3725 if (!type->isEnumeralType()) {
3726 CodeCompleteExpressionData Data(type);
Douglas Gregor68762e72010-08-23 21:17:50 +00003727 Data.IntegralConstantExpression = true;
3728 CodeCompleteExpression(S, Data);
Douglas Gregord328d572009-09-21 18:10:23 +00003729 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00003730 }
Douglas Gregord328d572009-09-21 18:10:23 +00003731
3732 // Code-complete the cases of a switch statement over an enumeration type
3733 // by providing the list of
John McCall5939b162011-08-06 07:30:58 +00003734 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor9b4f3702012-06-12 13:44:08 +00003735 if (EnumDecl *Def = Enum->getDefinition())
3736 Enum = Def;
Douglas Gregord328d572009-09-21 18:10:23 +00003737
3738 // Determine which enumerators we have already seen in the switch statement.
3739 // FIXME: Ideally, we would also be able to look *past* the code-completion
3740 // token, in case we are code-completing in the middle of the switch and not
3741 // at the end. However, we aren't able to do so at the moment.
3742 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Craig Topperc3ec1492014-05-26 06:22:03 +00003743 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregord328d572009-09-21 18:10:23 +00003744 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3745 SC = SC->getNextSwitchCase()) {
3746 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3747 if (!Case)
3748 continue;
3749
3750 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3751 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3752 if (EnumConstantDecl *Enumerator
3753 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3754 // We look into the AST of the case statement to determine which
3755 // enumerator was named. Alternatively, we could compute the value of
3756 // the integral constant expression, then compare it against the
3757 // values of each enumerator. However, value-based approach would not
3758 // work as well with C++ templates where enumerators declared within a
3759 // template are type- and value-dependent.
3760 EnumeratorsSeen.insert(Enumerator);
3761
Douglas Gregorf2510672009-09-21 19:57:38 +00003762 // If this is a qualified-id, keep track of the nested-name-specifier
3763 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00003764 //
3765 // switch (TagD.getKind()) {
3766 // case TagDecl::TK_enum:
3767 // break;
3768 // case XXX
3769 //
Douglas Gregorf2510672009-09-21 19:57:38 +00003770 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00003771 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3772 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003773 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00003774 }
3775 }
3776
David Blaikiebbafb8a2012-03-11 07:00:24 +00003777 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
Douglas Gregorf2510672009-09-21 19:57:38 +00003778 // If there are no prior enumerators in C++, check whether we have to
3779 // qualify the names of the enumerators that we suggest, because they
3780 // may not be visible in this scope.
Douglas Gregord3cebdb2012-02-01 05:02:47 +00003781 Qualifier = getRequiredQualification(Context, CurContext, Enum);
Douglas Gregorf2510672009-09-21 19:57:38 +00003782 }
3783
Douglas Gregord328d572009-09-21 18:10:23 +00003784 // Add any enumerators that have not yet been mentioned.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003785 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00003786 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00003787 CodeCompletionContext::CCC_Expression);
Douglas Gregord328d572009-09-21 18:10:23 +00003788 Results.EnterNewScope();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003789 for (auto *E : Enum->enumerators()) {
3790 if (EnumeratorsSeen.count(E))
Douglas Gregord328d572009-09-21 18:10:23 +00003791 continue;
3792
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003793 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Craig Topperc3ec1492014-05-26 06:22:03 +00003794 Results.AddResult(R, CurContext, nullptr, false);
Douglas Gregord328d572009-09-21 18:10:23 +00003795 }
3796 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00003797
Douglas Gregor21325842011-07-07 16:03:39 +00003798 //We need to make sure we're setting the right context,
3799 //so only say we include macros if the code completer says we do
3800 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3801 if (CodeCompleter->includeMacros()) {
Douglas Gregor8cb17462012-10-09 16:01:50 +00003802 AddMacroResults(PP, Results, false);
Douglas Gregor21325842011-07-07 16:03:39 +00003803 kind = CodeCompletionContext::CCC_OtherWithMacros;
3804 }
3805
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003806 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00003807 kind,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003808 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00003809}
3810
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003811static bool anyNullArguments(ArrayRef<Expr *> Args) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003812 if (Args.size() && !Args.data())
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003813 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003814
3815 for (unsigned I = 0; I != Args.size(); ++I)
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003816 if (!Args[I])
3817 return true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003818
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00003819 return false;
3820}
3821
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003822typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3823
3824void mergeCandidatesWithResults(Sema &SemaRef,
3825 SmallVectorImpl<ResultCandidate> &Results,
3826 OverloadCandidateSet &CandidateSet,
3827 SourceLocation Loc) {
3828 if (!CandidateSet.empty()) {
3829 // Sort the overload candidate set by placing the best overloads first.
3830 std::stable_sort(
3831 CandidateSet.begin(), CandidateSet.end(),
3832 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3833 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3834 });
3835
3836 // Add the remaining viable overload candidates as code-completion results.
3837 for (auto &Candidate : CandidateSet)
3838 if (Candidate.Viable)
3839 Results.push_back(ResultCandidate(Candidate.Function));
3840 }
3841}
3842
3843/// \brief Get the type of the Nth parameter from a given set of overload
3844/// candidates.
3845QualType getParamType(Sema &SemaRef, ArrayRef<ResultCandidate> Candidates,
3846 unsigned N) {
3847
3848 // Given the overloads 'Candidates' for a function call matching all arguments
3849 // up to N, return the type of the Nth parameter if it is the same for all
3850 // overload candidates.
3851 QualType ParamType;
3852 for (auto &Candidate : Candidates) {
3853 if (auto FType = Candidate.getFunctionType())
3854 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3855 if (N < Proto->getNumParams()) {
3856 if (ParamType.isNull())
3857 ParamType = Proto->getParamType(N);
3858 else if (!SemaRef.Context.hasSameUnqualifiedType(
3859 ParamType.getNonReferenceType(),
3860 Proto->getParamType(N).getNonReferenceType()))
3861 // Otherwise return a default-constructed QualType.
3862 return QualType();
3863 }
3864 }
3865
3866 return ParamType;
3867}
3868
3869void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3870 MutableArrayRef<ResultCandidate> Candidates,
3871 unsigned CurrentArg,
3872 bool CompleteExpressionWithCurrentArg = true) {
3873 QualType ParamType;
3874 if (CompleteExpressionWithCurrentArg)
3875 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3876
3877 if (ParamType.isNull())
3878 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3879 else
3880 SemaRef.CodeCompleteExpression(S, ParamType);
3881
3882 if (!Candidates.empty())
3883 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3884 Candidates.data(),
3885 Candidates.size());
3886}
3887
3888void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003889 if (!CodeCompleter)
3890 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003891
3892 // When we're code-completing for a call, we fall back to ordinary
3893 // name code-completion whenever we can't produce specific
3894 // results. We may want to revisit this strategy in the future,
3895 // e.g., by merging the two kinds of results.
3896
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003897 // FIXME: Provide support for highlighting optional parameters.
3898 // FIXME: Provide support for variadic template functions.
Douglas Gregor3ef59522009-12-11 19:06:04 +00003899
Douglas Gregorcabea402009-09-22 15:41:20 +00003900 // Ignore type-dependent call expressions entirely.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003901 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3902 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003903 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00003904 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00003905 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003906
John McCall57500772009-12-16 12:17:52 +00003907 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00003908 SourceLocation Loc = Fn->getExprLoc();
Richard Smith100b24a2014-04-17 01:52:14 +00003909 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
John McCall57500772009-12-16 12:17:52 +00003910
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003911 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorff59f672010-01-21 15:46:19 +00003912
John McCall57500772009-12-16 12:17:52 +00003913 Expr *NakedFn = Fn->IgnoreParenCasts();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003914 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003915 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003916 /*PartialOverloading=*/true);
3917 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3918 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
3919 if (UME->hasExplicitTemplateArgs()) {
3920 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
3921 TemplateArgs = &TemplateArgsBuffer;
Douglas Gregorff59f672010-01-21 15:46:19 +00003922 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003923 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
3924 ArgExprs.append(Args.begin(), Args.end());
3925 UnresolvedSet<8> Decls;
3926 Decls.append(UME->decls_begin(), UME->decls_end());
3927 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
3928 /*SuppressUsedConversions=*/false,
3929 /*PartialOverloading=*/true);
3930 } else if (auto DC = NakedFn->getType()->getCanonicalTypeInternal()
3931 ->getAsCXXRecordDecl()) {
3932 // If it's a CXXRecordDecl, it may overload the function call operator,
3933 // so we check if it does and add them as candidates.
3934 DeclarationName OpName = Context.DeclarationNames
3935 .getCXXOperatorName(OO_Call);
3936 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
3937 LookupQualifiedName(R, DC);
3938 R.suppressDiagnostics();
3939 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
3940 ArgExprs.append(Args.begin(), Args.end());
3941 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
3942 /*ExplicitArgs=*/nullptr,
3943 /*SuppressUsedConversions=*/false,
3944 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003945 } else {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003946 // Lastly we check, as a possibly resolved expression, whether it can be
3947 // converted to a function.
3948 FunctionDecl *FD = nullptr;
3949 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
3950 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
3951 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
3952 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3953 if (FD) {
3954 if (!getLangOpts().CPlusPlus ||
3955 !FD->getType()->getAs<FunctionProtoType>())
3956 Results.push_back(ResultCandidate(FD));
3957 else
3958 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
3959 Args, CandidateSet,
3960 /*SuppressUsedConversions=*/false,
3961 /*PartialOverloading=*/true);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00003962 }
Douglas Gregorcabea402009-09-22 15:41:20 +00003963 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00003964
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003965 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
3966 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
3967 !CandidateSet.empty());
3968}
3969
3970void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
3971 ArrayRef<Expr *> Args) {
3972 if (!CodeCompleter)
3973 return;
3974
3975 // A complete type is needed to lookup for constructors.
3976 if (RequireCompleteType(Loc, Type, 0))
3977 return;
3978
3979 // FIXME: Provide support for member initializers.
3980 // FIXME: Provide support for variadic template constructors.
3981 // FIXME: Provide support for highlighting optional parameters.
3982
3983 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
3984
3985 for (auto C : LookupConstructors(Type->getAsCXXRecordDecl())) {
3986 if (auto FD = dyn_cast<FunctionDecl>(C)) {
3987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
3988 Args, CandidateSet,
3989 /*SuppressUsedConversions=*/false,
3990 /*PartialOverloading=*/true);
3991 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
3992 AddTemplateOverloadCandidate(FTD,
3993 DeclAccessPair::make(FTD, C->getAccess()),
3994 /*ExplicitTemplateArgs=*/nullptr,
3995 Args, CandidateSet,
3996 /*SuppressUsedConversions=*/false,
3997 /*PartialOverloading=*/true);
3998 }
3999 }
4000
4001 SmallVector<ResultCandidate, 8> Results;
4002 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4003 CodeCompleteOverloadResults(*this, S, Results, Args.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00004004}
4005
John McCall48871652010-08-21 09:40:31 +00004006void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4007 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004008 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004009 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004010 return;
4011 }
4012
4013 CodeCompleteExpression(S, VD->getType());
4014}
4015
4016void Sema::CodeCompleteReturn(Scope *S) {
4017 QualType ResultType;
4018 if (isa<BlockDecl>(CurContext)) {
4019 if (BlockScopeInfo *BSI = getCurBlock())
4020 ResultType = BSI->ReturnType;
4021 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004022 ResultType = Function->getReturnType();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004023 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
Alp Toker314cc812014-01-25 16:55:45 +00004024 ResultType = Method->getReturnType();
4025
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004026 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004027 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004028 else
4029 CodeCompleteExpression(S, ResultType);
4030}
4031
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004032void Sema::CodeCompleteAfterIf(Scope *S) {
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004033 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004034 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004035 mapCodeCompletionContext(*this, PCC_Statement));
4036 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4037 Results.EnterNewScope();
4038
4039 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4040 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4041 CodeCompleter->includeGlobals());
4042
4043 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4044
4045 // "else" block
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004046 CodeCompletionBuilder Builder(Results.getAllocator(),
4047 Results.getCodeCompletionTUInfo());
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004048 Builder.AddTypedTextChunk("else");
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004049 if (Results.includeCodePatterns()) {
4050 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4051 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4052 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4053 Builder.AddPlaceholderChunk("statements");
4054 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4055 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4056 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004057 Results.AddResult(Builder.TakeString());
4058
4059 // "else if" block
4060 Builder.AddTypedTextChunk("else");
4061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4062 Builder.AddTextChunk("if");
4063 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4064 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004065 if (getLangOpts().CPlusPlus)
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004066 Builder.AddPlaceholderChunk("condition");
4067 else
4068 Builder.AddPlaceholderChunk("expression");
4069 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor3a5d6c22012-02-16 17:49:04 +00004070 if (Results.includeCodePatterns()) {
4071 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4072 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4073 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4074 Builder.AddPlaceholderChunk("statements");
4075 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4076 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4077 }
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004078 Results.AddResult(Builder.TakeString());
4079
4080 Results.ExitScope();
4081
4082 if (S->getFnParent())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004083 AddPrettyFunctionResults(PP.getLangOpts(), Results);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004084
4085 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00004086 AddMacroResults(PP, Results, false);
Douglas Gregor4ecb7202011-07-30 08:36:53 +00004087
4088 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4089 Results.data(),Results.size());
4090}
4091
Richard Trieu2bd04012011-09-09 02:00:50 +00004092void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004093 if (LHS)
4094 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4095 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004096 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00004097}
4098
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004099void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00004100 bool EnteringContext) {
4101 if (!SS.getScopeRep() || !CodeCompleter)
4102 return;
4103
Douglas Gregor3545ff42009-09-21 16:56:56 +00004104 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4105 if (!Ctx)
4106 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00004107
4108 // Try to instantiate any non-dependent declaration contexts before
4109 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00004110 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00004111 return;
4112
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004113 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004114 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004115 CodeCompletionContext::CCC_Name);
Douglas Gregorac322ec2010-08-27 21:18:54 +00004116 Results.EnterNewScope();
Douglas Gregor0ac41382010-09-23 23:01:17 +00004117
Douglas Gregor3545ff42009-09-21 16:56:56 +00004118 // The "template" keyword can follow "::" in the grammar, but only
4119 // put it into the grammar if the nested-name-specifier is dependent.
Aaron Ballman4a979672014-01-03 13:56:08 +00004120 NestedNameSpecifier *NNS = SS.getScopeRep();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004121 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00004122 Results.AddResult("template");
Douglas Gregorac322ec2010-08-27 21:18:54 +00004123
4124 // Add calls to overridden virtual functions, if there are any.
4125 //
4126 // FIXME: This isn't wonderful, because we don't know whether we're actually
4127 // in a context that permits expressions. This is a general issue with
4128 // qualified-id completions.
4129 if (!EnteringContext)
4130 MaybeAddOverrideCalls(*this, Ctx, Results);
4131 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004132
Douglas Gregorac322ec2010-08-27 21:18:54 +00004133 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4134 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4135
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004136 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorc1679ec2011-07-25 17:48:11 +00004137 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004138 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00004139}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004140
4141void Sema::CodeCompleteUsing(Scope *S) {
4142 if (!CodeCompleter)
4143 return;
4144
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004145 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004146 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004147 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4148 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004149 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004150
4151 // If we aren't in class scope, we could see the "namespace" keyword.
4152 if (!S->isClassScope())
John McCall276321a2010-08-25 06:19:51 +00004153 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004154
4155 // After "using", we can see anything that would start a
4156 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004157 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004158 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4159 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004160 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004161
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004162 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004163 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004164 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004165}
4166
4167void Sema::CodeCompleteUsingDirective(Scope *S) {
4168 if (!CodeCompleter)
4169 return;
4170
Douglas Gregor3545ff42009-09-21 16:56:56 +00004171 // After "using namespace", we expect to see a namespace name or namespace
4172 // alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004173 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004174 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004175 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004176 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004177 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004178 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004179 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4180 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00004181 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004182 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004183 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004184 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004185}
4186
4187void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4188 if (!CodeCompleter)
4189 return;
4190
Ted Kremenekc37877d2013-10-08 17:08:03 +00004191 DeclContext *Ctx = S->getEntity();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004192 if (!S->getParent())
4193 Ctx = Context.getTranslationUnitDecl();
4194
Douglas Gregor0ac41382010-09-23 23:01:17 +00004195 bool SuppressedGlobalResults
4196 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4197
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004198 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004199 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004200 SuppressedGlobalResults
4201 ? CodeCompletionContext::CCC_Namespace
4202 : CodeCompletionContext::CCC_Other,
4203 &ResultBuilder::IsNamespace);
4204
4205 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00004206 // We only want to see those namespaces that have already been defined
4207 // within this scope, because its likely that the user is creating an
4208 // extended namespace declaration. Keep track of the most recent
4209 // definition of each namespace.
4210 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4211 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4212 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4213 NS != NSEnd; ++NS)
David Blaikie40ed2972012-06-06 20:45:41 +00004214 OrigToLatest[NS->getOriginalNamespace()] = *NS;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004215
4216 // Add the most recent definition (or extended definition) of each
4217 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00004218 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004219 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
Douglas Gregor78254c82012-03-27 23:34:16 +00004220 NS = OrigToLatest.begin(),
4221 NSEnd = OrigToLatest.end();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004222 NS != NSEnd; ++NS)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004223 Results.AddResult(CodeCompletionResult(
Craig Topperc3ec1492014-05-26 06:22:03 +00004224 NS->second, Results.getBasePriority(NS->second),
4225 nullptr),
4226 CurContext, nullptr, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004227 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004228 }
4229
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004230 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004231 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004232 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004233}
4234
4235void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4236 if (!CodeCompleter)
4237 return;
4238
Douglas Gregor3545ff42009-09-21 16:56:56 +00004239 // After "namespace", we expect to see a namespace or alias.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004240 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004241 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004242 CodeCompletionContext::CCC_Namespace,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004243 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004244 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004245 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4246 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004247 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004248 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004249 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004250}
4251
Douglas Gregorc811ede2009-09-18 20:05:18 +00004252void Sema::CodeCompleteOperatorName(Scope *S) {
4253 if (!CodeCompleter)
4254 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00004255
John McCall276321a2010-08-25 06:19:51 +00004256 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004257 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004258 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004259 CodeCompletionContext::CCC_Type,
Douglas Gregor0ac41382010-09-23 23:01:17 +00004260 &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004261 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00004262
Douglas Gregor3545ff42009-09-21 16:56:56 +00004263 // Add the names of overloadable operators.
4264#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4265 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00004266 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00004267#include "clang/Basic/OperatorKinds.def"
4268
4269 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00004270 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00004271 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00004272 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4273 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00004274
4275 // Add any type specifiers
David Blaikiebbafb8a2012-03-11 07:00:24 +00004276 AddTypeSpecifierResults(getLangOpts(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00004277 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00004278
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004279 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00004280 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004281 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00004282}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00004283
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004284void Sema::CodeCompleteConstructorInitializer(
4285 Decl *ConstructorD,
4286 ArrayRef <CXXCtorInitializer *> Initializers) {
Douglas Gregor75acd922011-09-27 23:30:47 +00004287 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004288 CXXConstructorDecl *Constructor
4289 = static_cast<CXXConstructorDecl *>(ConstructorD);
4290 if (!Constructor)
4291 return;
4292
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004293 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004294 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00004295 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004296 Results.EnterNewScope();
4297
4298 // Fill in any already-initialized fields or base classes.
4299 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4300 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004301 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004302 if (Initializers[I]->isBaseInitializer())
4303 InitializedBases.insert(
4304 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4305 else
Francois Pichetd583da02010-12-04 09:14:42 +00004306 InitializedFields.insert(cast<FieldDecl>(
4307 Initializers[I]->getAnyMember()));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004308 }
4309
4310 // Add completions for base classes.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004311 CodeCompletionBuilder Builder(Results.getAllocator(),
4312 Results.getCodeCompletionTUInfo());
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004313 bool SawLastInitializer = Initializers.empty();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004314 CXXRecordDecl *ClassDecl = Constructor->getParent();
Aaron Ballman574705e2014-03-13 15:41:46 +00004315 for (const auto &Base : ClassDecl->bases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004316 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4317 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004318 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004319 = !Initializers.empty() &&
4320 Initializers.back()->isBaseInitializer() &&
Aaron Ballman574705e2014-03-13 15:41:46 +00004321 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004322 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004323 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004324 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004325
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004326 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004327 Results.getAllocator().CopyString(
Aaron Ballman574705e2014-03-13 15:41:46 +00004328 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004329 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4330 Builder.AddPlaceholderChunk("args");
4331 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4332 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004333 SawLastInitializer? CCP_NextInitializer
4334 : CCP_MemberDeclaration));
4335 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004336 }
4337
4338 // Add completions for virtual base classes.
Aaron Ballman445a9392014-03-13 16:15:17 +00004339 for (const auto &Base : ClassDecl->vbases()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004340 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4341 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004342 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004343 = !Initializers.empty() &&
4344 Initializers.back()->isBaseInitializer() &&
Aaron Ballman445a9392014-03-13 16:15:17 +00004345 Context.hasSameUnqualifiedType(Base.getType(),
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004346 QualType(Initializers.back()->getBaseClass(), 0));
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004347 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004348 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004349
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004350 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004351 Builder.getAllocator().CopyString(
Aaron Ballman445a9392014-03-13 16:15:17 +00004352 Base.getType().getAsString(Policy)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004353 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4354 Builder.AddPlaceholderChunk("args");
4355 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4356 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004357 SawLastInitializer? CCP_NextInitializer
4358 : CCP_MemberDeclaration));
4359 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004360 }
4361
4362 // Add completions for members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004363 for (auto *Field : ClassDecl->fields()) {
David Blaikie82e95a32014-11-19 07:49:47 +00004364 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4365 .second) {
Douglas Gregor99129ef2010-08-29 19:27:27 +00004366 SawLastInitializer
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00004367 = !Initializers.empty() &&
4368 Initializers.back()->isAnyMemberInitializer() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004369 Initializers.back()->getAnyMember() == Field;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004370 continue;
Douglas Gregor99129ef2010-08-29 19:27:27 +00004371 }
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004372
4373 if (!Field->getDeclName())
4374 continue;
4375
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00004376 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004377 Field->getIdentifier()->getName()));
4378 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4379 Builder.AddPlaceholderChunk("args");
4380 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4381 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor99129ef2010-08-29 19:27:27 +00004382 SawLastInitializer? CCP_NextInitializer
Douglas Gregorf3af3112010-09-09 21:42:20 +00004383 : CCP_MemberDeclaration,
Douglas Gregor78254c82012-03-27 23:34:16 +00004384 CXCursor_MemberRef,
4385 CXAvailability_Available,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004386 Field));
Douglas Gregor99129ef2010-08-29 19:27:27 +00004387 SawLastInitializer = false;
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004388 }
4389 Results.ExitScope();
4390
Douglas Gregor0ac41382010-09-23 23:01:17 +00004391 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregoreaeeca92010-08-28 00:00:50 +00004392 Results.data(), Results.size());
4393}
4394
Douglas Gregord8c61782012-02-15 15:34:24 +00004395/// \brief Determine whether this scope denotes a namespace.
4396static bool isNamespaceScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00004397 DeclContext *DC = S->getEntity();
Douglas Gregord8c61782012-02-15 15:34:24 +00004398 if (!DC)
4399 return false;
4400
4401 return DC->isFileContext();
4402}
4403
4404void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4405 bool AfterAmpersand) {
4406 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004407 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregord8c61782012-02-15 15:34:24 +00004408 CodeCompletionContext::CCC_Other);
4409 Results.EnterNewScope();
4410
4411 // Note what has already been captured.
4412 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4413 bool IncludedThis = false;
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004414 for (const auto &C : Intro.Captures) {
4415 if (C.Kind == LCK_This) {
Douglas Gregord8c61782012-02-15 15:34:24 +00004416 IncludedThis = true;
4417 continue;
4418 }
4419
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00004420 Known.insert(C.Id);
Douglas Gregord8c61782012-02-15 15:34:24 +00004421 }
4422
4423 // Look for other capturable variables.
4424 for (; S && !isNamespaceScope(S); S = S->getParent()) {
Aaron Ballman35c54952014-03-17 16:55:25 +00004425 for (const auto *D : S->decls()) {
4426 const auto *Var = dyn_cast<VarDecl>(D);
Douglas Gregord8c61782012-02-15 15:34:24 +00004427 if (!Var ||
4428 !Var->hasLocalStorage() ||
4429 Var->hasAttr<BlocksAttr>())
4430 continue;
4431
David Blaikie82e95a32014-11-19 07:49:47 +00004432 if (Known.insert(Var->getIdentifier()).second)
Douglas Gregor0a0e2b32013-01-31 04:52:16 +00004433 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
Craig Topperc3ec1492014-05-26 06:22:03 +00004434 CurContext, nullptr, false);
Douglas Gregord8c61782012-02-15 15:34:24 +00004435 }
4436 }
4437
4438 // Add 'this', if it would be valid.
4439 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4440 addThisCompletion(*this, Results);
4441
4442 Results.ExitScope();
4443
4444 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4445 Results.data(), Results.size());
4446}
4447
James Dennett596e4752012-06-14 03:11:41 +00004448/// Macro that optionally prepends an "@" to the string literal passed in via
4449/// Keyword, depending on whether NeedAt is true or false.
4450#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4451
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004452static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004453 ResultBuilder &Results,
4454 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004455 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004456 // Since we have an implementation, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004457 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004458
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004459 CodeCompletionBuilder Builder(Results.getAllocator(),
4460 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004461 if (LangOpts.ObjC2) {
4462 // @dynamic
James Dennett596e4752012-06-14 03:11:41 +00004463 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004464 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4465 Builder.AddPlaceholderChunk("property");
4466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004467
4468 // @synthesize
James Dennett596e4752012-06-14 03:11:41 +00004469 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004470 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4471 Builder.AddPlaceholderChunk("property");
4472 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004473 }
4474}
4475
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004476static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00004477 ResultBuilder &Results,
4478 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004479 typedef CodeCompletionResult Result;
Douglas Gregorf1934162010-01-13 21:24:21 +00004480
4481 // Since we have an interface or protocol, we can end it.
James Dennett596e4752012-06-14 03:11:41 +00004482 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004483
4484 if (LangOpts.ObjC2) {
4485 // @property
James Dennett596e4752012-06-14 03:11:41 +00004486 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004487
4488 // @required
James Dennett596e4752012-06-14 03:11:41 +00004489 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004490
4491 // @optional
James Dennett596e4752012-06-14 03:11:41 +00004492 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
Douglas Gregorf1934162010-01-13 21:24:21 +00004493 }
4494}
4495
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004496static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004497 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004498 CodeCompletionBuilder Builder(Results.getAllocator(),
4499 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004500
4501 // @class name ;
James Dennett596e4752012-06-14 03:11:41 +00004502 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004503 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4504 Builder.AddPlaceholderChunk("name");
4505 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004506
Douglas Gregorf4c33342010-05-28 00:22:41 +00004507 if (Results.includeCodePatterns()) {
4508 // @interface name
4509 // FIXME: Could introduce the whole pattern, including superclasses and
4510 // such.
James Dennett596e4752012-06-14 03:11:41 +00004511 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004512 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4513 Builder.AddPlaceholderChunk("class");
4514 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004515
Douglas Gregorf4c33342010-05-28 00:22:41 +00004516 // @protocol name
James Dennett596e4752012-06-14 03:11:41 +00004517 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004518 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4519 Builder.AddPlaceholderChunk("protocol");
4520 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004521
4522 // @implementation name
James Dennett596e4752012-06-14 03:11:41 +00004523 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004524 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4525 Builder.AddPlaceholderChunk("class");
4526 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004527 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004528
4529 // @compatibility_alias name
James Dennett596e4752012-06-14 03:11:41 +00004530 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4532 Builder.AddPlaceholderChunk("alias");
4533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4534 Builder.AddPlaceholderChunk("class");
4535 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor61e36812013-03-07 23:26:24 +00004536
4537 if (Results.getSema().getLangOpts().Modules) {
4538 // @import name
4539 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4540 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4541 Builder.AddPlaceholderChunk("module");
4542 Results.AddResult(Result(Builder.TakeString()));
4543 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004544}
4545
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004546void Sema::CodeCompleteObjCAtDirective(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004547 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004548 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004549 CodeCompletionContext::CCC_Other);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004550 Results.EnterNewScope();
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004551 if (isa<ObjCImplDecl>(CurContext))
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 AddObjCImplementationResults(getLangOpts(), Results, false);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004553 else if (CurContext->isObjCContainer())
David Blaikiebbafb8a2012-03-11 07:00:24 +00004554 AddObjCInterfaceResults(getLangOpts(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00004555 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004556 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00004557 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004558 HandleCodeCompleteResults(this, CodeCompleter,
4559 CodeCompletionContext::CCC_Other,
4560 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00004561}
4562
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004563static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004564 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004565 CodeCompletionBuilder Builder(Results.getAllocator(),
4566 Results.getCodeCompletionTUInfo());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004567
4568 // @encode ( type-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004569 const char *EncodeType = "char[]";
David Blaikiebbafb8a2012-03-11 07:00:24 +00004570 if (Results.getSema().getLangOpts().CPlusPlus ||
4571 Results.getSema().getLangOpts().ConstStrings)
Jordan Rose9da05852012-06-15 18:19:56 +00004572 EncodeType = "const char[]";
Douglas Gregore5c79d52011-10-18 21:20:17 +00004573 Builder.AddResultTypeChunk(EncodeType);
James Dennett596e4752012-06-14 03:11:41 +00004574 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004575 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4576 Builder.AddPlaceholderChunk("type-name");
4577 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4578 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004579
4580 // @protocol ( protocol-name )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004581 Builder.AddResultTypeChunk("Protocol *");
James Dennett596e4752012-06-14 03:11:41 +00004582 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4584 Builder.AddPlaceholderChunk("protocol-name");
4585 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4586 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004587
4588 // @selector ( selector )
Douglas Gregore5c79d52011-10-18 21:20:17 +00004589 Builder.AddResultTypeChunk("SEL");
James Dennett596e4752012-06-14 03:11:41 +00004590 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004591 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4592 Builder.AddPlaceholderChunk("selector");
4593 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4594 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004595
4596 // @"string"
4597 Builder.AddResultTypeChunk("NSString *");
4598 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4599 Builder.AddPlaceholderChunk("string");
4600 Builder.AddTextChunk("\"");
4601 Results.AddResult(Result(Builder.TakeString()));
4602
Douglas Gregor951de302012-07-17 23:24:47 +00004603 // @[objects, ...]
Jordan Rose9da05852012-06-15 18:19:56 +00004604 Builder.AddResultTypeChunk("NSArray *");
James Dennett596e4752012-06-14 03:11:41 +00004605 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004606 Builder.AddPlaceholderChunk("objects, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004607 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4608 Results.AddResult(Result(Builder.TakeString()));
4609
Douglas Gregor951de302012-07-17 23:24:47 +00004610 // @{key : object, ...}
Jordan Rose9da05852012-06-15 18:19:56 +00004611 Builder.AddResultTypeChunk("NSDictionary *");
James Dennett596e4752012-06-14 03:11:41 +00004612 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
Ted Kremeneke65b0862012-03-06 20:05:56 +00004613 Builder.AddPlaceholderChunk("key");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004614 Builder.AddChunk(CodeCompletionString::CK_Colon);
4615 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4616 Builder.AddPlaceholderChunk("object, ...");
Ted Kremeneke65b0862012-03-06 20:05:56 +00004617 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4618 Results.AddResult(Result(Builder.TakeString()));
Jordan Rose9da05852012-06-15 18:19:56 +00004619
Douglas Gregor951de302012-07-17 23:24:47 +00004620 // @(expression)
Jordan Rose9da05852012-06-15 18:19:56 +00004621 Builder.AddResultTypeChunk("id");
4622 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Jordan Rose9da05852012-06-15 18:19:56 +00004623 Builder.AddPlaceholderChunk("expression");
Jordan Rose9da05852012-06-15 18:19:56 +00004624 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4625 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004626}
4627
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004628static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004629 typedef CodeCompletionResult Result;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004630 CodeCompletionBuilder Builder(Results.getAllocator(),
4631 Results.getCodeCompletionTUInfo());
Douglas Gregorf1934162010-01-13 21:24:21 +00004632
Douglas Gregorf4c33342010-05-28 00:22:41 +00004633 if (Results.includeCodePatterns()) {
4634 // @try { statements } @catch ( declaration ) { statements } @finally
4635 // { statements }
James Dennett596e4752012-06-14 03:11:41 +00004636 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004637 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4638 Builder.AddPlaceholderChunk("statements");
4639 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4640 Builder.AddTextChunk("@catch");
4641 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4642 Builder.AddPlaceholderChunk("parameter");
4643 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4644 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4645 Builder.AddPlaceholderChunk("statements");
4646 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4647 Builder.AddTextChunk("@finally");
4648 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4649 Builder.AddPlaceholderChunk("statements");
4650 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4651 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004652 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004653
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004654 // @throw
James Dennett596e4752012-06-14 03:11:41 +00004655 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4657 Builder.AddPlaceholderChunk("expression");
4658 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf1934162010-01-13 21:24:21 +00004659
Douglas Gregorf4c33342010-05-28 00:22:41 +00004660 if (Results.includeCodePatterns()) {
4661 // @synchronized ( expression ) { statements }
James Dennett596e4752012-06-14 03:11:41 +00004662 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004663 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4664 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4665 Builder.AddPlaceholderChunk("expression");
4666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4667 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4668 Builder.AddPlaceholderChunk("statements");
4669 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4670 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorf4c33342010-05-28 00:22:41 +00004671 }
Douglas Gregorf1934162010-01-13 21:24:21 +00004672}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004673
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004674static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00004675 ResultBuilder &Results,
4676 bool NeedAt) {
John McCall276321a2010-08-25 06:19:51 +00004677 typedef CodeCompletionResult Result;
James Dennett596e4752012-06-14 03:11:41 +00004678 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4679 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4680 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004681 if (LangOpts.ObjC2)
James Dennett596e4752012-06-14 03:11:41 +00004682 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
Douglas Gregor48d46252010-01-13 21:54:15 +00004683}
4684
4685void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004686 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004687 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004688 CodeCompletionContext::CCC_Other);
Douglas Gregor48d46252010-01-13 21:54:15 +00004689 Results.EnterNewScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004690 AddObjCVisibilityResults(getLangOpts(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00004691 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004692 HandleCodeCompleteResults(this, CodeCompleter,
4693 CodeCompletionContext::CCC_Other,
4694 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00004695}
4696
4697void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004698 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004699 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004700 CodeCompletionContext::CCC_Other);
Douglas Gregorf1934162010-01-13 21:24:21 +00004701 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004702 AddObjCStatementResults(Results, false);
4703 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004704 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004705 HandleCodeCompleteResults(this, CodeCompleter,
4706 CodeCompletionContext::CCC_Other,
4707 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004708}
4709
4710void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004711 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004712 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004713 CodeCompletionContext::CCC_Other);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004714 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00004715 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004716 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004717 HandleCodeCompleteResults(this, CodeCompleter,
4718 CodeCompletionContext::CCC_Other,
4719 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00004720}
4721
Douglas Gregore6078da2009-11-19 00:14:45 +00004722/// \brief Determine whether the addition of the given flag to an Objective-C
4723/// property's attributes will cause a conflict.
Bill Wendling44426052012-12-20 19:22:21 +00004724static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
Douglas Gregore6078da2009-11-19 00:14:45 +00004725 // Check if we've already added this flag.
Bill Wendling44426052012-12-20 19:22:21 +00004726 if (Attributes & NewFlag)
Douglas Gregore6078da2009-11-19 00:14:45 +00004727 return true;
4728
Bill Wendling44426052012-12-20 19:22:21 +00004729 Attributes |= NewFlag;
Douglas Gregore6078da2009-11-19 00:14:45 +00004730
4731 // Check for collisions with "readonly".
Bill Wendling44426052012-12-20 19:22:21 +00004732 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4733 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregore6078da2009-11-19 00:14:45 +00004734 return true;
4735
Jordan Rose53cb2f32012-08-20 20:01:13 +00004736 // Check for more than one of { assign, copy, retain, strong, weak }.
Bill Wendling44426052012-12-20 19:22:21 +00004737 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCall31168b02011-06-15 23:02:42 +00004738 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregore6078da2009-11-19 00:14:45 +00004739 ObjCDeclSpec::DQ_PR_copy |
Jordan Rose53cb2f32012-08-20 20:01:13 +00004740 ObjCDeclSpec::DQ_PR_retain |
4741 ObjCDeclSpec::DQ_PR_strong |
4742 ObjCDeclSpec::DQ_PR_weak);
Douglas Gregore6078da2009-11-19 00:14:45 +00004743 if (AssignCopyRetMask &&
4744 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCall31168b02011-06-15 23:02:42 +00004745 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregore6078da2009-11-19 00:14:45 +00004746 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCall31168b02011-06-15 23:02:42 +00004747 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
Jordan Rose53cb2f32012-08-20 20:01:13 +00004748 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4749 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
Douglas Gregore6078da2009-11-19 00:14:45 +00004750 return true;
4751
4752 return false;
4753}
4754
Douglas Gregor36029f42009-11-18 23:08:07 +00004755void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00004756 if (!CodeCompleter)
4757 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004758
Bill Wendling44426052012-12-20 19:22:21 +00004759 unsigned Attributes = ODS.getPropertyAttributes();
Steve Naroff936354c2009-10-08 21:55:05 +00004760
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004761 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004762 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004763 CodeCompletionContext::CCC_Other);
Steve Naroff936354c2009-10-08 21:55:05 +00004764 Results.EnterNewScope();
Bill Wendling44426052012-12-20 19:22:21 +00004765 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall276321a2010-08-25 06:19:51 +00004766 Results.AddResult(CodeCompletionResult("readonly"));
Bill Wendling44426052012-12-20 19:22:21 +00004767 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall276321a2010-08-25 06:19:51 +00004768 Results.AddResult(CodeCompletionResult("assign"));
Bill Wendling44426052012-12-20 19:22:21 +00004769 if (!ObjCPropertyFlagConflicts(Attributes,
John McCall31168b02011-06-15 23:02:42 +00004770 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4771 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Bill Wendling44426052012-12-20 19:22:21 +00004772 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall276321a2010-08-25 06:19:51 +00004773 Results.AddResult(CodeCompletionResult("readwrite"));
Bill Wendling44426052012-12-20 19:22:21 +00004774 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall276321a2010-08-25 06:19:51 +00004775 Results.AddResult(CodeCompletionResult("retain"));
Bill Wendling44426052012-12-20 19:22:21 +00004776 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
John McCall31168b02011-06-15 23:02:42 +00004777 Results.AddResult(CodeCompletionResult("strong"));
Bill Wendling44426052012-12-20 19:22:21 +00004778 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall276321a2010-08-25 06:19:51 +00004779 Results.AddResult(CodeCompletionResult("copy"));
Bill Wendling44426052012-12-20 19:22:21 +00004780 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall276321a2010-08-25 06:19:51 +00004781 Results.AddResult(CodeCompletionResult("nonatomic"));
Bill Wendling44426052012-12-20 19:22:21 +00004782 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
Fariborz Jahanian1c2d29e2011-06-11 17:14:27 +00004783 Results.AddResult(CodeCompletionResult("atomic"));
Jordan Rose53cb2f32012-08-20 20:01:13 +00004784
4785 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
John McCall3deb1ad2012-08-21 02:47:43 +00004786 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
Bill Wendling44426052012-12-20 19:22:21 +00004787 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
Jordan Rose53cb2f32012-08-20 20:01:13 +00004788 Results.AddResult(CodeCompletionResult("weak"));
4789
Bill Wendling44426052012-12-20 19:22:21 +00004790 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004791 CodeCompletionBuilder Setter(Results.getAllocator(),
4792 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004793 Setter.AddTypedTextChunk("setter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004794 Setter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004795 Setter.AddPlaceholderChunk("method");
4796 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004797 }
Bill Wendling44426052012-12-20 19:22:21 +00004798 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004799 CodeCompletionBuilder Getter(Results.getAllocator(),
4800 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004801 Getter.AddTypedTextChunk("getter");
Argyrios Kyrtzidis7bbb8812014-02-20 07:55:15 +00004802 Getter.AddTextChunk("=");
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004803 Getter.AddPlaceholderChunk("method");
4804 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00004805 }
Steve Naroff936354c2009-10-08 21:55:05 +00004806 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004807 HandleCodeCompleteResults(this, CodeCompleter,
4808 CodeCompletionContext::CCC_Other,
4809 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00004810}
Steve Naroffeae65032009-11-07 02:08:14 +00004811
James Dennettf1243872012-06-17 05:33:25 +00004812/// \brief Describes the kind of Objective-C method that we want to find
Douglas Gregorc8537c52009-11-19 07:41:15 +00004813/// via code completion.
4814enum ObjCMethodKind {
Dmitri Gribenko4280e5c2012-06-08 23:13:42 +00004815 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4816 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4817 MK_OneArgSelector ///< One-argument selector.
Douglas Gregorc8537c52009-11-19 07:41:15 +00004818};
4819
Douglas Gregor67c692c2010-08-26 15:07:07 +00004820static bool isAcceptableObjCSelector(Selector Sel,
4821 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004822 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004823 bool AllowSameLength = true) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004824 unsigned NumSelIdents = SelIdents.size();
Douglas Gregor67c692c2010-08-26 15:07:07 +00004825 if (NumSelIdents > Sel.getNumArgs())
4826 return false;
4827
4828 switch (WantKind) {
4829 case MK_Any: break;
4830 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4831 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4832 }
4833
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004834 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4835 return false;
4836
Douglas Gregor67c692c2010-08-26 15:07:07 +00004837 for (unsigned I = 0; I != NumSelIdents; ++I)
4838 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4839 return false;
4840
4841 return true;
4842}
4843
Douglas Gregorc8537c52009-11-19 07:41:15 +00004844static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4845 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004846 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004847 bool AllowSameLength = true) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00004848 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004849 AllowSameLength);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004850}
Douglas Gregor1154e272010-09-16 16:06:31 +00004851
4852namespace {
4853 /// \brief A set of selectors, which is used to avoid introducing multiple
4854 /// completions with the same selector into the result set.
4855 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4856}
4857
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004858/// \brief Add all of the Objective-C methods in the given Objective-C
4859/// container to the set of results.
4860///
4861/// The container will be a class, protocol, category, or implementation of
4862/// any of the above. This mether will recurse to include methods from
4863/// the superclasses of classes along with their categories, protocols, and
4864/// implementations.
4865///
4866/// \param Container the container in which we'll look to find methods.
4867///
James Dennett596e4752012-06-14 03:11:41 +00004868/// \param WantInstanceMethods Whether to add instance methods (only); if
4869/// false, this routine will add factory methods (only).
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004870///
4871/// \param CurContext the context in which we're performing the lookup that
4872/// finds methods.
4873///
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004874/// \param AllowSameLength Whether we allow a method to be added to the list
4875/// when it has the same number of parameters as we have selector identifiers.
4876///
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004877/// \param Results the structure into which we'll add results.
4878static void AddObjCMethods(ObjCContainerDecl *Container,
4879 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00004880 ObjCMethodKind WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004881 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004882 DeclContext *CurContext,
Douglas Gregor1154e272010-09-16 16:06:31 +00004883 VisitedSelectorSet &Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004884 bool AllowSameLength,
Douglas Gregor416b5752010-08-25 01:08:01 +00004885 ResultBuilder &Results,
4886 bool InOriginalClass = true) {
John McCall276321a2010-08-25 06:19:51 +00004887 typedef CodeCompletionResult Result;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00004888 Container = getContainerDef(Container);
Douglas Gregor41778c32013-01-30 06:58:39 +00004889 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4890 bool isRootClass = IFace && !IFace->getSuperClass();
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004891 for (auto *M : Container->methods()) {
Douglas Gregor41778c32013-01-30 06:58:39 +00004892 // The instance methods on the root class can be messaged via the
4893 // metaclass.
4894 if (M->isInstanceMethod() == WantInstanceMethods ||
4895 (isRootClass && !WantInstanceMethods)) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00004896 // Check whether the selector identifiers we've been given are a
4897 // subset of the identifiers for this particular method.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004898 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
Douglas Gregor1b605f72009-11-19 01:08:35 +00004899 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00004900
David Blaikie82e95a32014-11-19 07:49:47 +00004901 if (!Selectors.insert(M->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00004902 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00004903
4904 Result R = Result(M, Results.getBasePriority(M), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004905 R.StartParameter = SelIdents.size();
Douglas Gregorc8537c52009-11-19 07:41:15 +00004906 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor416b5752010-08-25 01:08:01 +00004907 if (!InOriginalClass)
4908 R.Priority += CCD_InBaseClass;
Douglas Gregor1b605f72009-11-19 01:08:35 +00004909 Results.MaybeAddResult(R, CurContext);
4910 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004911 }
4912
Douglas Gregorf37c9492010-09-16 15:34:59 +00004913 // Visit the protocols of protocols.
4914 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004915 if (Protocol->hasDefinition()) {
4916 const ObjCList<ObjCProtocolDecl> &Protocols
4917 = Protocol->getReferencedProtocols();
4918 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4919 E = Protocols.end();
4920 I != E; ++I)
4921 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004922 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore6e48b12012-01-01 19:29:29 +00004923 }
Douglas Gregorf37c9492010-09-16 15:34:59 +00004924 }
4925
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004926 if (!IFace || !IFace->hasDefinition())
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004927 return;
4928
4929 // Add methods in protocols.
Aaron Ballmana49c5062014-03-13 20:29:09 +00004930 for (auto *I : IFace->protocols())
4931 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004932 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004933
4934 // Add methods in categories.
Aaron Ballman15063e12014-03-13 21:35:02 +00004935 for (auto *CatDecl : IFace->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004936 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004937 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004938 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004939
4940 // Add a categories protocol methods.
4941 const ObjCList<ObjCProtocolDecl> &Protocols
4942 = CatDecl->getReferencedProtocols();
4943 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4944 E = Protocols.end();
4945 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00004946 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004947 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004948 Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004949
4950 // Add methods in category implementations.
4951 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004952 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004953 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004954 Results, InOriginalClass);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004955 }
4956
4957 // Add methods in superclass.
4958 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004959 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004960 SelIdents, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004961 AllowSameLength, Results, false);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00004962
4963 // Add methods in our implementation, if any.
4964 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00004965 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004966 CurContext, Selectors, AllowSameLength,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004967 Results, InOriginalClass);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004968}
4969
4970
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004971void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00004972 // Try to find the interface where getters might live.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004973 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004974 if (!Class) {
4975 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004976 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00004977 Class = Category->getClassInterface();
4978
4979 if (!Class)
4980 return;
4981 }
4982
4983 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004984 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00004985 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00004986 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004987 Results.EnterNewScope();
4988
Douglas Gregor1154e272010-09-16 16:06:31 +00004989 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00004990 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00004991 /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00004992 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004993 HandleCodeCompleteResults(this, CodeCompleter,
4994 CodeCompletionContext::CCC_Other,
4995 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00004996}
4997
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004998void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00004999 // Try to find the interface where setters might live.
5000 ObjCInterfaceDecl *Class
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005001 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005002 if (!Class) {
5003 if (ObjCCategoryDecl *Category
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005004 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregorc8537c52009-11-19 07:41:15 +00005005 Class = Category->getClassInterface();
5006
5007 if (!Class)
5008 return;
5009 }
5010
5011 // Find all of the potential getters.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005012 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005013 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005014 CodeCompletionContext::CCC_Other);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005015 Results.EnterNewScope();
5016
Douglas Gregor1154e272010-09-16 16:06:31 +00005017 VisitedSelectorSet Selectors;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005018 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005019 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregorc8537c52009-11-19 07:41:15 +00005020
5021 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005022 HandleCodeCompleteResults(this, CodeCompleter,
5023 CodeCompletionContext::CCC_Other,
5024 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005025}
5026
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005027void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5028 bool IsParameter) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005029 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005030 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005031 CodeCompletionContext::CCC_Type);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005032 Results.EnterNewScope();
5033
5034 // Add context-sensitive, Objective-C parameter-passing keywords.
5035 bool AddedInOut = false;
5036 if ((DS.getObjCDeclQualifier() &
5037 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5038 Results.AddResult("in");
5039 Results.AddResult("inout");
5040 AddedInOut = true;
5041 }
5042 if ((DS.getObjCDeclQualifier() &
5043 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5044 Results.AddResult("out");
5045 if (!AddedInOut)
5046 Results.AddResult("inout");
5047 }
5048 if ((DS.getObjCDeclQualifier() &
5049 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5050 ObjCDeclSpec::DQ_Oneway)) == 0) {
5051 Results.AddResult("bycopy");
5052 Results.AddResult("byref");
5053 Results.AddResult("oneway");
5054 }
5055
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005056 // If we're completing the return type of an Objective-C method and the
5057 // identifier IBAction refers to a macro, provide a completion item for
5058 // an action, e.g.,
5059 // IBAction)<#selector#>:(id)sender
5060 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5061 Context.Idents.get("IBAction").hasMacroDefinition()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005062 CodeCompletionBuilder Builder(Results.getAllocator(),
5063 Results.getCodeCompletionTUInfo(),
5064 CCP_CodePattern, CXAvailability_Available);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005065 Builder.AddTypedTextChunk("IBAction");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005066 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005067 Builder.AddPlaceholderChunk("selector");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005068 Builder.AddChunk(CodeCompletionString::CK_Colon);
5069 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005070 Builder.AddTextChunk("id");
Benjamin Kramerdb534a42012-03-26 16:57:36 +00005071 Builder.AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005072 Builder.AddTextChunk("sender");
5073 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5074 }
Douglas Gregored1f5972013-01-30 07:11:43 +00005075
5076 // If we're completing the return type, provide 'instancetype'.
5077 if (!IsParameter) {
5078 Results.AddResult(CodeCompletionResult("instancetype"));
5079 }
Douglas Gregorf34a6f02011-02-15 22:19:42 +00005080
Douglas Gregor99fa2642010-08-24 01:06:58 +00005081 // Add various builtin type names and specifiers.
5082 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5083 Results.ExitScope();
5084
5085 // Add the various type names
5086 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5087 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5088 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5089 CodeCompleter->includeGlobals());
5090
5091 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005092 AddMacroResults(PP, Results, false);
Douglas Gregor99fa2642010-08-24 01:06:58 +00005093
5094 HandleCodeCompleteResults(this, CodeCompleter,
5095 CodeCompletionContext::CCC_Type,
5096 Results.data(), Results.size());
5097}
5098
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005099/// \brief When we have an expression with type "id", we may assume
5100/// that it has some more-specific class type based on knowledge of
5101/// common uses of Objective-C. This routine returns that class type,
5102/// or NULL if no better result could be determined.
5103static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregored0b69d2010-09-15 16:23:04 +00005104 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005105 if (!Msg)
Craig Topperc3ec1492014-05-26 06:22:03 +00005106 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005107
5108 Selector Sel = Msg->getSelector();
5109 if (Sel.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00005110 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005111
5112 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5113 if (!Id)
Craig Topperc3ec1492014-05-26 06:22:03 +00005114 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005115
5116 ObjCMethodDecl *Method = Msg->getMethodDecl();
5117 if (!Method)
Craig Topperc3ec1492014-05-26 06:22:03 +00005118 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005119
5120 // Determine the class that we're sending the message to.
Craig Topperc3ec1492014-05-26 06:22:03 +00005121 ObjCInterfaceDecl *IFace = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +00005122 switch (Msg->getReceiverKind()) {
5123 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00005124 if (const ObjCObjectType *ObjType
5125 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5126 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00005127 break;
5128
5129 case ObjCMessageExpr::Instance: {
5130 QualType T = Msg->getInstanceReceiver()->getType();
5131 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5132 IFace = Ptr->getInterfaceDecl();
5133 break;
5134 }
5135
5136 case ObjCMessageExpr::SuperInstance:
5137 case ObjCMessageExpr::SuperClass:
5138 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005139 }
5140
5141 if (!IFace)
Craig Topperc3ec1492014-05-26 06:22:03 +00005142 return nullptr;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005143
5144 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5145 if (Method->isInstanceMethod())
5146 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5147 .Case("retain", IFace)
John McCall31168b02011-06-15 23:02:42 +00005148 .Case("strong", IFace)
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005149 .Case("autorelease", IFace)
5150 .Case("copy", IFace)
5151 .Case("copyWithZone", IFace)
5152 .Case("mutableCopy", IFace)
5153 .Case("mutableCopyWithZone", IFace)
5154 .Case("awakeFromCoder", IFace)
5155 .Case("replacementObjectFromCoder", IFace)
5156 .Case("class", IFace)
5157 .Case("classForCoder", IFace)
5158 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005159 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005160
5161 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5162 .Case("new", IFace)
5163 .Case("alloc", IFace)
5164 .Case("allocWithZone", IFace)
5165 .Case("class", IFace)
5166 .Case("superclass", Super)
Craig Topperc3ec1492014-05-26 06:22:03 +00005167 .Default(nullptr);
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005168}
5169
Douglas Gregor6fc04132010-08-27 15:10:57 +00005170// Add a special completion for a message send to "super", which fills in the
5171// most likely case of forwarding all of our arguments to the superclass
5172// function.
5173///
5174/// \param S The semantic analysis object.
5175///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005176/// \param NeedSuperKeyword Whether we need to prefix this completion with
Douglas Gregor6fc04132010-08-27 15:10:57 +00005177/// the "super" keyword. Otherwise, we just need to provide the arguments.
5178///
5179/// \param SelIdents The identifiers in the selector that have already been
5180/// provided as arguments for a send to "super".
5181///
Douglas Gregor6fc04132010-08-27 15:10:57 +00005182/// \param Results The set of results to augment.
5183///
5184/// \returns the Objective-C method declaration that would be invoked by
5185/// this "super" completion. If NULL, no completion was added.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005186static ObjCMethodDecl *AddSuperSendCompletion(
5187 Sema &S, bool NeedSuperKeyword,
5188 ArrayRef<IdentifierInfo *> SelIdents,
5189 ResultBuilder &Results) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005190 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5191 if (!CurMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005192 return nullptr;
5193
Douglas Gregor6fc04132010-08-27 15:10:57 +00005194 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5195 if (!Class)
Craig Topperc3ec1492014-05-26 06:22:03 +00005196 return nullptr;
5197
Douglas Gregor6fc04132010-08-27 15:10:57 +00005198 // Try to find a superclass method with the same selector.
Craig Topperc3ec1492014-05-26 06:22:03 +00005199 ObjCMethodDecl *SuperMethod = nullptr;
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005200 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5201 // Check in the class
Douglas Gregor6fc04132010-08-27 15:10:57 +00005202 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5203 CurMethod->isInstanceMethod());
5204
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005205 // Check in categories or class extensions.
5206 if (!SuperMethod) {
Aaron Ballman15063e12014-03-13 21:35:02 +00005207 for (const auto *Cat : Class->known_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005208 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005209 CurMethod->isInstanceMethod())))
5210 break;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005211 }
Douglas Gregorb5f1e462011-02-16 00:51:18 +00005212 }
5213 }
5214
Douglas Gregor6fc04132010-08-27 15:10:57 +00005215 if (!SuperMethod)
Craig Topperc3ec1492014-05-26 06:22:03 +00005216 return nullptr;
5217
Douglas Gregor6fc04132010-08-27 15:10:57 +00005218 // Check whether the superclass method has the same signature.
5219 if (CurMethod->param_size() != SuperMethod->param_size() ||
5220 CurMethod->isVariadic() != SuperMethod->isVariadic())
Craig Topperc3ec1492014-05-26 06:22:03 +00005221 return nullptr;
5222
Douglas Gregor6fc04132010-08-27 15:10:57 +00005223 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5224 CurPEnd = CurMethod->param_end(),
5225 SuperP = SuperMethod->param_begin();
5226 CurP != CurPEnd; ++CurP, ++SuperP) {
5227 // Make sure the parameter types are compatible.
5228 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5229 (*SuperP)->getType()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005230 return nullptr;
5231
Douglas Gregor6fc04132010-08-27 15:10:57 +00005232 // Make sure we have a parameter name to forward!
5233 if (!(*CurP)->getIdentifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00005234 return nullptr;
Douglas Gregor6fc04132010-08-27 15:10:57 +00005235 }
5236
5237 // We have a superclass method. Now, form the send-to-super completion.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005238 CodeCompletionBuilder Builder(Results.getAllocator(),
5239 Results.getCodeCompletionTUInfo());
Douglas Gregor6fc04132010-08-27 15:10:57 +00005240
5241 // Give this completion a return type.
Douglas Gregor75acd922011-09-27 23:30:47 +00005242 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5243 Builder);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005244
5245 // If we need the "super" keyword, add it (plus some spacing).
5246 if (NeedSuperKeyword) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005247 Builder.AddTypedTextChunk("super");
5248 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005249 }
5250
5251 Selector Sel = CurMethod->getSelector();
5252 if (Sel.isUnarySelector()) {
5253 if (NeedSuperKeyword)
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005254 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005255 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005256 else
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005257 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005258 Sel.getNameForSlot(0)));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005259 } else {
5260 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5261 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005262 if (I > SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005263 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005264
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005265 if (I < SelIdents.size())
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005266 Builder.AddInformativeChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005267 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005268 Sel.getNameForSlot(I) + ":"));
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005269 else if (NeedSuperKeyword || I > SelIdents.size()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005270 Builder.AddTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005271 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005272 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005273 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005274 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005275 } else {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005276 Builder.AddTypedTextChunk(
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005277 Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005278 Sel.getNameForSlot(I) + ":"));
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005279 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005280 (*CurP)->getIdentifier()->getName()));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005281 }
5282 }
5283 }
5284
Douglas Gregor78254c82012-03-27 23:34:16 +00005285 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5286 CCP_SuperCompletion));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005287 return SuperMethod;
5288}
5289
Douglas Gregora817a192010-05-27 23:06:34 +00005290void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall276321a2010-08-25 06:19:51 +00005291 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005292 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005293 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005294 CodeCompletionContext::CCC_ObjCMessageReceiver,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005295 getLangOpts().CPlusPlus11
Douglas Gregord8c61782012-02-15 15:34:24 +00005296 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5297 : &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregora817a192010-05-27 23:06:34 +00005298
Douglas Gregora817a192010-05-27 23:06:34 +00005299 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5300 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00005301 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5302 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00005303
5304 // If we are in an Objective-C method inside a class that has a superclass,
5305 // add "super" as an option.
5306 if (ObjCMethodDecl *Method = getCurMethodDecl())
5307 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor6fc04132010-08-27 15:10:57 +00005308 if (Iface->getSuperClass()) {
Douglas Gregora817a192010-05-27 23:06:34 +00005309 Results.AddResult(Result("super"));
Douglas Gregor6fc04132010-08-27 15:10:57 +00005310
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005311 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
Douglas Gregor6fc04132010-08-27 15:10:57 +00005312 }
Douglas Gregora817a192010-05-27 23:06:34 +00005313
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005314 if (getLangOpts().CPlusPlus11)
Douglas Gregord8c61782012-02-15 15:34:24 +00005315 addThisCompletion(*this, Results);
5316
Douglas Gregora817a192010-05-27 23:06:34 +00005317 Results.ExitScope();
5318
5319 if (CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00005320 AddMacroResults(PP, Results, false);
Douglas Gregor50832e02010-09-20 22:39:41 +00005321 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005322 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00005323
5324}
5325
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005326void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005327 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005328 bool AtArgumentExpression) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005329 ObjCInterfaceDecl *CDecl = nullptr;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005330 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5331 // Figure out which interface we're in.
5332 CDecl = CurMethod->getClassInterface();
5333 if (!CDecl)
5334 return;
5335
5336 // Find the superclass of this class.
5337 CDecl = CDecl->getSuperClass();
5338 if (!CDecl)
5339 return;
5340
5341 if (CurMethod->isInstanceMethod()) {
5342 // We are inside an instance method, which means that the message
5343 // send [super ...] is actually calling an instance method on the
Douglas Gregor392a84b2010-10-13 21:24:53 +00005344 // current object.
Craig Topperc3ec1492014-05-26 06:22:03 +00005345 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005346 AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005347 CDecl);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005348 }
5349
5350 // Fall through to send to the superclass in CDecl.
5351 } else {
5352 // "super" may be the name of a type or variable. Figure out which
5353 // it is.
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00005354 IdentifierInfo *Super = getSuperIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005355 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5356 LookupOrdinaryName);
5357 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5358 // "super" names an interface. Use it.
5359 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00005360 if (const ObjCObjectType *Iface
5361 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5362 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005363 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5364 // "super" names an unresolved type; we can't be more specific.
5365 } else {
5366 // Assume that "super" names some kind of value and parse that way.
5367 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +00005368 SourceLocation TemplateKWLoc;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005369 UnqualifiedId id;
5370 id.setIdentifier(Super, SuperLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00005371 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5372 false, false);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005373 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005374 SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005375 AtArgumentExpression);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005376 }
5377
5378 // Fall through
5379 }
5380
John McCallba7bf592010-08-24 05:47:05 +00005381 ParsedType Receiver;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005382 if (CDecl)
John McCallba7bf592010-08-24 05:47:05 +00005383 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005384 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005385 AtArgumentExpression,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005386 /*IsSuper=*/true);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005387}
5388
Douglas Gregor74661272010-09-21 00:03:25 +00005389/// \brief Given a set of code-completion results for the argument of a message
5390/// send, determine the preferred type (if any) for that argument expression.
5391static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5392 unsigned NumSelIdents) {
5393 typedef CodeCompletionResult Result;
5394 ASTContext &Context = Results.getSema().Context;
5395
5396 QualType PreferredType;
5397 unsigned BestPriority = CCP_Unlikely * 2;
5398 Result *ResultsData = Results.data();
5399 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5400 Result &R = ResultsData[I];
5401 if (R.Kind == Result::RK_Declaration &&
5402 isa<ObjCMethodDecl>(R.Declaration)) {
5403 if (R.Priority <= BestPriority) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005404 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
Douglas Gregor74661272010-09-21 00:03:25 +00005405 if (NumSelIdents <= Method->param_size()) {
Alp Toker03376dc2014-07-07 09:02:20 +00005406 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
Douglas Gregor74661272010-09-21 00:03:25 +00005407 ->getType();
5408 if (R.Priority < BestPriority || PreferredType.isNull()) {
5409 BestPriority = R.Priority;
5410 PreferredType = MyPreferredType;
5411 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5412 MyPreferredType)) {
5413 PreferredType = QualType();
5414 }
5415 }
5416 }
5417 }
5418 }
5419
5420 return PreferredType;
5421}
5422
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005423static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5424 ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005425 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005426 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005427 bool IsSuper,
5428 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005429 typedef CodeCompletionResult Result;
Craig Topperc3ec1492014-05-26 06:22:03 +00005430 ObjCInterfaceDecl *CDecl = nullptr;
5431
Douglas Gregor8ce33212009-11-17 17:59:40 +00005432 // If the given name refers to an interface type, retrieve the
5433 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005434 if (Receiver) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005435 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005436 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00005437 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5438 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00005439 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005440
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005441 // Add all of the factory methods in this Objective-C class, its protocols,
5442 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00005443 Results.EnterNewScope();
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005444
Douglas Gregor6fc04132010-08-27 15:10:57 +00005445 // If this is a send-to-super, try to add the special "super" send
5446 // completion.
5447 if (IsSuper) {
5448 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005449 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005450 Results.Ignore(SuperMethod);
5451 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005452
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005453 // If we're inside an Objective-C method definition, prefer its selector to
5454 // others.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005455 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005456 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005457
Douglas Gregor1154e272010-09-16 16:06:31 +00005458 VisitedSelectorSet Selectors;
Douglas Gregor6285f752010-04-06 16:40:00 +00005459 if (CDecl)
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005460 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005461 SemaRef.CurContext, Selectors, AtArgumentExpression,
5462 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00005463 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00005464 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005465
Douglas Gregord720daf2010-04-06 17:30:22 +00005466 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005467 // pool from the AST file.
Axel Naumanndd433f02012-10-18 19:05:02 +00005468 if (SemaRef.getExternalSource()) {
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005469 for (uint32_t I = 0,
Axel Naumanndd433f02012-10-18 19:05:02 +00005470 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
John McCall75b960e2010-06-01 09:23:16 +00005471 I != N; ++I) {
Axel Naumanndd433f02012-10-18 19:05:02 +00005472 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005473 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005474 continue;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005475
5476 SemaRef.ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005477 }
5478 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005479
5480 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5481 MEnd = SemaRef.MethodPool.end();
Sebastian Redl75d8a322010-08-02 23:18:59 +00005482 M != MEnd; ++M) {
5483 for (ObjCMethodList *MethList = &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005484 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005485 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005486 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005487 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005488
Nico Weber2e0c8f72014-12-27 03:58:08 +00005489 Result R(MethList->getMethod(),
5490 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005491 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005492 R.AllParametersAreInformative = false;
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005493 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor6285f752010-04-06 16:40:00 +00005494 }
5495 }
5496 }
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005497
5498 Results.ExitScope();
5499}
Douglas Gregor6285f752010-04-06 16:40:00 +00005500
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005501void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005502 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005503 bool AtArgumentExpression,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00005504 bool IsSuper) {
Douglas Gregor63745d52011-07-21 01:05:26 +00005505
5506 QualType T = this->GetTypeFromParser(Receiver);
5507
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005508 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005509 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005510 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005511 T, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005512
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005513 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005514 AtArgumentExpression, IsSuper, Results);
Douglas Gregor74661272010-09-21 00:03:25 +00005515
5516 // If we're actually at the argument expression (rather than prior to the
5517 // selector), we're actually performing code completion for an expression.
5518 // Determine whether we have a single, best method. If so, we can
5519 // code-complete the expression using the corresponding parameter type as
5520 // our preferred type, improving completion results.
5521 if (AtArgumentExpression) {
5522 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005523 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005524 if (PreferredType.isNull())
5525 CodeCompleteOrdinaryName(S, PCC_Expression);
5526 else
5527 CodeCompleteExpression(S, PreferredType);
5528 return;
5529 }
5530
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005531 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005532 Results.getCompletionContext(),
Douglas Gregor6fc04132010-08-27 15:10:57 +00005533 Results.data(), Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005534}
5535
Richard Trieu2bd04012011-09-09 02:00:50 +00005536void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005537 ArrayRef<IdentifierInfo *> SelIdents,
Douglas Gregorf86e4da2010-09-20 23:34:21 +00005538 bool AtArgumentExpression,
Douglas Gregor392a84b2010-10-13 21:24:53 +00005539 ObjCInterfaceDecl *Super) {
John McCall276321a2010-08-25 06:19:51 +00005540 typedef CodeCompletionResult Result;
Steve Naroffeae65032009-11-07 02:08:14 +00005541
5542 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00005543
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005544 // If necessary, apply function/array conversion to the receiver.
5545 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00005546 if (RecExpr) {
5547 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5548 if (Conv.isInvalid()) // conversion failed. bail.
5549 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005550 RecExpr = Conv.get();
John Wiegley01296292011-04-08 18:41:53 +00005551 }
Douglas Gregor392a84b2010-10-13 21:24:53 +00005552 QualType ReceiverType = RecExpr? RecExpr->getType()
5553 : Super? Context.getObjCObjectPointerType(
5554 Context.getObjCInterfaceType(Super))
5555 : Context.getObjCIdType();
Steve Naroffeae65032009-11-07 02:08:14 +00005556
Douglas Gregordc520b02010-11-08 21:12:30 +00005557 // If we're messaging an expression with type "id" or "Class", check
5558 // whether we know something special about the receiver that allows
5559 // us to assume a more-specific receiver type.
Anders Carlsson382ba412014-02-28 19:07:22 +00005560 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
Douglas Gregordc520b02010-11-08 21:12:30 +00005561 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5562 if (ReceiverType->isObjCClassType())
5563 return CodeCompleteObjCClassMessage(S,
5564 ParsedType::make(Context.getObjCInterfaceType(IFace)),
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005565 SelIdents,
Douglas Gregordc520b02010-11-08 21:12:30 +00005566 AtArgumentExpression, Super);
5567
5568 ReceiverType = Context.getObjCObjectPointerType(
5569 Context.getObjCInterfaceType(IFace));
5570 }
Anders Carlsson382ba412014-02-28 19:07:22 +00005571 } else if (RecExpr && getLangOpts().CPlusPlus) {
5572 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5573 if (Conv.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005574 RecExpr = Conv.get();
Anders Carlsson382ba412014-02-28 19:07:22 +00005575 ReceiverType = RecExpr->getType();
5576 }
5577 }
Douglas Gregordc520b02010-11-08 21:12:30 +00005578
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005579 // Build the set of methods we can see.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005580 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005581 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor63745d52011-07-21 01:05:26 +00005582 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005583 ReceiverType, SelIdents));
Douglas Gregor63745d52011-07-21 01:05:26 +00005584
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005585 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00005586
Douglas Gregor6fc04132010-08-27 15:10:57 +00005587 // If this is a send-to-super, try to add the special "super" send
5588 // completion.
Douglas Gregor392a84b2010-10-13 21:24:53 +00005589 if (Super) {
Douglas Gregor6fc04132010-08-27 15:10:57 +00005590 if (ObjCMethodDecl *SuperMethod
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005591 = AddSuperSendCompletion(*this, false, SelIdents, Results))
Douglas Gregor6fc04132010-08-27 15:10:57 +00005592 Results.Ignore(SuperMethod);
5593 }
5594
Douglas Gregorc2cb2e22010-08-27 15:29:55 +00005595 // If we're inside an Objective-C method definition, prefer its selector to
5596 // others.
5597 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5598 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00005599
Douglas Gregor1154e272010-09-16 16:06:31 +00005600 // Keep track of the selectors we've already added.
5601 VisitedSelectorSet Selectors;
5602
Douglas Gregora3329fa2009-11-18 00:06:18 +00005603 // Handle messages to Class. This really isn't a message to an instance
5604 // method, so we treat it the same way we would treat a message send to a
5605 // class method.
5606 if (ReceiverType->isObjCClassType() ||
5607 ReceiverType->isObjCQualifiedClassType()) {
5608 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5609 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005610 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005611 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005612 }
5613 }
5614 // Handle messages to a qualified ID ("id<foo>").
5615 else if (const ObjCObjectPointerType *QualID
5616 = ReceiverType->getAsObjCQualifiedIdType()) {
5617 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005618 for (auto *I : QualID->quals())
5619 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005620 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005621 }
5622 // Handle messages to a pointer to interface type.
5623 else if (const ObjCObjectPointerType *IFacePtr
5624 = ReceiverType->getAsObjCInterfacePointerType()) {
5625 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00005626 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005627 CurContext, Selectors, AtArgumentExpression,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005628 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005629
5630 // Search protocols for instance methods.
Aaron Ballman83731462014-03-17 16:14:00 +00005631 for (auto *I : IFacePtr->quals())
5632 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
Douglas Gregorb4a7c032010-11-17 21:36:08 +00005633 Selectors, AtArgumentExpression, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00005634 }
Douglas Gregor6285f752010-04-06 16:40:00 +00005635 // Handle messages to "id".
5636 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005637 // We're messaging "id", so provide all instance methods we know
5638 // about as code-completion results.
5639
5640 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005641 // pool from the AST file.
Douglas Gregord720daf2010-04-06 17:30:22 +00005642 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00005643 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5644 I != N; ++I) {
5645 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00005646 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00005647 continue;
5648
Sebastian Redl75d8a322010-08-02 23:18:59 +00005649 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00005650 }
5651 }
5652
Sebastian Redl75d8a322010-08-02 23:18:59 +00005653 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5654 MEnd = MethodPool.end();
5655 M != MEnd; ++M) {
5656 for (ObjCMethodList *MethList = &M->second.first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00005657 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00005658 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00005659 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor6285f752010-04-06 16:40:00 +00005660 continue;
Douglas Gregor1154e272010-09-16 16:06:31 +00005661
Nico Weber2e0c8f72014-12-27 03:58:08 +00005662 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
Douglas Gregor1154e272010-09-16 16:06:31 +00005663 continue;
Craig Topperc3ec1492014-05-26 06:22:03 +00005664
Nico Weber2e0c8f72014-12-27 03:58:08 +00005665 Result R(MethList->getMethod(),
5666 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005667 R.StartParameter = SelIdents.size();
Douglas Gregor6285f752010-04-06 16:40:00 +00005668 R.AllParametersAreInformative = false;
5669 Results.MaybeAddResult(R, CurContext);
5670 }
5671 }
5672 }
Steve Naroffeae65032009-11-07 02:08:14 +00005673 Results.ExitScope();
Douglas Gregor74661272010-09-21 00:03:25 +00005674
5675
5676 // If we're actually at the argument expression (rather than prior to the
5677 // selector), we're actually performing code completion for an expression.
5678 // Determine whether we have a single, best method. If so, we can
5679 // code-complete the expression using the corresponding parameter type as
5680 // our preferred type, improving completion results.
5681 if (AtArgumentExpression) {
5682 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005683 SelIdents.size());
Douglas Gregor74661272010-09-21 00:03:25 +00005684 if (PreferredType.isNull())
5685 CodeCompleteOrdinaryName(S, PCC_Expression);
5686 else
5687 CodeCompleteExpression(S, PreferredType);
5688 return;
5689 }
5690
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005691 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor63745d52011-07-21 01:05:26 +00005692 Results.getCompletionContext(),
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005693 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00005694}
Douglas Gregorbaf69612009-11-18 04:19:12 +00005695
Douglas Gregor68762e72010-08-23 21:17:50 +00005696void Sema::CodeCompleteObjCForCollection(Scope *S,
5697 DeclGroupPtrTy IterationVar) {
5698 CodeCompleteExpressionData Data;
5699 Data.ObjCCollection = true;
5700
5701 if (IterationVar.getAsOpaquePtr()) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00005702 DeclGroupRef DG = IterationVar.get();
Douglas Gregor68762e72010-08-23 21:17:50 +00005703 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5704 if (*I)
5705 Data.IgnoreDecls.push_back(*I);
5706 }
5707 }
5708
5709 CodeCompleteExpression(S, Data);
5710}
5711
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005712void Sema::CodeCompleteObjCSelector(Scope *S,
5713 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor67c692c2010-08-26 15:07:07 +00005714 // If we have an external source, load the entire class method
5715 // pool from the AST file.
5716 if (ExternalSource) {
5717 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5718 I != N; ++I) {
5719 Selector Sel = ExternalSource->GetExternalSelector(I);
5720 if (Sel.isNull() || MethodPool.count(Sel))
5721 continue;
5722
5723 ReadMethodPool(Sel);
5724 }
5725 }
5726
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005727 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005728 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005729 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor67c692c2010-08-26 15:07:07 +00005730 Results.EnterNewScope();
5731 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5732 MEnd = MethodPool.end();
5733 M != MEnd; ++M) {
5734
5735 Selector Sel = M->first;
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005736 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
Douglas Gregor67c692c2010-08-26 15:07:07 +00005737 continue;
5738
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005739 CodeCompletionBuilder Builder(Results.getAllocator(),
5740 Results.getCodeCompletionTUInfo());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005741 if (Sel.isUnarySelector()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005742 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00005743 Sel.getNameForSlot(0)));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005744 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005745 continue;
5746 }
5747
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005748 std::string Accumulator;
Douglas Gregor67c692c2010-08-26 15:07:07 +00005749 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00005750 if (I == SelIdents.size()) {
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005751 if (!Accumulator.empty()) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005752 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005753 Accumulator));
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005754 Accumulator.clear();
5755 }
5756 }
5757
Benjamin Kramer632500c2011-07-26 16:59:25 +00005758 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor9ac1ad12010-08-26 16:46:39 +00005759 Accumulator += ':';
Douglas Gregor67c692c2010-08-26 15:07:07 +00005760 }
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00005761 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005762 Results.AddResult(Builder.TakeString());
Douglas Gregor67c692c2010-08-26 15:07:07 +00005763 }
5764 Results.ExitScope();
5765
5766 HandleCodeCompleteResults(this, CodeCompleter,
5767 CodeCompletionContext::CCC_SelectorName,
5768 Results.data(), Results.size());
5769}
5770
Douglas Gregorbaf69612009-11-18 04:19:12 +00005771/// \brief Add all of the protocol declarations that we find in the given
5772/// (translation unit) context.
5773static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005774 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00005775 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005776 typedef CodeCompletionResult Result;
Douglas Gregorbaf69612009-11-18 04:19:12 +00005777
Aaron Ballman629afae2014-03-07 19:56:05 +00005778 for (const auto *D : Ctx->decls()) {
Douglas Gregorbaf69612009-11-18 04:19:12 +00005779 // Record any protocols we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005780 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
Douglas Gregore6e48b12012-01-01 19:29:29 +00005781 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00005782 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5783 CurContext, nullptr, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005784 }
5785}
5786
5787void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5788 unsigned NumProtocols) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005789 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005790 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005791 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005792
Douglas Gregora3b23b02010-12-09 21:44:02 +00005793 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5794 Results.EnterNewScope();
5795
5796 // Tell the result set to ignore all of the protocols we have
5797 // already seen.
5798 // FIXME: This doesn't work when caching code-completion results.
5799 for (unsigned I = 0; I != NumProtocols; ++I)
5800 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5801 Protocols[I].second))
5802 Results.Ignore(Protocol);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005803
Douglas Gregora3b23b02010-12-09 21:44:02 +00005804 // Add all protocols.
5805 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5806 Results);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005807
Douglas Gregora3b23b02010-12-09 21:44:02 +00005808 Results.ExitScope();
5809 }
5810
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005811 HandleCodeCompleteResults(this, CodeCompleter,
5812 CodeCompletionContext::CCC_ObjCProtocolName,
5813 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005814}
5815
5816void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005817 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005818 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005819 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor5b4671c2009-11-18 04:49:41 +00005820
Douglas Gregora3b23b02010-12-09 21:44:02 +00005821 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5822 Results.EnterNewScope();
5823
5824 // Add all protocols.
5825 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5826 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00005827
Douglas Gregora3b23b02010-12-09 21:44:02 +00005828 Results.ExitScope();
5829 }
5830
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005831 HandleCodeCompleteResults(this, CodeCompleter,
5832 CodeCompletionContext::CCC_ObjCProtocolName,
5833 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00005834}
Douglas Gregor49c22a72009-11-18 16:26:39 +00005835
5836/// \brief Add all of the Objective-C interface declarations that we find in
5837/// the given (translation unit) context.
5838static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5839 bool OnlyForwardDeclarations,
5840 bool OnlyUnimplemented,
5841 ResultBuilder &Results) {
John McCall276321a2010-08-25 06:19:51 +00005842 typedef CodeCompletionResult Result;
Douglas Gregor49c22a72009-11-18 16:26:39 +00005843
Aaron Ballman629afae2014-03-07 19:56:05 +00005844 for (const auto *D : Ctx->decls()) {
Douglas Gregor1c283312010-08-11 12:19:30 +00005845 // Record any interfaces we find.
Aaron Ballman629afae2014-03-07 19:56:05 +00005846 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
Douglas Gregordc9166c2011-12-15 20:29:51 +00005847 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregor1c283312010-08-11 12:19:30 +00005848 (!OnlyUnimplemented || !Class->getImplementation()))
Craig Topperc3ec1492014-05-26 06:22:03 +00005849 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5850 CurContext, nullptr, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005851 }
5852}
5853
5854void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005855 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005856 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005857 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005858 Results.EnterNewScope();
5859
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005860 if (CodeCompleter->includeGlobals()) {
5861 // Add all classes.
5862 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5863 false, Results);
5864 }
5865
Douglas Gregor49c22a72009-11-18 16:26:39 +00005866 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005867
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005868 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005869 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005870 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005871}
5872
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005873void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5874 SourceLocation ClassNameLoc) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005875 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005876 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005877 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005878 Results.EnterNewScope();
5879
5880 // Make sure that we ignore the class we're currently defining.
5881 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005882 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005883 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00005884 Results.Ignore(CurClass);
5885
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005886 if (CodeCompleter->includeGlobals()) {
5887 // Add all classes.
5888 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5889 false, Results);
5890 }
5891
Douglas Gregor49c22a72009-11-18 16:26:39 +00005892 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005893
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005894 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005895 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005896 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005897}
5898
5899void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005900 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005901 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005902 CodeCompletionContext::CCC_Other);
Douglas Gregor49c22a72009-11-18 16:26:39 +00005903 Results.EnterNewScope();
5904
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005905 if (CodeCompleter->includeGlobals()) {
5906 // Add all unimplemented classes.
5907 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5908 true, Results);
5909 }
5910
Douglas Gregor49c22a72009-11-18 16:26:39 +00005911 Results.ExitScope();
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005912
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005913 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor2c595ad2011-07-30 06:55:39 +00005914 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005915 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00005916}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005917
5918void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005919 IdentifierInfo *ClassName,
5920 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005921 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005922
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005923 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005924 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00005925 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005926
5927 // Ignore any categories we find that have already been implemented by this
5928 // interface.
5929 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5930 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005931 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005932 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
Aaron Ballman3fe486a2014-03-13 21:23:55 +00005933 for (const auto *Cat : Class->visible_categories())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005934 CategoryNames.insert(Cat->getIdentifier());
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005935 }
5936
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005937 // Add all of the categories we know about.
5938 Results.EnterNewScope();
5939 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Aaron Ballman629afae2014-03-07 19:56:05 +00005940 for (const auto *D : TU->decls())
5941 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
David Blaikie82e95a32014-11-19 07:49:47 +00005942 if (CategoryNames.insert(Category->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00005943 Results.AddResult(Result(Category, Results.getBasePriority(Category),
5944 nullptr),
5945 CurContext, nullptr, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005946 Results.ExitScope();
5947
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005948 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005949 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005950 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005951}
5952
5953void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005954 IdentifierInfo *ClassName,
5955 SourceLocation ClassNameLoc) {
John McCall276321a2010-08-25 06:19:51 +00005956 typedef CodeCompletionResult Result;
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005957
5958 // Find the corresponding interface. If we couldn't find the interface, the
5959 // program itself is ill-formed. However, we'll try to be helpful still by
5960 // providing the list of all of the categories we know about.
5961 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005962 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005963 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5964 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005965 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005966
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005967 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005968 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor21325842011-07-07 16:03:39 +00005969 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005970
5971 // Add all of the categories that have have corresponding interface
5972 // declarations in this class and any of its superclasses, except for
5973 // already-implemented categories in the class itself.
5974 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5975 Results.EnterNewScope();
5976 bool IgnoreImplemented = true;
5977 while (Class) {
Aaron Ballman3fe486a2014-03-13 21:23:55 +00005978 for (const auto *Cat : Class->visible_categories()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005979 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
David Blaikie82e95a32014-11-19 07:49:47 +00005980 CategoryNames.insert(Cat->getIdentifier()).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00005981 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
5982 CurContext, nullptr, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005983 }
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005984
5985 Class = Class->getSuperClass();
5986 IgnoreImplemented = false;
5987 }
5988 Results.ExitScope();
5989
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005990 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor21325842011-07-07 16:03:39 +00005991 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00005992 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00005993}
Douglas Gregor5d649882009-11-18 22:32:06 +00005994
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00005995void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00005997 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00005998 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00005999
6000 // Figure out where this @synthesize lives.
6001 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006002 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006003 if (!Container ||
6004 (!isa<ObjCImplementationDecl>(Container) &&
6005 !isa<ObjCCategoryImplDecl>(Container)))
6006 return;
6007
6008 // Ignore any properties that have already been implemented.
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006009 Container = getContainerDef(Container);
Aaron Ballman629afae2014-03-07 19:56:05 +00006010 for (const auto *D : Container->decls())
6011 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregor5d649882009-11-18 22:32:06 +00006012 Results.Ignore(PropertyImpl->getPropertyDecl());
6013
6014 // Add any properties that we find.
Douglas Gregorb888acf2010-12-09 23:01:55 +00006015 AddedPropertiesSet AddedProperties;
Douglas Gregor5d649882009-11-18 22:32:06 +00006016 Results.EnterNewScope();
6017 if (ObjCImplementationDecl *ClassImpl
6018 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor95147142011-05-05 15:50:42 +00006019 AddObjCProperties(ClassImpl->getClassInterface(), false,
6020 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregorb888acf2010-12-09 23:01:55 +00006021 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006022 else
6023 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor95147142011-05-05 15:50:42 +00006024 false, /*AllowNullaryMethods=*/false, CurContext,
6025 AddedProperties, Results);
Douglas Gregor5d649882009-11-18 22:32:06 +00006026 Results.ExitScope();
6027
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006028 HandleCodeCompleteResults(this, CodeCompleter,
6029 CodeCompletionContext::CCC_Other,
6030 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006031}
6032
6033void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006034 IdentifierInfo *PropertyName) {
John McCall276321a2010-08-25 06:19:51 +00006035 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006036 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006037 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006038 CodeCompletionContext::CCC_Other);
Douglas Gregor5d649882009-11-18 22:32:06 +00006039
6040 // Figure out where this @synthesize lives.
6041 ObjCContainerDecl *Container
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006042 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor5d649882009-11-18 22:32:06 +00006043 if (!Container ||
6044 (!isa<ObjCImplementationDecl>(Container) &&
6045 !isa<ObjCCategoryImplDecl>(Container)))
6046 return;
6047
6048 // Figure out which interface we're looking into.
Craig Topperc3ec1492014-05-26 06:22:03 +00006049 ObjCInterfaceDecl *Class = nullptr;
Douglas Gregor5d649882009-11-18 22:32:06 +00006050 if (ObjCImplementationDecl *ClassImpl
6051 = dyn_cast<ObjCImplementationDecl>(Container))
6052 Class = ClassImpl->getClassInterface();
6053 else
6054 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6055 ->getClassInterface();
6056
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006057 // Determine the type of the property we're synthesizing.
6058 QualType PropertyType = Context.getObjCIdType();
6059 if (Class) {
6060 if (ObjCPropertyDecl *Property
6061 = Class->FindPropertyDeclaration(PropertyName)) {
6062 PropertyType
6063 = Property->getType().getNonReferenceType().getUnqualifiedType();
6064
6065 // Give preference to ivars
6066 Results.setPreferredType(PropertyType);
6067 }
6068 }
6069
Douglas Gregor5d649882009-11-18 22:32:06 +00006070 // Add all of the instance variables in this class and its superclasses.
6071 Results.EnterNewScope();
Douglas Gregor331faa02011-04-18 14:13:53 +00006072 bool SawSimilarlyNamedIvar = false;
6073 std::string NameWithPrefix;
6074 NameWithPrefix += '_';
Benjamin Kramer632500c2011-07-26 16:59:25 +00006075 NameWithPrefix += PropertyName->getName();
Douglas Gregor331faa02011-04-18 14:13:53 +00006076 std::string NameWithSuffix = PropertyName->getName().str();
6077 NameWithSuffix += '_';
Douglas Gregor5d649882009-11-18 22:32:06 +00006078 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006079 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6080 Ivar = Ivar->getNextIvar()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006081 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6082 CurContext, nullptr, false);
6083
Douglas Gregor331faa02011-04-18 14:13:53 +00006084 // Determine whether we've seen an ivar with a name similar to the
6085 // property.
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006086 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregor331faa02011-04-18 14:13:53 +00006087 NameWithPrefix == Ivar->getName() ||
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006088 NameWithSuffix == Ivar->getName())) {
Douglas Gregor331faa02011-04-18 14:13:53 +00006089 SawSimilarlyNamedIvar = true;
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006090
6091 // Reduce the priority of this result by one, to give it a slight
6092 // advantage over other results whose names don't match so closely.
6093 if (Results.size() &&
6094 Results.data()[Results.size() - 1].Kind
6095 == CodeCompletionResult::RK_Declaration &&
6096 Results.data()[Results.size() - 1].Declaration == Ivar)
6097 Results.data()[Results.size() - 1].Priority--;
6098 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006099 }
Douglas Gregor5d649882009-11-18 22:32:06 +00006100 }
Douglas Gregor331faa02011-04-18 14:13:53 +00006101
6102 if (!SawSimilarlyNamedIvar) {
6103 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006104 // an ivar of the appropriate type.
6105 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregor331faa02011-04-18 14:13:53 +00006106 typedef CodeCompletionResult Result;
6107 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006108 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6109 Priority,CXAvailability_Available);
Douglas Gregor331faa02011-04-18 14:13:53 +00006110
Douglas Gregor75acd922011-09-27 23:30:47 +00006111 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor6c7a9ee2011-04-18 14:40:46 +00006112 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006113 Policy, Allocator));
Douglas Gregor331faa02011-04-18 14:13:53 +00006114 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6115 Results.AddResult(Result(Builder.TakeString(), Priority,
6116 CXCursor_ObjCIvarDecl));
6117 }
6118
Douglas Gregor5d649882009-11-18 22:32:06 +00006119 Results.ExitScope();
6120
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006121 HandleCodeCompleteResults(this, CodeCompleter,
6122 CodeCompletionContext::CCC_Other,
6123 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00006124}
Douglas Gregor636a61e2010-04-07 00:21:17 +00006125
Douglas Gregor416b5752010-08-25 01:08:01 +00006126// Mapping from selectors to the methods that implement that selector, along
6127// with the "in original class" flag.
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006128typedef llvm::DenseMap<
6129 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006130
6131/// \brief Find all of the methods that reside in the given container
6132/// (and its superclasses, protocols, etc.) that meet the given
6133/// criteria. Insert those methods into the map of known methods,
6134/// indexed by selector so they can be easily found.
6135static void FindImplementableMethods(ASTContext &Context,
6136 ObjCContainerDecl *Container,
6137 bool WantInstanceMethods,
6138 QualType ReturnType,
Douglas Gregor416b5752010-08-25 01:08:01 +00006139 KnownMethodsMap &KnownMethods,
6140 bool InOriginalClass = true) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006141 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006142 // Make sure we have a definition; that's what we'll walk.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006143 if (!IFace->hasDefinition())
6144 return;
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006145
6146 IFace = IFace->getDefinition();
6147 Container = IFace;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00006148
Douglas Gregor636a61e2010-04-07 00:21:17 +00006149 const ObjCList<ObjCProtocolDecl> &Protocols
6150 = IFace->getReferencedProtocols();
6151 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006152 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006153 I != E; ++I)
6154 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006155 KnownMethods, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006156
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006157 // Add methods from any class extensions and categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00006158 for (auto *Cat : IFace->visible_categories()) {
6159 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006160 KnownMethods, false);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00006161 }
6162
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006163 // Visit the superclass.
6164 if (IFace->getSuperClass())
6165 FindImplementableMethods(Context, IFace->getSuperClass(),
6166 WantInstanceMethods, ReturnType,
6167 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006168 }
6169
6170 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6171 // Recurse into protocols.
6172 const ObjCList<ObjCProtocolDecl> &Protocols
6173 = Category->getReferencedProtocols();
6174 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006175 E = Protocols.end();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006176 I != E; ++I)
6177 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006178 KnownMethods, InOriginalClass);
6179
6180 // If this category is the original class, jump to the interface.
6181 if (InOriginalClass && Category->getClassInterface())
6182 FindImplementableMethods(Context, Category->getClassInterface(),
6183 WantInstanceMethods, ReturnType, KnownMethods,
6184 false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006185 }
6186
6187 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor9b4f3702012-06-12 13:44:08 +00006188 // Make sure we have a definition; that's what we'll walk.
6189 if (!Protocol->hasDefinition())
6190 return;
6191 Protocol = Protocol->getDefinition();
6192 Container = Protocol;
6193
6194 // Recurse into protocols.
6195 const ObjCList<ObjCProtocolDecl> &Protocols
6196 = Protocol->getReferencedProtocols();
6197 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6198 E = Protocols.end();
6199 I != E; ++I)
6200 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6201 KnownMethods, false);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006202 }
6203
6204 // Add methods in this container. This operation occurs last because
6205 // we want the methods from this container to override any methods
6206 // we've previously seen with the same selector.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006207 for (auto *M : Container->methods()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006208 if (M->isInstanceMethod() == WantInstanceMethods) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006209 if (!ReturnType.isNull() &&
Alp Toker314cc812014-01-25 16:55:45 +00006210 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
Douglas Gregor636a61e2010-04-07 00:21:17 +00006211 continue;
6212
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006213 KnownMethods[M->getSelector()] =
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006214 KnownMethodsMap::mapped_type(M, InOriginalClass);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006215 }
6216 }
6217}
6218
Douglas Gregor669a25a2011-02-17 00:22:45 +00006219/// \brief Add the parenthesized return or parameter type chunk to a code
6220/// completion string.
6221static void AddObjCPassingTypeChunk(QualType Type,
Douglas Gregor29979142012-04-10 18:35:07 +00006222 unsigned ObjCDeclQuals,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006223 ASTContext &Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006224 const PrintingPolicy &Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006225 CodeCompletionBuilder &Builder) {
6226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor29979142012-04-10 18:35:07 +00006227 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6228 if (!Quals.empty())
6229 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Douglas Gregor75acd922011-09-27 23:30:47 +00006230 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006231 Builder.getAllocator()));
6232 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6233}
6234
6235/// \brief Determine whether the given class is or inherits from a class by
6236/// the given name.
6237static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006238 StringRef Name) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006239 if (!Class)
6240 return false;
6241
6242 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6243 return true;
6244
6245 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6246}
6247
6248/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6249/// Key-Value Observing (KVO).
6250static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6251 bool IsInstanceMethod,
6252 QualType ReturnType,
6253 ASTContext &Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00006254 VisitedSelectorSet &KnownSelectors,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006255 ResultBuilder &Results) {
6256 IdentifierInfo *PropName = Property->getIdentifier();
6257 if (!PropName || PropName->getLength() == 0)
6258 return;
6259
Douglas Gregor75acd922011-09-27 23:30:47 +00006260 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6261
Douglas Gregor669a25a2011-02-17 00:22:45 +00006262 // Builder that will create each code completion.
6263 typedef CodeCompletionResult Result;
6264 CodeCompletionAllocator &Allocator = Results.getAllocator();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006265 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Douglas Gregor669a25a2011-02-17 00:22:45 +00006266
6267 // The selector table.
6268 SelectorTable &Selectors = Context.Selectors;
6269
6270 // The property name, copied into the code completion allocation region
6271 // on demand.
6272 struct KeyHolder {
6273 CodeCompletionAllocator &Allocator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006274 StringRef Key;
Douglas Gregor669a25a2011-02-17 00:22:45 +00006275 const char *CopiedKey;
Craig Topperc3ec1492014-05-26 06:22:03 +00006276
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006277 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Craig Topperc3ec1492014-05-26 06:22:03 +00006278 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6279
Douglas Gregor669a25a2011-02-17 00:22:45 +00006280 operator const char *() {
6281 if (CopiedKey)
6282 return CopiedKey;
6283
6284 return CopiedKey = Allocator.CopyString(Key);
6285 }
6286 } Key(Allocator, PropName->getName());
6287
6288 // The uppercased name of the property name.
6289 std::string UpperKey = PropName->getName();
6290 if (!UpperKey.empty())
Jordan Rose4938f272013-02-09 10:09:43 +00006291 UpperKey[0] = toUppercase(UpperKey[0]);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006292
6293 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6294 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6295 Property->getType());
6296 bool ReturnTypeMatchesVoid
6297 = ReturnType.isNull() || ReturnType->isVoidType();
6298
6299 // Add the normal accessor -(type)key.
6300 if (IsInstanceMethod &&
David Blaikie82e95a32014-11-19 07:49:47 +00006301 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
Douglas Gregor669a25a2011-02-17 00:22:45 +00006302 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6303 if (ReturnType.isNull())
Douglas Gregor29979142012-04-10 18:35:07 +00006304 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6305 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006306
6307 Builder.AddTypedTextChunk(Key);
6308 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6309 CXCursor_ObjCInstanceMethodDecl));
6310 }
6311
6312 // If we have an integral or boolean property (or the user has provided
6313 // an integral or boolean return type), add the accessor -(type)isKey.
6314 if (IsInstanceMethod &&
6315 ((!ReturnType.isNull() &&
6316 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6317 (ReturnType.isNull() &&
6318 (Property->getType()->isIntegerType() ||
6319 Property->getType()->isBooleanType())))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006320 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006321 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006322 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6323 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006324 if (ReturnType.isNull()) {
6325 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6326 Builder.AddTextChunk("BOOL");
6327 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6328 }
6329
6330 Builder.AddTypedTextChunk(
6331 Allocator.CopyString(SelectorId->getName()));
6332 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6333 CXCursor_ObjCInstanceMethodDecl));
6334 }
6335 }
6336
6337 // Add the normal mutator.
6338 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6339 !Property->getSetterMethodDecl()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006340 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006341 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006342 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006343 if (ReturnType.isNull()) {
6344 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6345 Builder.AddTextChunk("void");
6346 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6347 }
6348
6349 Builder.AddTypedTextChunk(
6350 Allocator.CopyString(SelectorId->getName()));
6351 Builder.AddTypedTextChunk(":");
Douglas Gregor29979142012-04-10 18:35:07 +00006352 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6353 Context, Policy, Builder);
Douglas Gregor669a25a2011-02-17 00:22:45 +00006354 Builder.AddTextChunk(Key);
6355 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6356 CXCursor_ObjCInstanceMethodDecl));
6357 }
6358 }
6359
6360 // Indexed and unordered accessors
6361 unsigned IndexedGetterPriority = CCP_CodePattern;
6362 unsigned IndexedSetterPriority = CCP_CodePattern;
6363 unsigned UnorderedGetterPriority = CCP_CodePattern;
6364 unsigned UnorderedSetterPriority = CCP_CodePattern;
6365 if (const ObjCObjectPointerType *ObjCPointer
6366 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6367 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6368 // If this interface type is not provably derived from a known
6369 // collection, penalize the corresponding completions.
6370 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6371 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6372 if (!InheritsFromClassNamed(IFace, "NSArray"))
6373 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6374 }
6375
6376 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6377 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6378 if (!InheritsFromClassNamed(IFace, "NSSet"))
6379 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6380 }
6381 }
6382 } else {
6383 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6384 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6385 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6386 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6387 }
6388
6389 // Add -(NSUInteger)countOf<key>
6390 if (IsInstanceMethod &&
6391 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006392 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006393 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006394 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6395 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006396 if (ReturnType.isNull()) {
6397 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6398 Builder.AddTextChunk("NSUInteger");
6399 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6400 }
6401
6402 Builder.AddTypedTextChunk(
6403 Allocator.CopyString(SelectorId->getName()));
6404 Results.AddResult(Result(Builder.TakeString(),
6405 std::min(IndexedGetterPriority,
6406 UnorderedGetterPriority),
6407 CXCursor_ObjCInstanceMethodDecl));
6408 }
6409 }
6410
6411 // Indexed getters
6412 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6413 if (IsInstanceMethod &&
6414 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006415 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006416 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006417 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006418 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006419 if (ReturnType.isNull()) {
6420 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6421 Builder.AddTextChunk("id");
6422 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6423 }
6424
6425 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6426 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6427 Builder.AddTextChunk("NSUInteger");
6428 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6429 Builder.AddTextChunk("index");
6430 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6431 CXCursor_ObjCInstanceMethodDecl));
6432 }
6433 }
6434
6435 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6436 if (IsInstanceMethod &&
6437 (ReturnType.isNull() ||
6438 (ReturnType->isObjCObjectPointerType() &&
6439 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6440 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6441 ->getName() == "NSArray"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006442 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006443 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006444 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006445 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006446 if (ReturnType.isNull()) {
6447 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6448 Builder.AddTextChunk("NSArray *");
6449 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6450 }
6451
6452 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6453 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6454 Builder.AddTextChunk("NSIndexSet *");
6455 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6456 Builder.AddTextChunk("indexes");
6457 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6458 CXCursor_ObjCInstanceMethodDecl));
6459 }
6460 }
6461
6462 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6463 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006464 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006465 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006466 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006467 &Context.Idents.get("range")
6468 };
6469
David Blaikie82e95a32014-11-19 07:49:47 +00006470 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006471 if (ReturnType.isNull()) {
6472 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6473 Builder.AddTextChunk("void");
6474 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6475 }
6476
6477 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6478 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6479 Builder.AddPlaceholderChunk("object-type");
6480 Builder.AddTextChunk(" **");
6481 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6482 Builder.AddTextChunk("buffer");
6483 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6484 Builder.AddTypedTextChunk("range:");
6485 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6486 Builder.AddTextChunk("NSRange");
6487 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6488 Builder.AddTextChunk("inRange");
6489 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6490 CXCursor_ObjCInstanceMethodDecl));
6491 }
6492 }
6493
6494 // Mutable indexed accessors
6495
6496 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6497 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006498 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006499 IdentifierInfo *SelectorIds[2] = {
6500 &Context.Idents.get("insertObject"),
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006501 &Context.Idents.get(SelectorName)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006502 };
6503
David Blaikie82e95a32014-11-19 07:49:47 +00006504 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006505 if (ReturnType.isNull()) {
6506 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6507 Builder.AddTextChunk("void");
6508 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6509 }
6510
6511 Builder.AddTypedTextChunk("insertObject:");
6512 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6513 Builder.AddPlaceholderChunk("object-type");
6514 Builder.AddTextChunk(" *");
6515 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6516 Builder.AddTextChunk("object");
6517 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6518 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6519 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6520 Builder.AddPlaceholderChunk("NSUInteger");
6521 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6522 Builder.AddTextChunk("index");
6523 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6524 CXCursor_ObjCInstanceMethodDecl));
6525 }
6526 }
6527
6528 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6529 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006530 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006531 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006532 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006533 &Context.Idents.get("atIndexes")
6534 };
6535
David Blaikie82e95a32014-11-19 07:49:47 +00006536 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006537 if (ReturnType.isNull()) {
6538 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6539 Builder.AddTextChunk("void");
6540 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6541 }
6542
6543 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6544 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6545 Builder.AddTextChunk("NSArray *");
6546 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6547 Builder.AddTextChunk("array");
6548 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6549 Builder.AddTypedTextChunk("atIndexes:");
6550 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6551 Builder.AddPlaceholderChunk("NSIndexSet *");
6552 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6553 Builder.AddTextChunk("indexes");
6554 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6555 CXCursor_ObjCInstanceMethodDecl));
6556 }
6557 }
6558
6559 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6560 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006561 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006562 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006563 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006564 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006565 if (ReturnType.isNull()) {
6566 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6567 Builder.AddTextChunk("void");
6568 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6569 }
6570
6571 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6572 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6573 Builder.AddTextChunk("NSUInteger");
6574 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6575 Builder.AddTextChunk("index");
6576 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6577 CXCursor_ObjCInstanceMethodDecl));
6578 }
6579 }
6580
6581 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6582 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006583 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006584 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006585 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006586 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006587 if (ReturnType.isNull()) {
6588 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6589 Builder.AddTextChunk("void");
6590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6591 }
6592
6593 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6594 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6595 Builder.AddTextChunk("NSIndexSet *");
6596 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6597 Builder.AddTextChunk("indexes");
6598 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6599 CXCursor_ObjCInstanceMethodDecl));
6600 }
6601 }
6602
6603 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6604 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006605 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006606 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006607 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006608 &Context.Idents.get(SelectorName),
Douglas Gregor669a25a2011-02-17 00:22:45 +00006609 &Context.Idents.get("withObject")
6610 };
6611
David Blaikie82e95a32014-11-19 07:49:47 +00006612 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006613 if (ReturnType.isNull()) {
6614 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6615 Builder.AddTextChunk("void");
6616 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6617 }
6618
6619 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6620 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6621 Builder.AddPlaceholderChunk("NSUInteger");
6622 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6623 Builder.AddTextChunk("index");
6624 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6625 Builder.AddTypedTextChunk("withObject:");
6626 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6627 Builder.AddTextChunk("id");
6628 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6629 Builder.AddTextChunk("object");
6630 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6631 CXCursor_ObjCInstanceMethodDecl));
6632 }
6633 }
6634
6635 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6636 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006637 std::string SelectorName1
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006638 = (Twine("replace") + UpperKey + "AtIndexes").str();
6639 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor669a25a2011-02-17 00:22:45 +00006640 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006641 &Context.Idents.get(SelectorName1),
6642 &Context.Idents.get(SelectorName2)
Douglas Gregor669a25a2011-02-17 00:22:45 +00006643 };
6644
David Blaikie82e95a32014-11-19 07:49:47 +00006645 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006646 if (ReturnType.isNull()) {
6647 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6648 Builder.AddTextChunk("void");
6649 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6650 }
6651
6652 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6653 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6654 Builder.AddPlaceholderChunk("NSIndexSet *");
6655 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6656 Builder.AddTextChunk("indexes");
6657 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6658 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6659 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6660 Builder.AddTextChunk("NSArray *");
6661 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6662 Builder.AddTextChunk("array");
6663 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6664 CXCursor_ObjCInstanceMethodDecl));
6665 }
6666 }
6667
6668 // Unordered getters
6669 // - (NSEnumerator *)enumeratorOfKey
6670 if (IsInstanceMethod &&
6671 (ReturnType.isNull() ||
6672 (ReturnType->isObjCObjectPointerType() &&
6673 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6674 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6675 ->getName() == "NSEnumerator"))) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006676 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006677 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006678 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6679 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006680 if (ReturnType.isNull()) {
6681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6682 Builder.AddTextChunk("NSEnumerator *");
6683 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6684 }
6685
6686 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6687 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6688 CXCursor_ObjCInstanceMethodDecl));
6689 }
6690 }
6691
6692 // - (type *)memberOfKey:(type *)object
6693 if (IsInstanceMethod &&
6694 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006695 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006696 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006697 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006698 if (ReturnType.isNull()) {
6699 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6700 Builder.AddPlaceholderChunk("object-type");
6701 Builder.AddTextChunk(" *");
6702 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6703 }
6704
6705 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6706 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6707 if (ReturnType.isNull()) {
6708 Builder.AddPlaceholderChunk("object-type");
6709 Builder.AddTextChunk(" *");
6710 } else {
6711 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor75acd922011-09-27 23:30:47 +00006712 Policy,
Douglas Gregor669a25a2011-02-17 00:22:45 +00006713 Builder.getAllocator()));
6714 }
6715 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6716 Builder.AddTextChunk("object");
6717 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6718 CXCursor_ObjCInstanceMethodDecl));
6719 }
6720 }
6721
6722 // Mutable unordered accessors
6723 // - (void)addKeyObject:(type *)object
6724 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006725 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006726 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006727 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006728 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006729 if (ReturnType.isNull()) {
6730 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6731 Builder.AddTextChunk("void");
6732 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6733 }
6734
6735 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6736 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6737 Builder.AddPlaceholderChunk("object-type");
6738 Builder.AddTextChunk(" *");
6739 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6740 Builder.AddTextChunk("object");
6741 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6742 CXCursor_ObjCInstanceMethodDecl));
6743 }
6744 }
6745
6746 // - (void)addKey:(NSSet *)objects
6747 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006749 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006750 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006751 if (ReturnType.isNull()) {
6752 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6753 Builder.AddTextChunk("void");
6754 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6755 }
6756
6757 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6758 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6759 Builder.AddTextChunk("NSSet *");
6760 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6761 Builder.AddTextChunk("objects");
6762 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6763 CXCursor_ObjCInstanceMethodDecl));
6764 }
6765 }
6766
6767 // - (void)removeKeyObject:(type *)object
6768 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006769 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006770 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006771 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006772 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006773 if (ReturnType.isNull()) {
6774 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6775 Builder.AddTextChunk("void");
6776 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6777 }
6778
6779 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6780 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6781 Builder.AddPlaceholderChunk("object-type");
6782 Builder.AddTextChunk(" *");
6783 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6784 Builder.AddTextChunk("object");
6785 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6786 CXCursor_ObjCInstanceMethodDecl));
6787 }
6788 }
6789
6790 // - (void)removeKey:(NSSet *)objects
6791 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006792 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006793 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006794 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006795 if (ReturnType.isNull()) {
6796 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6797 Builder.AddTextChunk("void");
6798 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6799 }
6800
6801 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6802 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6803 Builder.AddTextChunk("NSSet *");
6804 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6805 Builder.AddTextChunk("objects");
6806 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6807 CXCursor_ObjCInstanceMethodDecl));
6808 }
6809 }
6810
6811 // - (void)intersectKey:(NSSet *)objects
6812 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006813 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006814 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006815 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006816 if (ReturnType.isNull()) {
6817 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6818 Builder.AddTextChunk("void");
6819 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6820 }
6821
6822 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6823 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6824 Builder.AddTextChunk("NSSet *");
6825 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6826 Builder.AddTextChunk("objects");
6827 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6828 CXCursor_ObjCInstanceMethodDecl));
6829 }
6830 }
6831
6832 // Key-Value Observing
6833 // + (NSSet *)keyPathsForValuesAffectingKey
6834 if (!IsInstanceMethod &&
6835 (ReturnType.isNull() ||
6836 (ReturnType->isObjCObjectPointerType() &&
6837 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6838 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6839 ->getName() == "NSSet"))) {
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006840 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006841 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor0e5d72f2011-02-17 03:19:26 +00006842 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006843 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6844 .second) {
Douglas Gregor669a25a2011-02-17 00:22:45 +00006845 if (ReturnType.isNull()) {
6846 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6847 Builder.AddTextChunk("NSSet *");
6848 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6849 }
6850
6851 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6852 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor857bcda2011-06-02 04:02:27 +00006853 CXCursor_ObjCClassMethodDecl));
6854 }
6855 }
6856
6857 // + (BOOL)automaticallyNotifiesObserversForKey
6858 if (!IsInstanceMethod &&
6859 (ReturnType.isNull() ||
6860 ReturnType->isIntegerType() ||
6861 ReturnType->isBooleanType())) {
6862 std::string SelectorName
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006863 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor857bcda2011-06-02 04:02:27 +00006864 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
David Blaikie82e95a32014-11-19 07:49:47 +00006865 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6866 .second) {
Douglas Gregor857bcda2011-06-02 04:02:27 +00006867 if (ReturnType.isNull()) {
6868 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6869 Builder.AddTextChunk("BOOL");
6870 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6871 }
6872
6873 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6874 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6875 CXCursor_ObjCClassMethodDecl));
Douglas Gregor669a25a2011-02-17 00:22:45 +00006876 }
6877 }
6878}
6879
Douglas Gregor636a61e2010-04-07 00:21:17 +00006880void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6881 bool IsInstanceMethod,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006882 ParsedType ReturnTy) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006883 // Determine the return type of the method we're declaring, if
6884 // provided.
6885 QualType ReturnType = GetTypeFromParser(ReturnTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00006886 Decl *IDecl = nullptr;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00006887 if (CurContext->isObjCContainer()) {
6888 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6889 IDecl = cast<Decl>(OCD);
6890 }
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006891 // Determine where we should start searching for methods.
Craig Topperc3ec1492014-05-26 06:22:03 +00006892 ObjCContainerDecl *SearchDecl = nullptr;
Douglas Gregor636a61e2010-04-07 00:21:17 +00006893 bool IsInImplementation = false;
John McCall48871652010-08-21 09:40:31 +00006894 if (Decl *D = IDecl) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006895 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6896 SearchDecl = Impl->getClassInterface();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006897 IsInImplementation = true;
6898 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006899 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006900 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregor636a61e2010-04-07 00:21:17 +00006901 IsInImplementation = true;
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006902 } else
Douglas Gregor636a61e2010-04-07 00:21:17 +00006903 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006904 }
6905
6906 if (!SearchDecl && S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00006907 if (DeclContext *DC = S->getEntity())
Douglas Gregor636a61e2010-04-07 00:21:17 +00006908 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006909 }
6910
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006911 if (!SearchDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00006912 HandleCodeCompleteResults(this, CodeCompleter,
6913 CodeCompletionContext::CCC_Other,
Craig Topperc3ec1492014-05-26 06:22:03 +00006914 nullptr, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006915 return;
6916 }
6917
6918 // Find all of the methods that we could declare/implement here.
6919 KnownMethodsMap KnownMethods;
6920 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregor1b035bb2010-10-18 18:21:28 +00006921 ReturnType, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006922
Douglas Gregor636a61e2010-04-07 00:21:17 +00006923 // Add declarations or definitions for each of the known methods.
John McCall276321a2010-08-25 06:19:51 +00006924 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006925 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006926 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006927 CodeCompletionContext::CCC_Other);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006928 Results.EnterNewScope();
Douglas Gregor75acd922011-09-27 23:30:47 +00006929 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006930 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6931 MEnd = KnownMethods.end();
6932 M != MEnd; ++M) {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00006933 ObjCMethodDecl *Method = M->second.getPointer();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00006934 CodeCompletionBuilder Builder(Results.getAllocator(),
6935 Results.getCodeCompletionTUInfo());
Douglas Gregor636a61e2010-04-07 00:21:17 +00006936
6937 // If the result type was not already provided, add it to the
6938 // pattern as (type).
Douglas Gregor669a25a2011-02-17 00:22:45 +00006939 if (ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00006940 AddObjCPassingTypeChunk(Method->getReturnType(),
6941 Method->getObjCDeclQualifier(), Context, Policy,
6942 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006943
6944 Selector Sel = Method->getSelector();
6945
6946 // Add the first part of the selector to the pattern.
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006947 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006948 Sel.getNameForSlot(0)));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006949
6950 // Add parameters to the pattern.
6951 unsigned I = 0;
6952 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6953 PEnd = Method->param_end();
6954 P != PEnd; (void)++P, ++I) {
6955 // Add the part of the selector name.
6956 if (I == 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006957 Builder.AddTypedTextChunk(":");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006958 else if (I < Sel.getNumArgs()) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006959 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6960 Builder.AddTypedTextChunk(
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00006961 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006962 } else
6963 break;
6964
6965 // Add the parameter type.
Douglas Gregor29979142012-04-10 18:35:07 +00006966 AddObjCPassingTypeChunk((*P)->getOriginalType(),
6967 (*P)->getObjCDeclQualifier(),
6968 Context, Policy,
Douglas Gregor75acd922011-09-27 23:30:47 +00006969 Builder);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006970
6971 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00006972 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregor636a61e2010-04-07 00:21:17 +00006973 }
6974
6975 if (Method->isVariadic()) {
6976 if (Method->param_size() > 0)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006977 Builder.AddChunk(CodeCompletionString::CK_Comma);
6978 Builder.AddTextChunk("...");
Douglas Gregor400f5972010-08-31 05:13:43 +00006979 }
Douglas Gregor636a61e2010-04-07 00:21:17 +00006980
Douglas Gregord37c59d2010-05-28 00:57:46 +00006981 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006982 // We will be defining the method here, so add a compound statement.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006983 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6984 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6985 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Alp Toker314cc812014-01-25 16:55:45 +00006986 if (!Method->getReturnType()->isVoidType()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00006987 // If the result type is not void, add a return clause.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006988 Builder.AddTextChunk("return");
6989 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6990 Builder.AddPlaceholderChunk("expression");
6991 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006992 } else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006993 Builder.AddPlaceholderChunk("statements");
Douglas Gregor636a61e2010-04-07 00:21:17 +00006994
Douglas Gregorb278aaf2011-02-01 19:23:04 +00006995 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6996 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor636a61e2010-04-07 00:21:17 +00006997 }
6998
Douglas Gregor416b5752010-08-25 01:08:01 +00006999 unsigned Priority = CCP_CodePattern;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00007000 if (!M->second.getInt())
Douglas Gregor416b5752010-08-25 01:08:01 +00007001 Priority += CCD_InBaseClass;
7002
Douglas Gregor78254c82012-03-27 23:34:16 +00007003 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
Douglas Gregor636a61e2010-04-07 00:21:17 +00007004 }
7005
Douglas Gregor669a25a2011-02-17 00:22:45 +00007006 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7007 // the properties in this class and its categories.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007008 if (Context.getLangOpts().ObjC2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007009 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor669a25a2011-02-17 00:22:45 +00007010 Containers.push_back(SearchDecl);
7011
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007012 VisitedSelectorSet KnownSelectors;
7013 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7014 MEnd = KnownMethods.end();
7015 M != MEnd; ++M)
7016 KnownSelectors.insert(M->first);
7017
7018
Douglas Gregor669a25a2011-02-17 00:22:45 +00007019 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7020 if (!IFace)
7021 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7022 IFace = Category->getClassInterface();
7023
Aaron Ballman3fe486a2014-03-13 21:23:55 +00007024 if (IFace)
7025 for (auto *Cat : IFace->visible_categories())
7026 Containers.push_back(Cat);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007027
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007028 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
Aaron Ballmand174edf2014-03-13 19:11:50 +00007029 for (auto *P : Containers[I]->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00007030 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
Douglas Gregord4a8ced2011-05-04 23:50:46 +00007031 KnownSelectors, Results);
Douglas Gregor669a25a2011-02-17 00:22:45 +00007032 }
7033
Douglas Gregor636a61e2010-04-07 00:21:17 +00007034 Results.ExitScope();
7035
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007036 HandleCodeCompleteResults(this, CodeCompleter,
7037 CodeCompletionContext::CCC_Other,
7038 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00007039}
Douglas Gregor95887f92010-07-08 23:20:03 +00007040
7041void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7042 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00007043 bool AtParameterName,
John McCallba7bf592010-08-24 05:47:05 +00007044 ParsedType ReturnTy,
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007045 ArrayRef<IdentifierInfo *> SelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00007046 // If we have an external source, load the entire class method
Sebastian Redld44cd6a2010-08-18 23:57:06 +00007047 // pool from the AST file.
Douglas Gregor95887f92010-07-08 23:20:03 +00007048 if (ExternalSource) {
7049 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7050 I != N; ++I) {
7051 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00007052 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00007053 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00007054
7055 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00007056 }
7057 }
7058
7059 // Build the set of methods we can see.
John McCall276321a2010-08-25 06:19:51 +00007060 typedef CodeCompletionResult Result;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007061 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007062 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007063 CodeCompletionContext::CCC_Other);
Douglas Gregor95887f92010-07-08 23:20:03 +00007064
7065 if (ReturnTy)
7066 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00007067
Douglas Gregor95887f92010-07-08 23:20:03 +00007068 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00007069 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7070 MEnd = MethodPool.end();
7071 M != MEnd; ++M) {
7072 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7073 &M->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00007074 MethList && MethList->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007075 MethList = MethList->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00007076 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
Douglas Gregor95887f92010-07-08 23:20:03 +00007077 continue;
7078
Douglas Gregor45879692010-07-08 23:37:41 +00007079 if (AtParameterName) {
7080 // Suggest parameter names we've seen before.
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007081 unsigned NumSelIdents = SelIdents.size();
Nico Weber2e0c8f72014-12-27 03:58:08 +00007082 if (NumSelIdents &&
7083 NumSelIdents <= MethList->getMethod()->param_size()) {
7084 ParmVarDecl *Param =
7085 MethList->getMethod()->parameters()[NumSelIdents - 1];
Douglas Gregor45879692010-07-08 23:37:41 +00007086 if (Param->getIdentifier()) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007087 CodeCompletionBuilder Builder(Results.getAllocator(),
7088 Results.getCodeCompletionTUInfo());
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007089 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007090 Param->getIdentifier()->getName()));
7091 Results.AddResult(Builder.TakeString());
Douglas Gregor45879692010-07-08 23:37:41 +00007092 }
7093 }
7094
7095 continue;
7096 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007097
Nico Weber2e0c8f72014-12-27 03:58:08 +00007098 Result R(MethList->getMethod(),
7099 Results.getBasePriority(MethList->getMethod()), nullptr);
Dmitri Gribenko070a10e2013-06-16 03:47:57 +00007100 R.StartParameter = SelIdents.size();
Douglas Gregor95887f92010-07-08 23:20:03 +00007101 R.AllParametersAreInformative = false;
7102 R.DeclaringEntity = true;
7103 Results.MaybeAddResult(R, CurContext);
7104 }
7105 }
7106
7107 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00007108 HandleCodeCompleteResults(this, CodeCompleter,
7109 CodeCompletionContext::CCC_Other,
7110 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00007111}
Douglas Gregorb14904c2010-08-13 22:48:40 +00007112
Douglas Gregorec00a262010-08-24 22:20:20 +00007113void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007114 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007115 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007116 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007117 Results.EnterNewScope();
7118
7119 // #if <condition>
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007120 CodeCompletionBuilder Builder(Results.getAllocator(),
7121 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007122 Builder.AddTypedTextChunk("if");
7123 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7124 Builder.AddPlaceholderChunk("condition");
7125 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007126
7127 // #ifdef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007128 Builder.AddTypedTextChunk("ifdef");
7129 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7130 Builder.AddPlaceholderChunk("macro");
7131 Results.AddResult(Builder.TakeString());
7132
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007133 // #ifndef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007134 Builder.AddTypedTextChunk("ifndef");
7135 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7136 Builder.AddPlaceholderChunk("macro");
7137 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007138
7139 if (InConditional) {
7140 // #elif <condition>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007141 Builder.AddTypedTextChunk("elif");
7142 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7143 Builder.AddPlaceholderChunk("condition");
7144 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007145
7146 // #else
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007147 Builder.AddTypedTextChunk("else");
7148 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007149
7150 // #endif
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007151 Builder.AddTypedTextChunk("endif");
7152 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007153 }
7154
7155 // #include "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007156 Builder.AddTypedTextChunk("include");
7157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7158 Builder.AddTextChunk("\"");
7159 Builder.AddPlaceholderChunk("header");
7160 Builder.AddTextChunk("\"");
7161 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007162
7163 // #include <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007164 Builder.AddTypedTextChunk("include");
7165 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7166 Builder.AddTextChunk("<");
7167 Builder.AddPlaceholderChunk("header");
7168 Builder.AddTextChunk(">");
7169 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007170
7171 // #define <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007172 Builder.AddTypedTextChunk("define");
7173 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7174 Builder.AddPlaceholderChunk("macro");
7175 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007176
7177 // #define <macro>(<args>)
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007178 Builder.AddTypedTextChunk("define");
7179 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7180 Builder.AddPlaceholderChunk("macro");
7181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7182 Builder.AddPlaceholderChunk("args");
7183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7184 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007185
7186 // #undef <macro>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007187 Builder.AddTypedTextChunk("undef");
7188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7189 Builder.AddPlaceholderChunk("macro");
7190 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007191
7192 // #line <number>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007193 Builder.AddTypedTextChunk("line");
7194 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7195 Builder.AddPlaceholderChunk("number");
7196 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007197
7198 // #line <number> "filename"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007199 Builder.AddTypedTextChunk("line");
7200 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7201 Builder.AddPlaceholderChunk("number");
7202 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7203 Builder.AddTextChunk("\"");
7204 Builder.AddPlaceholderChunk("filename");
7205 Builder.AddTextChunk("\"");
7206 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007207
7208 // #error <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007209 Builder.AddTypedTextChunk("error");
7210 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7211 Builder.AddPlaceholderChunk("message");
7212 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007213
7214 // #pragma <arguments>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007215 Builder.AddTypedTextChunk("pragma");
7216 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7217 Builder.AddPlaceholderChunk("arguments");
7218 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007219
David Blaikiebbafb8a2012-03-11 07:00:24 +00007220 if (getLangOpts().ObjC1) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007221 // #import "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007222 Builder.AddTypedTextChunk("import");
7223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7224 Builder.AddTextChunk("\"");
7225 Builder.AddPlaceholderChunk("header");
7226 Builder.AddTextChunk("\"");
7227 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007228
7229 // #import <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007230 Builder.AddTypedTextChunk("import");
7231 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7232 Builder.AddTextChunk("<");
7233 Builder.AddPlaceholderChunk("header");
7234 Builder.AddTextChunk(">");
7235 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007236 }
7237
7238 // #include_next "header"
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007239 Builder.AddTypedTextChunk("include_next");
7240 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7241 Builder.AddTextChunk("\"");
7242 Builder.AddPlaceholderChunk("header");
7243 Builder.AddTextChunk("\"");
7244 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007245
7246 // #include_next <header>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007247 Builder.AddTypedTextChunk("include_next");
7248 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7249 Builder.AddTextChunk("<");
7250 Builder.AddPlaceholderChunk("header");
7251 Builder.AddTextChunk(">");
7252 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007253
7254 // #warning <message>
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007255 Builder.AddTypedTextChunk("warning");
7256 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7257 Builder.AddPlaceholderChunk("message");
7258 Results.AddResult(Builder.TakeString());
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007259
7260 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7261 // completions for them. And __include_macros is a Clang-internal extension
7262 // that we don't want to encourage anyone to use.
7263
7264 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7265 Results.ExitScope();
7266
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007267 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0de55ce2010-08-25 18:41:16 +00007268 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007269 Results.data(), Results.size());
7270}
7271
7272void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorec00a262010-08-24 22:20:20 +00007273 CodeCompleteOrdinaryName(S,
John McCallfaf5fb42010-08-26 23:41:50 +00007274 S->getFnParent()? Sema::PCC_RecoveryInFunction
7275 : Sema::PCC_Namespace);
Douglas Gregor3a7ad252010-08-24 19:08:16 +00007276}
7277
Douglas Gregorec00a262010-08-24 22:20:20 +00007278void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007279 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007280 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007281 IsDefinition? CodeCompletionContext::CCC_MacroName
7282 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor12785102010-08-24 20:21:13 +00007283 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7284 // Add just the names of macros, not their arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007285 CodeCompletionBuilder Builder(Results.getAllocator(),
7286 Results.getCodeCompletionTUInfo());
Douglas Gregor12785102010-08-24 20:21:13 +00007287 Results.EnterNewScope();
7288 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7289 MEnd = PP.macro_end();
7290 M != MEnd; ++M) {
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007291 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007292 M->first->getName()));
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00007293 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7294 CCP_CodePattern,
7295 CXCursor_MacroDefinition));
Douglas Gregor12785102010-08-24 20:21:13 +00007296 }
7297 Results.ExitScope();
7298 } else if (IsDefinition) {
7299 // FIXME: Can we detect when the user just wrote an include guard above?
7300 }
7301
Douglas Gregor0ac41382010-09-23 23:01:17 +00007302 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor12785102010-08-24 20:21:13 +00007303 Results.data(), Results.size());
7304}
7305
Douglas Gregorec00a262010-08-24 22:20:20 +00007306void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007307 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007308 CodeCompleter->getCodeCompletionTUInfo(),
Douglas Gregor0ac41382010-09-23 23:01:17 +00007309 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorec00a262010-08-24 22:20:20 +00007310
7311 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007312 AddMacroResults(PP, Results, true);
Douglas Gregorec00a262010-08-24 22:20:20 +00007313
7314 // defined (<macro>)
7315 Results.EnterNewScope();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007316 CodeCompletionBuilder Builder(Results.getAllocator(),
7317 Results.getCodeCompletionTUInfo());
Douglas Gregorb278aaf2011-02-01 19:23:04 +00007318 Builder.AddTypedTextChunk("defined");
7319 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7320 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7321 Builder.AddPlaceholderChunk("macro");
7322 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7323 Results.AddResult(Builder.TakeString());
Douglas Gregorec00a262010-08-24 22:20:20 +00007324 Results.ExitScope();
7325
7326 HandleCodeCompleteResults(this, CodeCompleter,
7327 CodeCompletionContext::CCC_PreprocessorExpression,
7328 Results.data(), Results.size());
7329}
7330
7331void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7332 IdentifierInfo *Macro,
7333 MacroInfo *MacroInfo,
7334 unsigned Argument) {
7335 // FIXME: In the future, we could provide "overload" results, much like we
7336 // do for function calls.
7337
Argyrios Kyrtzidis75f6cd22011-08-18 19:41:28 +00007338 // Now just ignore this. There will be another code-completion callback
7339 // for the expanded tokens.
Douglas Gregorec00a262010-08-24 22:20:20 +00007340}
7341
Douglas Gregor11583702010-08-25 17:04:25 +00007342void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +00007343 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorea736372010-08-25 17:10:00 +00007344 CodeCompletionContext::CCC_NaturalLanguage,
Craig Topperc3ec1492014-05-26 06:22:03 +00007345 nullptr, 0);
Douglas Gregor11583702010-08-25 17:04:25 +00007346}
7347
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00007348void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007349 CodeCompletionTUInfo &CCTUInfo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007350 SmallVectorImpl<CodeCompletionResult> &Results) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00007351 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7352 CodeCompletionContext::CCC_Recovery);
Douglas Gregor39982192010-08-15 06:18:01 +00007353 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7354 CodeCompletionDeclConsumer Consumer(Builder,
7355 Context.getTranslationUnitDecl());
7356 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7357 Consumer);
7358 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00007359
7360 if (!CodeCompleter || CodeCompleter->includeMacros())
Douglas Gregor8cb17462012-10-09 16:01:50 +00007361 AddMacroResults(PP, Builder, true);
Douglas Gregorb14904c2010-08-13 22:48:40 +00007362
7363 Results.clear();
7364 Results.insert(Results.end(),
7365 Builder.data(), Builder.data() + Builder.size());
7366}